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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
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.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author 涛
 * @date 2023/11/30
     * 收款单-服务插件-财务确认反同步EAS
 */
public class GathEringUnAudit extends AbstractOperationServicePlugIn {
    private final static String TYPE = "10002";
    private final static Log log = LogFactory.getLog(GathEringUnAudit.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);
        List<String> list = setData(dataEntities, jsonArray, TYPE);
        if (list.size()>0){
            e.setDataEntities(new DynamicObject[]{});
        }
    }

    private 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")));
                jsonArray.add(json);
            }
        }
        log.debug("收款单-服务插件删除EAS:"+jsonArray.toJSONString());
        return jsonArray;
    }



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

        try {
            service = RequestEAS.getServiceUnAudit(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 过滤同步失败的数据
     */
    private 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",false);
            yemReceiptdetail.set("yem_easbillno",null);
            SaveServiceHelper.update(info);
        }

        return list;
    }

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


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

    }
}
