package com.yem.wm.syn.eas.form;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.wm.syn.eas.GathEringService;
import com.yem.wm.syn.eas.submit.utils.FilterUtils;
import com.yem.wm.utils.RequestEAS;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.validate.ErrorLevel;
import kd.bos.entity.validate.ValidationErrorInfo;
import kd.bos.form.IFormView;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.form.operate.FormOperate;
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.function.Predicate;
import java.util.stream.Collectors;

public class GatheringForm extends AbstractBillPlugIn {
    private final static String TYPE = "10002";
    private final static Log log = LogFactory.getLog(GatheringForm.class);

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate source = (FormOperate) args.getSource();
        String operateKey = source.getOperateKey();
        if (!"synceas".equals(operateKey)) {
            return;
        }

        IFormView view = this.getView();
        IDataModel model = view.getModel();
        OperationStatus status = view.getFormShowParameter().getStatus();
        if (OperationStatus.ADDNEW == status) {
            return;
        }
        String billTypes = model.getValue("yem_billtypes").toString();


        //是否真实合同客户
        DynamicObject yemCompanyorg = (DynamicObject) model.getValue("yem_org");
        String orgname = yemCompanyorg.getString("name");

        String billno = model.getValue("billno").toString();
        DynamicObject customer = (DynamicObject) model.getValue("yem_comegoman");
        Boolean customers = FilterUtils.setCustomer(yemCompanyorg, customer);

        if (customers) {
            String customerNum = customer.getString("number");
            String msg = "单据编码:" + billno + "同步失败,财务组织" + orgname + "客户编码为:" + customerNum + "不存在,请在EAS核准";
            this.getView().showTipNotification(msg);
            args.cancel = true;
            return;
        }
        allsyneas(billTypes, args);
//        //获取单据体控件
//        EntryGrid entryGrid = this.getControl("yem_receiptdetail");
//        //获取选中行，数组为行号，从0开始int[]
//        int selectRows[] = entryGrid.getSelectRows();
//        //获取单据体数据集合
//        DynamicObjectCollection entity = this.getModel().getEntryEntity("yem_receiptdetail");
//        if (selectRows != null && selectRows.length > 0) {
//            DynamicObjectCollection collection = new DynamicObjectCollection();
//            for (int selectRow : selectRows) {
//                DynamicObject dynamicObject = entity.get(selectRow);  //获取选中行的单据体数据
//                //标准收款单
//                if ("A".equals(billTypes) || "B".equals(billTypes)) {
//                    collection.add(dynamicObject);
//                } else {
//                    String sourceeasbillno = dynamicObject.getString("yem_sourceeasbillno");
//                    DynamicObject[] yemReceiptdetails = BusinessDataServiceHelper.load(view.getEntityId(), "id,yem_billtypes,yem_receiptdetail,yem_receiptdetail.yem_ifeas,yem_receiptdetail.yem_sourceeasbillno", new QFilter[]{new QFilter("yem_receiptdetail.yem_sourceeasbillno", QCP.equals, sourceeasbillno)});
//                    for (int i = 0; i < yemReceiptdetails.length; i++) {
//                        DynamicObject yemReceiptdetail = yemReceiptdetails[i];
//                        String yem_billtypes = yemReceiptdetail.getString("yem_billtypes");
//                        //如果不是负向调整单
//                        if (!"B".equals(yem_billtypes)) {
//                            continue;
//                        }
//                        DynamicObjectCollection receiptdetailc = yemReceiptdetail.getDynamicObjectCollection("yem_receiptdetail");
//                        for (DynamicObject receiptdetail : receiptdetailc) {
//                            String yemSourceeasbillno = receiptdetail.getString("yem_sourceeasbillno");
//                            if (yemSourceeasbillno.equals(sourceeasbillno)) {
//                                boolean iseas = receiptdetail.getBoolean("yem_ifeas");
//                                if (iseas) {
//                                    collection.add(dynamicObject);
//                                }
//                            }
//                        }
//                    }
//                }
//
//            }
//            DynamicObject dataEntity = model.getDataEntity();
//            //collection 分录可以同步的数据
//            JSONArray jsonArray = getJSON(new DynamicObject[]{dataEntity}, collection);
//            if (jsonArray.size() == 0) {
//                this.getView().showTipNotification("没有可以同步的数据");
//                return;
//            }
//            List<String> list = setData(new DynamicObject[]{dataEntity}, collection, jsonArray, TYPE);
//            view.showSuccessNotification("同步完成");
//            this.getView().invokeOperation("refresh");
//        } else {
//            this.getView().showTipNotification("请选择分录行进行操作!");
//            args.cancel = true;
//        }
    }

    public void allsyneas(String billTypes, BeforeDoOperationEventArgs args) {
        IFormView view = this.getView();
        IDataModel model = view.getModel();
        DynamicObjectCollection collection = new DynamicObjectCollection();
        DynamicObject data = this.getModel().getDataEntity(true);
        DynamicObjectCollection yem_receiptdetail = data.getDynamicObjectCollection("yem_receiptdetail");
        for (int j = 0; j < yem_receiptdetail.size(); j++) {
            DynamicObject dynamicObject = yem_receiptdetail.get(j);
            boolean yem_ifeas = dynamicObject.getBoolean("yem_ifeas");
            //标准收款单
            if ("A".equals(billTypes) || "B".equals(billTypes)) {
                if (!yem_ifeas) {
                    collection.add(dynamicObject);
                }
            } else {
                String sourceeasbillno = dynamicObject.getString("yem_sourceeasbillno");
                DynamicObject[] yemReceiptdetails = BusinessDataServiceHelper.load(view.getEntityId(), "id,yem_billtypes,yem_receiptdetail,yem_receiptdetail.yem_ifeas,yem_receiptdetail.yem_sourceeasbillno", new QFilter[]{new QFilter("yem_receiptdetail.yem_sourceeasbillno", QCP.equals, sourceeasbillno)});
                for (int i = 0; i < yemReceiptdetails.length; i++) {
                    DynamicObject yemReceiptdetail = yemReceiptdetails[i];
                    String yem_billtypes = yemReceiptdetail.getString("yem_billtypes");
                    //如果不是负向调整单
                    if (!"B".equals(yem_billtypes)) {
                        continue;
                    }
                    DynamicObjectCollection receiptdetailc = yemReceiptdetail.getDynamicObjectCollection("yem_receiptdetail");
                    for (DynamicObject receiptdetail : receiptdetailc) {
                        String yemSourceeasbillno = receiptdetail.getString("yem_sourceeasbillno");
                        if (yemSourceeasbillno.equals(sourceeasbillno)) {
                            boolean iseas = receiptdetail.getBoolean("yem_ifeas");
                            if (iseas) {
                                collection.add(dynamicObject);
                            }
                        }
                    }
                }
            }
        }
        DynamicObject dataEntity = model.getDataEntity();
        //collection 分录可以同步的数据
        JSONArray jsonArray = getJSON(new DynamicObject[]{dataEntity}, collection);
        if (jsonArray.size() == 0) {
            this.getView().showTipNotification("没有可以同步的数据");
            return;
        }
        List<String> list = setData(new DynamicObject[]{dataEntity}, collection, jsonArray, TYPE);
        view.showSuccessNotification("同步完成");
        this.getView().invokeOperation("refresh");
    }


    public JSONArray getJSON(DynamicObject[] dataEntities, DynamicObjectCollection collection) {

        JSONArray jsonArray = new JSONArray();
        for (DynamicObject dataEntitie : dataEntities) {
            //DynamicObjectCollection receiptdetailcoll = dataEntitie.getDynamicObjectCollection("yem_receiptdetail");
            for (DynamicObject receiptdetail : collection) {
                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"));
                //zhouc 2024-03-01
                DynamicObject yem_receiptaccount = (DynamicObject) this.getModel().getValue("yem_receiptaccount");
                if (yem_receiptaccount != null) {
                    json.put("payeeAccountBank", setJson("number", yem_receiptaccount.getString("yem_number")));
                } else {
                    json.put("payeeAccountBank", "");
                }
                //结算方式
                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 = GathEringService.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", FilterUtils.getUserNumber(creators.getString("number"))));
                }

                //应收金额
                BigDecimal sumreceivableamt = dataEntitie.getBigDecimal("yem_sumreceivableamt");
                json.put("sumReceivableAmt", sumreceivableamt);
                //应收金额（本位币）
                BigDecimal sumreceivableamtba = dataEntitie.getBigDecimal("yem_sumreceivableamtba");
                json.put("sumReceivableAmtBase", sumreceivableamtba);

                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 List setWebService(JSONArray json, DynamicObjectCollection collection, 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 : collection) {
                    String seq = receiptdetail.getString("seq");
                    String billno = data.getString("billno") + "_" + seq;
                    list.add(billno);
                }
                //addErrorInfo(msgE,data.getPkValue());
                this.getView().showErrorNotification(msgE);
            }
            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());
                this.getView().showErrorNotification(msgE);
            }
            if (list.size() == 0) {
                String msgE = "同步EAS失败:" + msg;
                for (DynamicObject data : datas) {
                    // DynamicObjectCollection receiptdetailcoll = data.getDynamicObjectCollection("yem_receiptdetail");
                    for (DynamicObject receiptdetail : collection) {
                        String seq = receiptdetail.getString("seq");
                        String billno = data.getString("billno") + "_" + seq;
                        list.add(billno);
                    }
                    //addErrorInfo(msgE,data.getPkValue());
                    this.getView().showErrorNotification(msgE);
                }
                return list;
            }
        }

        return list;
    }

    /**
     * @param datas     实体
     * @param jsonArray
     * @return 过滤同步失败的数据
     */
    public List<String> setData(DynamicObject[] datas, DynamicObjectCollection collection, JSONArray jsonArray, String type) {
        List<String> list = setWebService(jsonArray, collection, 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 : collection) {
                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;
    }


}
