package com.yem.wm.syn.eas;

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.AfterOperationArgs;
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 涛
 * @date 2023/11/21
 * 礼品领用申请单-服务插件-审核后同步EAS
 */
public class ImGiftApplyService extends AbstractOperationServicePlugIn {
    private final static String TYPE = "10004";
    private final static Log log = LogFactory.getLog(ImGiftApplyService.class);

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_billtype");
        fieldKeys.add("org");
        fieldKeys.add("yem_proposer");
        fieldKeys.add("yem_department");
        fieldKeys.add("yem_generalasstacttype");
        fieldKeys.add("yem_provideunit");
        fieldKeys.add("yem_isacross");
        fieldKeys.add("yem_costitem");
        fieldKeys.add("creator");
        fieldKeys.add("createtime");
        fieldKeys.add("yem_im_entryentity");
        fieldKeys.add("yem_materialnum");
        fieldKeys.add("yem_qty");
        fieldKeys.add("yem_reqstorageorgunit");
        fieldKeys.add("yem_iseas");
        fieldKeys.add("yem_remark");
        fieldKeys.add("yem_warehouse");
        fieldKeys.add("yem_fromhouse");
        fieldKeys.add("yem_location");
        fieldKeys.add("yem_fromlocation");
    }


    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
//        //过滤单据类型
//        DynamicObject[] dataEntite = isbillType(dataEntities);
//        if (dataEntite.length == 0) {
//            return;
//        }
//        JSONArray jsonArray = getJSON(dataEntite);
//
//        DynamicObject[] data = setData(dataEntities, jsonArray, TYPE);
//        for (DynamicObject dynamicObject : data) {
//            dynamicObject.set("yem_iseas", true);
//            dynamicObject.set("yem_synfalt", "同步EAS成功！");
//            SaveServiceHelper.update(dynamicObject);
//        }

    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        String operationKey = e.getOperationKey();
        DynamicObject[] dataEntities = e.getDataEntities();
        //过滤单据类型
        DynamicObject[] dataEntite = isbillType(dataEntities);
        if (dataEntite.length == 0) {
            return;
        }
        JSONArray jsonArray = getJSON(dataEntite);

        DynamicObject[] data = setData(dataEntities, jsonArray, TYPE);
        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) {

            JSONObject json = new JSONObject();
            //单据编号
            json.put("sourceYunNum", dataEntitie.getString("billno"));
            json.put("description", dataEntitie.getString("yem_remark"));


            //业务日期
            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_reqstorageorgunit = dataEntitie.getDynamicObject("yem_reqstorageorgunit");
            if (yem_reqstorageorgunit != null) {
                json.put("ReqStorageOrgUnit", setJson("number", yem_reqstorageorgunit.getString("number")));
            }

            //公司
            //end  by zhouc 2024-03-05
            DynamicObject org = dataEntitie.getDynamicObject("org");
            if (org != null) {
                json.put("CU", setJson("number", org.getString("number")));
            }

            //领料人
            DynamicObject yem_proposer = dataEntitie.getDynamicObject("yem_proposer");
            if (yem_proposer != null) {
                json.put("ReqUser", setJson("number", yem_proposer.getString("number")));
            }

            //领料部门
            DynamicObject yem_department = dataEntitie.getDynamicObject("yem_department");
            if (yem_department != null) {
                json.put("ReqDepartment", setJson("number", yem_department.getString("number")));
            }
            //工程项目
            DynamicObject yem_generalasstacttype = dataEntitie.getDynamicObject("yem_generalasstacttype");
            if (yem_generalasstacttype != null) {
//                json.put("engineeProject", setJson("number", yem_generalasstacttype.getString("number")));
                String longnumber = yem_generalasstacttype.getString("longnumber");
                json.put("engineeProject", setJson("number", longnumber.replace(".", "!")));
            }

            //需求方库存组织
            DynamicObject yem_provideunit = dataEntitie.getDynamicObject("yem_provideunit");
            if (yem_provideunit != null) {
                json.put("provideUnit", setJson("number", yem_provideunit.getString("number")));
            }
            //是否跨事业部
            if (dataEntitie.getBoolean("yem_isacross")) {
                json.put("isAcross", "是");
            } else {
                json.put("isAcross", "不是");
            }
            //费用项目
            DynamicObject yem_costitem = dataEntitie.getDynamicObject("yem_costitem");
            if (yem_costitem != null) {
//                json.put("costTypeNew", setJson("number", yem_costitem.getString("number")));
                String longnumber = yem_costitem.getString("longnumber");
                json.put("costTypeNew", setJson("number", longnumber.replace(".", "!")));
            }
            //业务类型
            json.put("BusinessType", setJson("number", "510"));
            //审核人
            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_im_entryentity");
            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_materialnum");
            if (yemMaterial != null) {
                json.put("MaterialNumber", setJson("number", yemMaterial.getString("number")));
                json.put("FigureNumber", yemMaterial.getString("number"));
                json.put("MaterialName", yemMaterial.getString("name"));
                //计量单位
                DynamicObject material = BusinessDataServiceHelper.loadSingle(yemMaterial.getPkValue(), yemMaterial.getDynamicObjectType());
                DynamicObject baseunit = material.getDynamicObject("baseunit");
                json.put("Unit", baseunit.getString("number"));
                //规格型号
                String modelnum = material.getString("modelnum");
                json.put("Model", modelnum);

            }
            //申请数量
            BigDecimal yemQty = entryentity.getBigDecimal("yem_qty");
            json.put("ReqQty", yemQty);
            //未领料数量
            json.put("unGetQty", yemQty);
            //已领料数量
            json.put("HavePickQty", 0);
            //仓库
            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")));
            }
            jsonArray.add(json);
        }
        return jsonArray;
    }

    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_im_giftapply", 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;
    }

    /**
     * @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 DynamicObject[] isbillType(DynamicObject[] dataEntities) {
        ArrayList<DynamicObject> list = new ArrayList<>();
        for (int i = 0; i < dataEntities.length; i++) {
            DynamicObject dataEntity = dataEntities[i];
            DynamicObject yemBilltype = dataEntity.getDynamicObject("yem_billtype");

            //如果单据类型等于礼品领用申请单
            if ("yem_im_giftapply_LY".equals(yemBilltype.getString("number"))) {
                list.add(dataEntity);
            }
        }
        DynamicObject[] data = new DynamicObject[list.size()];
        for (int i = 0; i < list.size(); i++) {
            DynamicObject dataEntity = list.get(i);
            data[i] = dataEntity;
        }

        return data;
    }

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

    }
}
