package com.yem.wm.syn.eas;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.grapecity.documents.excel.J;
import com.yem.wm.utils.RequestEAS;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.entity.validate.ErrorLevel;
import kd.bos.entity.validate.ValidationErrorInfo;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import org.apache.commons.lang.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author 涛
 * @date 2023/11/24
     * 收款单-服务插件-财务确认同步EAS
 */
public class GathEringService  extends AbstractOperationServicePlugIn {
    private final static String TYPE = "10002";
    private final static Log log = LogFactory.getLog(GathEringService.class);
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_financeaffirm");
        fieldKeys.add("yem_bizdate");
        fieldKeys.add("yem_paymenttype");
        fieldKeys.add("yem_receipttype");
        fieldKeys.add("yem_currency");
        fieldKeys.add("yem_sumfundsreceived");
        fieldKeys.add("yem_exrate");
        fieldKeys.add("yem_sumfundsreceivedba");
        fieldKeys.add("yem_receiptname");
        fieldKeys.add("yem_moneytypetl_a");
        fieldKeys.add("yem_clearing");
        fieldKeys.add("yem_comegoman");
        fieldKeys.add("yem_receipttype_a");
        fieldKeys.add("yem_receivableamt");
        fieldKeys.add("yem_receivableamtbase");
        fieldKeys.add("yem_receiptdetail");
        fieldKeys.add("yem_org");
        fieldKeys.add("yem_easbillno");
        fieldKeys.add("creator");
    }


    @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        super.beginOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();

        JSONArray jsonArray = getJSON(dataEntities);
        if (jsonArray.size()==0) {
            return;
        }
        List<String> list = setData(dataEntities, jsonArray, TYPE);
        if (list.size()>0){
            e.setDataEntities(new DynamicObject[]{});
        }
    }

    public JSONArray getJSON(DynamicObject[] dataEntities) {

        JSONArray jsonArray = new JSONArray();
        for (DynamicObject dataEntitie: dataEntities) {
            DynamicObjectCollection receiptdetailcoll = dataEntitie.getDynamicObjectCollection("yem_receiptdetail");
            for (DynamicObject receiptdetail: receiptdetailcoll) {
                boolean yemIfeas = receiptdetail.getBoolean("yem_ifeas");
                if (yemIfeas){
                    continue;
                }
                JSONObject json = new JSONObject();
                String seq = receiptdetail.getString("seq");
                json.put("number",dataEntitie.getString("billno")+"_"+seq);
                //公司
                DynamicObject yem_org = dataEntitie.getDynamicObject("yem_org");
                json.put("company",setJson("number",yem_org.getString("number")));

                //单据日期
                SimpleDateFormat fmtDate = new SimpleDateFormat("yyyy-MM-dd");
                String yemBizdate = fmtDate.format(dataEntitie.getDate("yem_bizdate"));
                json.put("bizDate",yemBizdate);
                //收款类型
                DynamicObject yemReceipttype = dataEntitie.getDynamicObject("yem_receipttype");
                if (yemReceipttype!=null){
                    json.put("recBillType",setJson("number",yemReceipttype.getString("number")));
                }

                //paymentType 付款方式
                String yemPaymenttype = dataEntitie.getString("yem_paymenttype");
                //赊销
                if ("A".equals(yemPaymenttype)||"C".equals(yemPaymenttype)){
                    json.put("paymentType",setJson("number","002"));
                } else if ("B".equals(yemPaymenttype)) {
                    json.put("paymentType",setJson("number","001"));
                }

                //币别
                DynamicObject yemCurrency = dataEntitie.getDynamicObject("yem_currency");
                if (yemCurrency!=null){
                  //  json.put("currency",setJson("number",yemCurrency.getString("number")));
                    //end by zhouc  2024-03-13
                    json.put("currency",setJson("number",yemCurrency.getString("description")));
                }

                //实收金额合计
                json.put("actRecAmt",dataEntitie.getBigDecimal("yem_sumfundsreceived"));
                //汇率
                json.put("exchangeRate",dataEntitie.getBigDecimal("yem_exrate"));
                //折本位币
                json.put("actRecLocAmt",dataEntitie.getBigDecimal("yem_sumfundsreceivedba"));
                //收款账号
                json.put("payeeAccountBank",setJson("number",dataEntitie.getString("yem_receiptname")));
//                json.put("payeeAccountBank",setJson("number","ZGBB-001"));
                //结算方式
                DynamicObject yemClearing = dataEntitie.getDynamicObject("yem_clearing");
                if (yemClearing!=null){
                    json.put("settlementType",setJson("number",yemClearing.getString("number")));
                }

                // 对方科目
                DynamicObject yemMoneytypetlA = receiptdetail.getDynamicObject("yem_moneytypetl_a");
                if (yemMoneytypetlA!=null){
                    DynamicObject moneyType = BusinessDataServiceHelper.loadSingle(yemMoneytypetlA.getPkValue(), yemMoneytypetlA.getDynamicObjectType().getName());
                    json.put("oppAccount",setJson("number",moneyType.getString("yem_accountview")));
                }
                //往来户
                DynamicObject comegoman = dataEntitie.getDynamicObject("yem_comegoman");
                if (comegoman!=null){
                    //往来类型
                    String number = getPayerTypeNumer("客户");
                    json.put("payerType",setJson("number",number));
                    json.put("payerNumber",comegoman.getString("number"));
                    json.put("payerName",comegoman.getString("name"));
                }
                //申请人  creator
                DynamicObject creators = dataEntitie.getDynamicObject("creator");
                if (creators!=null){
                    //创建者
                    json.put("creator",setJson("number",creators.getString("number")));
                }


                JSONArray entrys = new JSONArray();
                JSONObject entryObj = new JSONObject();
                DynamicObject fkYemReceipttypeA = receiptdetail.getDynamicObject("yem_receipttype_a");
                if (fkYemReceipttypeA!=null){
                    entryObj.put("recBillType",setJson("number",fkYemReceipttypeA.getString("number")));
                }
                //应收金额
                BigDecimal yemReceivableamt = receiptdetail.getBigDecimal("yem_receivableamt");
                entryObj.put("amount",yemReceivableamt);
                //应收本位币金额
                BigDecimal yemReceivableamtbase = receiptdetail.getBigDecimal("yem_receivableamtbase");
                entryObj.put("localAmt",yemReceivableamtbase);
                //实收本位币金额
                entryObj.put("actualLocAmt",yemReceivableamtbase);
                //未锁定金额本位币
                entryObj.put("unLockAmt",yemReceivableamtbase);
                //未结算金额本位币
                entryObj.put("unVcLocAmount",yemReceivableamtbase);
                //实收金额
                entryObj.put("actualAmt",yemReceivableamt);
                //未锁定金额
                entryObj.put("unLockLocAmt",yemReceivableamt);
                //未结算金额
                entryObj.put("unVcAmount",yemReceivableamt);
                //对方科目
                if (yemMoneytypetlA!=null){
                    DynamicObject moneyType = BusinessDataServiceHelper.loadSingle(yemMoneytypetlA.getPkValue(), yemMoneytypetlA.getDynamicObjectType().getName());
                    entryObj.put("oppAccount",setJson("number",moneyType.getString("yem_accountview")));
                }
                entrys.add(entryObj);
                json.put("entries",entrys);
                jsonArray.add(json);
            }
        }
        log.debug("收款单-服务插件同步EAS:"+jsonArray.toJSONString());
        return jsonArray;
    }

    public static String getPayerTypeNumer(String s) {
        String sql = "select fnumber from T_BD_AsstActType where fname_l2 = '"+s+"'";
        List<Map<String, Object>> list = RequestEAS.exeSql(sql);
        String fnumber = null;
        for (Map<String, Object> map : list) {
            fnumber = (String) map.get("fnumber");
        }
        return fnumber;
    }


    public List setWebService(JSONArray json, DynamicObject[] datas, String type){
        String service = null;
        ArrayList<String> list = new ArrayList<>();

        try {
            service = RequestEAS.getService(json.toJSONString(), type);
        }catch (Exception e){
            log.error("同步EAS异常,请联系管理员"+e.getMessage());
            String msgE = "同步EAS异常,请联系管理员"+e.getMessage();
            for (DynamicObject data: datas) {
                DynamicObjectCollection receiptdetailcoll = data.getDynamicObjectCollection("yem_receiptdetail");
                for (DynamicObject receiptdetail:receiptdetailcoll) {
                    String seq = receiptdetail.getString("seq");
                    String billno = data.getString("billno")+"_"+seq;
                    list.add(billno);
                }
                addErrorInfo(msgE,data.getPkValue());
            }
            return list;
        }

        JSONObject jsonObject = JSON.parseObject(service);
        String status = jsonObject.getString("status");
        String msg = jsonObject.getString("msg");
        if (!"0".equals(status)){
            JSONArray billErrors = jsonObject.getJSONArray("billErrors");
            for (Object billError: billErrors) {
                JSONObject js = (JSONObject) billError;
                String number = js.getString("number");
                list.add(number);
                JSONArray errorMsgs = js.getJSONArray("errorMsgs");
                StringBuilder s = new StringBuilder();
                for (Object errorMsg: errorMsgs) {
                    s.append(errorMsg+";");
                }
                String msgE = number+"同步EAS失败:"+s;
                DynamicObject dynamicObject =
                        BusinessDataServiceHelper.loadSingle("yem_gathering_pro", new QFilter[]{new QFilter("billno", QCP.equals, number)});
                addErrorInfo(msgE,dynamicObject.getPkValue());
            }
            if (list.size()==0){
                String msgE = "同步EAS失败:"+msg;
                for (DynamicObject data: datas) {
                    DynamicObjectCollection receiptdetailcoll = data.getDynamicObjectCollection("yem_receiptdetail");
                    for (DynamicObject receiptdetail:receiptdetailcoll) {
                        String seq = receiptdetail.getString("seq");
                        String billno = data.getString("billno")+"_"+seq;
                        list.add(billno);
                    }
                    addErrorInfo(msgE,data.getPkValue());
                }
                return list;
            }
        }

        return list;
    }

    /**
     *
     * @param datas 实体
     * @param jsonArray
     * @return 过滤同步失败的数据
     */
    public List<String> setData(DynamicObject[] datas, JSONArray jsonArray, String type){
        List<String> list = setWebService(jsonArray,datas,type);
        List<String> listNum = new ArrayList<>();
        for (int i = 0; i < datas.length; i++) {
            DynamicObject info = datas[i];
            DynamicObjectCollection yemReceiptdetailcoll = info.getDynamicObjectCollection("yem_receiptdetail");
            for (DynamicObject yemReceiptdetail: yemReceiptdetailcoll) {
                String seq = yemReceiptdetail.getString("seq");
                String billno = info.getString("billno")+"_"+seq;
                listNum.add(billno);
            }
        }


        for (String number: list) {
            Predicate<String> predicate = num -> !StringUtils.equals(num,number);
            listNum = listNum.stream().filter(predicate).collect(Collectors.toList());
        }
        for (String nums: listNum) {
            String[] seqNum = nums.split("_"); //SKD-231017-00000035-1 //SKD-231017-00000035-3
            String seqNums = seqNum[0];
            String seq = seqNum[1];
            DynamicObject info = BusinessDataServiceHelper.loadSingle("yem_gathering_pro", new QFilter[]{new QFilter("billno", QCP.equals, seqNums)});
            DynamicObject yemReceiptdetail = info.getDynamicObjectCollection("yem_receiptdetail").get(Integer.parseInt(seq) - 1);
            yemReceiptdetail.set("yem_ifeas",true);
            yemReceiptdetail.set("yem_easbillno",nums);
            SaveServiceHelper.update(info);
        }

        return list;
    }

    public JSONObject setJson(String key, String value) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put(key, value);
        return jsonObject;
    }


    public void addErrorInfo(String message,Object pk){
        this.operationResult.addErrorInfo(
                new ValidationErrorInfo(
                        "",pk, 0,0,"err","同步EAS失败",message, ErrorLevel.Error));

    }
}
