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.ExtendedDataEntity;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.BeforeOperationArgs;
import kd.bos.entity.plugin.args.BeginOperationTransactionArgs;
import kd.bos.entity.validate.ErrorLevel;
import kd.bos.entity.validate.ValidationErrorInfo;
import kd.bos.exception.KDBizException;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * @author 涛
 * @date 2023/11/21
 * 询价单_配件-服务插件-提交同步EAS
 */
public class ImInQuirylistPJService extends AbstractOperationServicePlugIn {
    private final static String TYPE = "10001";
    private final static Log log = LogFactory.getLog(ImInQuirylistPJService.class);

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_department");
        fieldKeys.add("yem_billtype");
        fieldKeys.add("yem_enquirymessage");
        fieldKeys.add("yem_bizdate");
        fieldKeys.add("yem_currency");
        fieldKeys.add("yem_exrate");
        fieldKeys.add("yem_iscaigou");
        fieldKeys.add("yem_remark");
        fieldKeys.add("creator");
        fieldKeys.add("createtime");
        fieldKeys.add("yem_im_detailedinfor");
        fieldKeys.add("yem_material");
        fieldKeys.add("yem_marketre");
        fieldKeys.add("yem_classification");
        fieldKeys.add("yem_iseas");
        fieldKeys.add("yem_synfalt");
        fieldKeys.add("org");
        fieldKeys.add("yem_remarks");
        fieldKeys.add("yem_pjbzwfl");
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        List<ExtendedDataEntity> selectedRows = e.getSelectedRows();
        //过滤单据类型
        List<ExtendedDataEntity> datas = isbillType(selectedRows);
        if (datas.size() == 0) {
//            e.setCancel(true);
            return;
        }
        JSONArray jsonArray = getJSON(datas);
        String operationKey = e.getOperationKey();
        List<ExtendedDataEntity> data = setData(datas, jsonArray, TYPE, operationKey);
        //获取整机
        List<ExtendedDataEntity> typeZJBill = isbillTypeZJ(selectedRows);
        data.addAll(typeZJBill);
        e.getSelectedRows().clear();
        if (data.size() == 0) {
            e.setCancel(true);
        } else {
            e.getSelectedRows().addAll(data);
            for (ExtendedDataEntity selectedRow : selectedRows) {
                DynamicObject dataEntity = selectedRow.getDataEntity();
                dataEntity.set("yem_iseas", true);
                dataEntity.set("yem_synfalt", "同步成功!");
                SaveServiceHelper.update(dataEntity);
            }
        }
    }

   /* @Override
    public void beginOperationTransaction(BeginOperationTransactionArgs e) {
        super.beginOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        //过滤单据类型
        DynamicObject[] datas = isbillType(dataEntities);
        if (datas.length==0){
            return;
        }
        JSONArray jsonArray = getJSON(datas);
        DynamicObject[] data = setData(datas, jsonArray,TYPE);
        //获取整机
        DynamicObject[] typeZJBill = isbillTypeZJ(dataEntities);
        DynamicObject[] dataEntite = setEntite(typeZJBill, data);
        //获取通过对象
        e.setDataEntities(dataEntite);

    }

    private DynamicObject[] setEntite(List<ExtendedDataEntity> typeZJBill, List<ExtendedDataEntity> data){
        DynamicObject[] dataEntites = new DynamicObject[typeZJBill.size()+ data.size()];
        System.arraycopy(data,0,dataEntites,0,data.length);
        System.arraycopy(typeZJBill,0,dataEntites,data.length,typeZJBill.length);
        return dataEntites;
    }*/

    private JSONArray getJSON(List<ExtendedDataEntity> selectedRows) {
        JSONArray jsonArray = new JSONArray();
        for (ExtendedDataEntity selectedRow : selectedRows) {
            DynamicObject dataEntitie = selectedRow.getDataEntity();
            JSONObject json = new JSONObject();
            //单据编号
            json.put("number", dataEntitie.getString("billno"));
            //业务部门
            DynamicObject yemDepartment = dataEntitie.getDynamicObject("yem_department");
            if (yemDepartment != null) {
                json.put("Department", setJson("number", yemDepartment.getString("number")));
            }
            //公司
            DynamicObject org = dataEntitie.getDynamicObject("org");
            if (org != null) {
                json.put("CU", setJson("number", org.getString("number")));
            }
            //单据状态
            json.put("BillStatus", 1);

            //询价信息
            String yemEnquirymessage = dataEntitie.getString("yem_enquirymessage");
            //自制件询价-大装
            if ("A".equals(yemEnquirymessage)) {
                json.put("InquiryInfo", 1);
            } else if ("C".equals(yemEnquirymessage)) { //自制件询价-农装
                json.put("InquiryInfo", 3);
            } else if ("D".equals(yemEnquirymessage)) { //自制件询价-叉车
                json.put("InquiryInfo", 5);
            } else if ("E".equals(yemEnquirymessage)) { //外购件询价-大装
                json.put("InquiryInfo", 2);
            } else if ("G".equals(yemEnquirymessage)) { //外购件询价-农装
                json.put("InquiryInfo", 4);
            } else if ("H".equals(yemEnquirymessage)) { //外购件询价-叉车
                json.put("InquiryInfo", 6);
            }
            //是否估价
            json.put("IsEvaluation", 0);
            //业务日期
            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 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("ExchangeRate", dataEntitie.getBigDecimal("yem_exrate"));
            //是否到采购
            json.put("IsCaiGou", dataEntitie.getString("yem_iscaigou"));
            //参考信息
            json.put("description", dataEntitie.getString("yem_remark"));
            //创建者 creator
            DynamicObject creators = dataEntitie.getDynamicObject("creator");
            if (creators != null) {
                json.put("creator", setJson("number", creators.getString("number")));
            }
            //创建日期
            String createtime = fmtTime.format(dataEntitie.getDate("createtime"));
            json.put("createTime", createtime);

            //明细信息分录
            //商品明细
            DynamicObjectCollection yem_im_detailedinforcoll = dataEntitie.getDynamicObjectCollection("yem_im_detailedinfor");
            JSONArray entry = getEntry(yem_im_detailedinforcoll, dataEntitie);
            json.put("entrys", entry);
            jsonArray.add(json);
            log.debug(dataEntitie.getString("billno") + "配件询价单同步EASjson" + jsonArray.toJSONString());

        }

        return jsonArray;
    }


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

        for (DynamicObject detailedinfor : yem_im_detailedinforcoll) {
            JSONObject json = new JSONObject();
            //物料代码
            DynamicObject yemMaterial = detailedinfor.getDynamicObject("yem_material");
            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");
                if (baseunit != null) {
                    json.put("MeasurementUnit", baseunit.getString("number"));
                }
            }
            //市场参考价格
            json.put("MarketReferencePrice", detailedinfor.getBigDecimal("yem_marketre"));
            //配件分类
            DynamicObject yemClassification = detailedinfor.getDynamicObject("yem_classification");
            if (yemClassification != null) {
                json.put("ClassificationParts", setJson("number", yemClassification.getString("number")));
            }
            //备注 服务人员备注
            json.put("ServiceRemark", detailedinfor.getString("yem_remarks"));
            //配件包装物分类 服务人员备注
            json.put("packageClassification", detailedinfor.getString("yem_pjbzwfl"));
            jsonArray.add(json);
        }
        return jsonArray;
    }

    private List setWebService(JSONArray json, List<ExtendedDataEntity> selectedRows, 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 (ExtendedDataEntity selectedRow : selectedRows) {
                DynamicObject data = selectedRow.getDataEntity();
                data.set("yem_synfalt", "同步失败,失败原因:" + e.getMessage());
                SaveServiceHelper.update(data);
                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_inquirylist", new QFilter[]{new QFilter("billno", QCP.equals, number)});
                dynamicObject.set("yem_synfalt", "同步失败,失败原因:" + s);
                SaveServiceHelper.update(dynamicObject);
                addErrorInfo(msgE, dynamicObject.getPkValue());
            }
            if (list.size() == 0) {
                String msgE = "同步EAS失败:" + msg;
                for (ExtendedDataEntity selectedRow : selectedRows) {
                    DynamicObject data = selectedRow.getDataEntity();
                    data.set("yem_synfalt", "同步失败,失败原因:" + msg);
                    SaveServiceHelper.update(data);
                    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 List<ExtendedDataEntity> isbillType(List<ExtendedDataEntity> selectedRows) {
        List<ExtendedDataEntity> list = new ArrayList<>();
        for (ExtendedDataEntity selectedRow : selectedRows) {
            DynamicObject dataEntity = selectedRow.getDataEntity();
            DynamicObject yemBilltype = dataEntity.getDynamicObject("yem_billtype");

            //如果单据类型等于配件
            if ("yem_im_inquirylist_PJ".equals(yemBilltype.getString("number"))) {
                list.add(selectedRow);
            }
        }

        return list;
    }


    private List<ExtendedDataEntity> isbillTypeZJ(List<ExtendedDataEntity> selectedRows) {
        List<ExtendedDataEntity> list = new ArrayList<>();
        for (ExtendedDataEntity selectedRow : selectedRows) {
            DynamicObject dataEntity = selectedRow.getDataEntity();
            DynamicObject yemBilltype = dataEntity.getDynamicObject("yem_billtype");

            //如果单据类型等于配件
            if (!"yem_im_inquirylist_PJ".equals(yemBilltype.getString("number"))) {
                list.add(selectedRow);
            }
        }

        return list;
    }

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

        for (String number : list) {
            Predicate<ExtendedDataEntity> predicate = selectedRow -> !StringUtils.equals(selectedRow.getDataEntity().getString("billno"), number);
            arrayList = arrayList.stream().filter(predicate).collect(Collectors.toList());
        }
        List<ExtendedDataEntity> arrayLists = new ArrayList<>();
//        if ("syn_eas".equals(operationKey)){
        for (ExtendedDataEntity selectedRow : arrayList) {
            DynamicObject dataEntity = selectedRow.getDataEntity();
            dataEntity.set("yem_iseas", true);
            dataEntity.set("yem_synfalt", "同步成功!");
            SaveServiceHelper.update(dataEntity);
            arrayLists.add(selectedRow);
        }
//        }else{
//            for (ExtendedDataEntity selectedRow:arrayList) {
//                DynamicObject dataEntity = selectedRow.getDataEntity();
//                dataEntity.set("yem_iseas",true);
//                dataEntity.set("yem_synfalt","同步EAS成功!");
//                SaveServiceHelper.update(dataEntity);
//                arrayLists.add(selectedRow);
//            }
//        }
        return arrayList;
    }


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

    }


}
