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

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.wm.utils.RequestEAS;
import com.yem.wm.utils.YEM;
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.BeforeOperationArgs;
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 zhouc
 * @date 2024/4/15 15:11
 * @className DelivernoticeSynEAS
 * @description 销售出库单审核同步EAS其他领料申请单
 */
public class DelivernoticeSynEAS extends AbstractOperationServicePlugIn {
    private final static Log log = LogFactory.getLog(DelivernoticeSynEAS.class);


    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.addAll(this.billEntityType.getAllFields().keySet());
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        String operationKey = e.getOperationKey();
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntitie : dataEntities) {
            dataEntitie = BusinessDataServiceHelper.loadSingle(dataEntitie.getPkValue(), dataEntitie.getDynamicObjectType().getName());
            DynamicObject yem_billtype = dataEntitie.getDynamicObject("yem_billtype");
            if (yem_billtype != null) {
                String number = yem_billtype.getString("number");
                if (number.equals("yem_es_delivernotice_o")) {
                    JSONArray jsonArray = getJSON(dataEntities);
                    DynamicObject[] data = setData(dataEntities, jsonArray, "10004");
                    if (data.length > 0) {
                        for (DynamicObject dynamicObject : data) {
                            dynamicObject.set("yem_iseas", true);
                            dynamicObject.set("yem_synfalt", "同步EAS成功！");
                            SaveServiceHelper.update(dynamicObject);
                        }
                    } else {
                        e.setCancel(true);
                    }
                }
            }
        }
    }

    private JSONArray getJSON(DynamicObject[] dataEntities) {
        JSONArray jsonArray = new JSONArray();
        for (DynamicObject dataEntitie : dataEntities) {
            dataEntitie = BusinessDataServiceHelper.loadSingle(dataEntitie.getPkValue(), dataEntitie.getDynamicObjectType().getName());
            JSONObject json = new JSONObject();
            //CU控制单元
            DynamicObject org = dataEntitie.getDynamicObject("org");
            if (org != null) {
                json.put("CU", setJson("number", org.getString("number")));
            }
            //供应方库存组织
            DynamicObject yem_reqstorageorgunit = dataEntitie.getDynamicObject("yem_deliverorg");
            if (yem_reqstorageorgunit != null) {
                json.put("ReqStorageOrgUnit", setJson("number", yem_reqstorageorgunit.getString("number")));
            }
            //业务类型
            json.put("BusinessType", setJson("number", "510"));
            //是否跨事业部
            boolean isacrossdept = dataEntitie.getBoolean("yem_isacrossdept");
            json.put("isAcross", isacrossdept ? "是" : "否");
            //业务日期
            SimpleDateFormat fmtDate = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat fmtTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String yemBizdate = fmtDate.format(dataEntitie.getDate("yem_bizdate"));
            json.put("bizDate", yemBizdate);
            //领料人
            DynamicObject yem_proposer = dataEntitie.getDynamicObject("yem_operator");
            if (yem_proposer != null) {
                json.put("ReqUser", setJson("number", yem_proposer.getString("number")));
            }
            //工程项目
            DynamicObject engineproject = dataEntitie.getDynamicObject("yem_engineproject");
            String engineeProject = "";
            if (YEM.isNotEmpty(engineproject)) {
                String longnumber = engineproject.getString("longnumber");
                engineeProject = longnumber.replace(".", "!");
            }
            json.put("engineeProject", setJson("number", engineeProject));
            //参考信息
            String isdeclare = dataEntitie.getString("yem_isdeclare");
            String val = "A".equals(isdeclare) ? "本票报关" : "本票不报关";
            json.put("description", val + " " + dataEntitie.getString("yem_comment"));
            //领料部门
            DynamicObject yem_department = dataEntitie.getDynamicObject("yem_department");
            if (yem_department != null) {
                json.put("ReqDepartment", setJson("number", yem_department.getString("number")));
            }

            //需求方库存组织 默认：116-国际事业部
            DynamicObject yem_org = dataEntitie.getDynamicObject("yem_org");
            String provideUnit = "";
            if (YEM.isNotEmpty(yem_org)) {
                provideUnit = yem_org.getString("number");
            }
            json.put("provideUnit", setJson("number", provideUnit));

            //费用项目 默认：FY001.001-常规
            String costTypeNew = "";
            DynamicObject costproject = dataEntitie.getDynamicObject("yem_costproject");
            if (YEM.isNotEmpty(costproject)) {
                String longnumber = costproject.getString("longnumber");
                costTypeNew = longnumber.replace(".", "!");
            }
            json.put("costTypeNew", setJson("number", costTypeNew));


            //单据编号
            json.put("sourceYunNum", dataEntitie.getString("billno"));

            //审核人
            json.put("auditor", setJson("number", "COSMIC"));
            //创建者 creator
//            DynamicObject creators = dataEntitie.getDynamicObject("creator");
//            if (creators != null) {
//                json.put("creator", setJson("number", creators.getString("number")));
//            }
            json.put("creator", setJson("number", "COSMIC"));
            //创建日期
            String createtime = fmtTime.format(dataEntitie.getDate("createtime"));
            json.put("createTime", createtime);
            //明细信息分录
            //商品明细
            DynamicObjectCollection yem_im_entryentitycoll = dataEntitie.getDynamicObjectCollection("yem_es_materialinfo");
            JSONArray entry = getEntry(yem_im_entryentitycoll, dataEntitie);
            json.put("entrys", entry);
            jsonArray.add(json);
            log.debug(dataEntitie.getString("billno") + "礼品领用申请EAS" + jsonArray.toJSONString());

        }

        return jsonArray;
    }


    private JSONArray getEntry(DynamicObjectCollection yem_im_entryentitycoll, DynamicObject dataEntitie) {
        JSONArray jsonArray = new JSONArray();

        for (DynamicObject entryentity : yem_im_entryentitycoll) {
            JSONObject json = new JSONObject();
            //物料代码
            DynamicObject yemMaterial = entryentity.getDynamicObject("yem_materiel");
            if (yemMaterial != null) {
                DynamicObject material = BusinessDataServiceHelper.loadSingle(yemMaterial.getPkValue(), yemMaterial.getDynamicObjectType());
                //明细信息-物料编码
                json.put("MaterialNumber", setJson("number", yemMaterial.getString("number")));
                //物料名称
                json.put("MaterialName", yemMaterial.getString("name"));
                //规格型号
                String modelnum = material.getString("modelnum");
                json.put("Model", modelnum);
                //工程图号
                json.put("FigureNumber", yemMaterial.getString("number"));
                //计量单位
                DynamicObject baseunit = material.getDynamicObject("baseunit");
                json.put("Unit", baseunit.getString("number"));
            }
            //申请数量
            BigDecimal yemQty = entryentity.getBigDecimal("yem_qty");
            json.put("ReqQty", yemQty);
            //批次
            json.put("Lot",entryentity.getString("yem_lotnumber"));
            //仓库
            DynamicObject yem_warehouse = entryentity.getDynamicObject("yem_warehouse");
            if (yem_warehouse != null) {
                json.put("WareHouse", setJson("number", yem_warehouse.getString("number")));
            }
            //需方仓库
//            DynamicObject yem_fromhouse = entryentity.getDynamicObject("yem_fromhouse");
//            if (yem_fromhouse != null) {
//                json.put("fromHouse", setJson("number", yem_fromhouse.getString("number")));
//            }
            //库位
            DynamicObject yem_location = entryentity.getDynamicObject("yem_location");
            if (yem_location != null) {
                json.put("Location", setJson("number", yem_location.getString("number")));
            }
            //供方库位
//            DynamicObject yem_fromlocation = entryentity.getDynamicObject("yem_fromlocation");
//            if (yem_fromlocation != null) {
//                json.put("fromLocation", setJson("number", yem_fromlocation.getString("number")));
//            }
            //未领料数量
            json.put("unGetQty", yemQty);
            //已领料数量
            json.put("HavePickQty", 0);
            //备注
            json.put("Remark", entryentity.getString("yem_remark"));
            jsonArray.add(json);
        }
        return jsonArray;
    }

    /**
     * @param datas     实体
     * @param jsonArray
     * @return 过滤同步失败的数据
     */
    private DynamicObject[] setData(DynamicObject[] datas, JSONArray jsonArray, String type) {
        List<String> list = setWebService(jsonArray, datas, type);
        List<DynamicObject> arrayList = new ArrayList<>();
        for (DynamicObject dataEntitie : datas) {
            arrayList.add(dataEntitie);
        }

        for (String number : list) {
            Predicate<DynamicObject> predicate = dynamicObject -> !StringUtils.equals(dynamicObject.getString("billno"), number);
            arrayList = arrayList.stream().filter(predicate).collect(Collectors.toList());
        }
        DynamicObject[] data = new DynamicObject[arrayList.size()];
        for (int i = 0; i < arrayList.size(); i++) {
            data[i] = arrayList.get(i);
        }
        return data;
    }

    private 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) {
                list.add(data.getString("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_es_delivernotice", new QFilter[]{new QFilter("billno", QCP.equals, number)});
                addErrorInfo(msgE, dynamicObject.getPkValue());
            }
            if (list.size() == 0) {
                String msgE = "同步EAS失败:" + msg;
                for (DynamicObject data : datas) {
                    list.add(data.getString("billno"));
                    addErrorInfo(msgE, data.getPkValue());
                }
                return list;
            }
        }

        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) {
        DynamicObject dynamicObject = BusinessDataServiceHelper.loadSingle(pk, "yem_es_delivernotice");
        if (dynamicObject != null) {
            dynamicObject.set("yem_synfalt", message);
            SaveServiceHelper.update(dynamicObject);
        }
        this.operationResult.addErrorInfo(
                new ValidationErrorInfo(
                        "", pk, 0, 0, "err", "同步EAS失败", message, ErrorLevel.Error));

    }
}
