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.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.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 涛
 * @date 2023/10/24
 * 发货通知单标准服务插件
 */
public class YemDelivernoticeService extends AbstractOperationServicePlugIn {
    private final static Log log = LogFactory.getLog(YemDelivernoticeService.class);

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_customer1");
        fieldKeys.add("yem_currency");
        fieldKeys.add("yem_comment");
        fieldKeys.add("yem_linkman");
        fieldKeys.add("yem_reclinkman");
        fieldKeys.add("yem_org");
        fieldKeys.add("yem_bizdate1");
        fieldKeys.add("yem_department");
        fieldKeys.add("auditor");
        fieldKeys.add("creator");
        fieldKeys.add("createtime");
        fieldKeys.add("auditdate");
        fieldKeys.add("yem_remark");
        fieldKeys.add("yem_materiel");
        fieldKeys.add("yem_unit");
        fieldKeys.add("yem_qty");
        fieldKeys.add("yem_lotnumber");
        fieldKeys.add("yem_warehouse");
        fieldKeys.add("yem_baseunit");
        fieldKeys.add("yem_baseqty");
        fieldKeys.add("yem_price");
        fieldKeys.add("yem_taxrateid");
        fieldKeys.add("yem_priceandtax");
        fieldKeys.add("yem_amt");
        fieldKeys.add("yem_locamt");
        fieldKeys.add("yem_taxamount");
        fieldKeys.add("yem_curtaxamount");
        fieldKeys.add("yem_amountandtax");
        fieldKeys.add("yem_curamountandtax");
        fieldKeys.add("yem_salesorg");
        fieldKeys.add("yem_operator");
        fieldKeys.add("yem_receiveaddress");
        fieldKeys.add("yem_location");
        fieldKeys.add("yem_paymode");
        fieldKeys.add("yem_exrate");
        fieldKeys.add("yem_isgift");
        fieldKeys.add("EntryID");
        fieldKeys.add("yem_synfalt");
        fieldKeys.add("yem_synfalt_tag");
        fieldKeys.add("yem_saletype");
        fieldKeys.add("yem_bd_products");
        fieldKeys.add("yem_bizdate");
        fieldKeys.add("yem_taxrate");
    }

    @Override
    public void beforeExecuteOperationTransaction(BeforeOperationArgs e) {
        super.beforeExecuteOperationTransaction(e);
        String operationKey = e.getOperationKey();
        if ("audit".equals(operationKey) || "submit".equals(operationKey)) {
            List<ExtendedDataEntity> selectedRows = e.getSelectedRows();
            List<ExtendedDataEntity> list = new ArrayList<>();
            for (ExtendedDataEntity selectedRow : selectedRows) {
                DynamicObject dataEntity = selectedRow.getDataEntity();
                dataEntity = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), dataEntity.getDynamicObjectType().getName());
                DynamicObject yem_billtype = dataEntity.getDynamicObject("yem_billtype");
                if (yem_billtype != null) {
                    String number = yem_billtype.getString("number");
                    if (number.equals("yem_es_delivernotice_zj") || number.equals("yem_es_delivernotice_pj")) {
                        JSONArray json = getJSON(new DynamicObject[]{dataEntity});
                        try {
                            String s = setWebService(json);
                            if (s.length() > 0) {
                                this.operationResult.addErrorInfo(
                                        new ValidationErrorInfo(
                                                "", dataEntity.getPkValue(), 0, 0, "err", "billtitle", dataEntity.getString("billno") + "同步EAS失败:" + s, ErrorLevel.Error));
                                dataEntity.set("yem_synfalt", "同步失败,点击按钮查看失败详情！");
                                dataEntity.set("yem_synfalt_tag", s);
                                SaveServiceHelper.update(dataEntity);
                            } else {
                                dataEntity.set("yem_iseas", true);
                                dataEntity.set("yem_synfalt", "提交EAS成功！");
                                dataEntity.set("yem_synfalt_tag", "提交EAS成功");
                                SaveServiceHelper.update(dataEntity);
                                list.add(selectedRow);
                            }
                        } catch (Exception ex) {
                            log.error("同步EAS异常请联系管理员:" + ex.getMessage());
                            this.operationResult.addErrorInfo(new ValidationErrorInfo("", dataEntity.getPkValue(), 0, 0, "err", "billtitle", dataEntity.getString("billno") + "同步EAS失败:" + ex.getMessage(), ErrorLevel.Error));
                        }
                    } else {
                        list.add(selectedRow);
                    }
                }
            }

            e.getSelectedRows().clear();
            if (list.size() == 0) {
                e.setCancel(true);
                throw new KDBizException("单据提交EAS失败");
            } else {
                e.getSelectedRows().addAll(list);
            }
        }
    }


    private JSONArray getJSON(DynamicObject[] dataEntities) {
        JSONArray jsonArray = new JSONArray();
        for (DynamicObject dataEntitie : dataEntities) {

            JSONObject json = new JSONObject();

            // 是否外贸单据	“true” “false”	是	布尔         默认是
            json.put("cosmic", true);
            // saleType    	销售类型	内销	“1” 外销	“2”	是	字符串，
            String saletype = dataEntitie.getString("yem_saletype");
            json.put("saleType", "A".equals(saletype) ? "1" : "2");
            // productType    	配件类型	装载机	“1”拖拉机	“2”叉车	“3”	是	 字符串
            // 产品分类
            DynamicObject products = dataEntitie.getDynamicObject("yem_bd_products");
            String productType = "";
            if (products != null) {
                String number = products.getString("number");
                if (number.contains("ZZJ")) {
                    productType = "1";
                }
                if (number.contains("TLJ")) {
                    productType = "2";
                }
                if (number.contains("CC")) {
                    productType = "3";
                }
            }
            json.put("productType", productType);

            //单据状态
            json.put("billStatus", 1);
            //单据编号
            json.put("number", dataEntitie.getString("billno"));
            //送货客户
            DynamicObject yemCustomer = dataEntitie.getDynamicObject("yem_customer1");
            if (yemCustomer != null) {
                json.put("customer", setJson("number", yemCustomer.getString("number")));
            }
            //币别
            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")));
            }
            String isdeclare = dataEntitie.getString("yem_isdeclare");
            String val = "A".equals(isdeclare) ? "本票报关" : "本票不报关";
            //摘要
            json.put("description", val + " " + dataEntitie.getString("yem_comment"));
            //发货人
            DynamicObject yemLinkman = dataEntitie.getDynamicObject("yem_linkman");
            if (yemLinkman != null) {
                json.put("realReceivePerson", setJson("number", yemLinkman.getString("number")));
            }
            //领料人  修改为创建人
            DynamicObject creator = dataEntitie.getDynamicObject("creator");
            if (creator != null) {
                json.put("lingliaoren", setJson("number", creator.getString("number")));
            }
            //业务类型
//            json.put("bizType", setJson("number", "310"));
            // change by zzs 2024-05-09
            json.put("bizType", setJson("number", "210"));
            //事务类型
            json.put("transactionType", setJson("number", "010"));
            //库存组织
            DynamicObject org = dataEntitie.getDynamicObject("yem_org");
            if (org != null) {
                json.put("storageOrgUnit", setJson("number", org.getString("number")));
            }
            //付款方式
            String yemPaymode = dataEntitie.getString("yem_paymode");
            if ("CREDIT".equals(yemPaymode)) {//赊销
                json.put("paymentType", setJson("number", "002"));
            } else if ("CASH".equals(yemPaymode)) {//现销
                json.put("paymentType", setJson("number", "001"));
            }
            //汇率
            json.put("exchangeRate", dataEntitie.getBigDecimal("yem_exrate"));
            //销售类型
//            String yemSaletype = dataEntitie.getString("yem_saletype");
//            if ("A".equals(yemSaletype)){//内销
//                json.put("saleType",1);
//            } else if ("B".equals(yemSaletype)) {//外销
//                json.put("saleType",2);
//            }

            //业务日期
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            String yemBizdate = fmt.format(dataEntitie.getDate("yem_bizdate"));
            json.put("bizDate", yemBizdate);
            //部门
            DynamicObject yemDept = dataEntitie.getDynamicObject("yem_department");
            if (yemDept != null) {
                json.put("adminOrgUnit", setJson("number", yemDept.getString("number")));
            }
            //含税
            json.put("isInTax", Boolean.TRUE);

            //审核人
            DynamicObject auditor = dataEntitie.getDynamicObject("auditor");
            if (auditor != null) {
                //json.put("auditor",setJson("number",auditor.getString("number")));
            }
            json.put("auditor", setJson("number", "COSMIC"));
            //创建人
            DynamicObject creators = dataEntitie.getDynamicObject("creator");
            if (creators != null) {
                json.put("creator", setJson("number", creators.getString("number")));
                //json.put("creator",setJson("number","00003"));
            }
            json.put("creator", setJson("number", "COSMIC"));
            SimpleDateFormat fmtTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            //创建时间
            String createtime = fmtTime.format(dataEntitie.getDate("createtime"));
            json.put("createTime", createtime);
            //审核日期
            Date auditdate = dataEntitie.getDate("auditdate");
            if (auditdate != null) {
                String auditdates = fmtTime.format(auditdate);
                json.put("auditTime", auditdates);
            }

            //财务信息-价和兑合计(本位币)
            json.put("totalLocalAmount", dataEntitie.getBigDecimal("yem_curtotalallamount"));
            //财务信息-金额
            json.put("totalAmount", dataEntitie.getBigDecimal("yem_amount"));

            //明细信息分录
            //商品明细
            DynamicObjectCollection materialcoll = dataEntitie.getDynamicObjectCollection("yem_es_materialinfo");
            BigDecimal qty = BigDecimal.ZERO;
            for (DynamicObject dynamicObject : materialcoll) {
                qty = qty.add(dynamicObject.getBigDecimal("yem_qty"));
            }
            //明细信息-数量汇总
            json.put("totalQty", qty);

            JSONArray entry = getEntry(materialcoll, dataEntitie);
            json.put("entry", entry);
            jsonArray.add(json);
            log.debug(dataEntitie.getString("billno") + "发货通知单同步EASjson" + jsonArray.toJSONString());
        }

        return jsonArray;
    }

    //明细信息分录
    private JSONArray getEntry(DynamicObjectCollection materialcoll, DynamicObject dataEntitie) {
        JSONArray jsonArray = new JSONArray();

        for (DynamicObject materialentry : materialcoll) {
            JSONObject json = new JSONObject();
            //苍穹分录ID
            json.put("plmeid", materialentry.getPkValue());
            //备注
            json.put("remark", materialentry.getString("yem_remark"));
            //更新类型
            json.put("invUpdateType", setJson("number", "002"));
            //物料编码
            DynamicObject yem_materiel = materialentry.getDynamicObject("yem_materiel");
            if (yem_materiel != null) {
                json.put("material", setJson("number", yem_materiel.getString("number")));
            }
            //计量单位
            DynamicObject yemUnit = materialentry.getDynamicObject("yem_unit");
            if (yemUnit != null) {
                json.put("unit", setJson("number", yemUnit.getString("number")));
            }
            //数量
            json.put("qty", materialentry.getBigDecimal("yem_qty"));
            //批次
            json.put("lot", materialentry.getString("yem_lotnumber"));
            //仓库
            DynamicObject yemWarehouse = materialentry.getDynamicObject("yem_warehouse");
            if (yemWarehouse != null) {
                json.put("warehouse", setJson("number", yemWarehouse.getString("number")));
            }
            //库位
            DynamicObject yemLocation = materialentry.getDynamicObject("yem_location");
            if (yemLocation != null) {
                json.put("location", setJson("number", yemLocation.getString("number")));
                //库位编码
                json.put("saleOrgUnit", yemLocation.getString("number"));
            }
            //基本计量单位
            DynamicObject yemBaseunit = materialentry.getDynamicObject("yem_baseunit");
            if (yemBaseunit != null) {
                json.put("baseUnit", setJson("number", yemBaseunit.getString("number")));
            }
            //基本数量
            json.put("baseQty", materialentry.getBigDecimal("yem_baseqty"));
            //赠品
            json.put("isPresent", materialentry.getBoolean("yem_isgift"));
            //单价
            json.put("salePrice", materialentry.getBigDecimal("yem_price"));
            //税率%
            json.put("taxRate", materialentry.getBigDecimal("yem_taxrate"));
            //含税单价
            json.put("taxPrice", materialentry.getBigDecimal("yem_priceandtax"));
            //实际单价
            json.put("actualPrice", materialentry.getBigDecimal("yem_price"));
            //实际含税单价
            json.put("price", materialentry.getBigDecimal("yem_priceandtax"));
            //金额
            json.put("nonTaxAmount", materialentry.getBigDecimal("yem_amt"));
            //金额本位币
            json.put("localNonTaxAmount", materialentry.getBigDecimal("yem_locamt"));
            //税额
            json.put("tax", materialentry.getBigDecimal("yem_taxamount"));
            //税额本位币
            json.put("localTax", materialentry.getBigDecimal("yem_curtaxamount"));
            //价税合计
            json.put("amount", materialentry.getBigDecimal("yem_amountandtax"));
            //价税合计本位币
            json.put("localAmount", materialentry.getBigDecimal("yem_curamountandtax"));
            //销售组织
            DynamicObject yemSalesorg = materialentry.getDynamicObject("yem_salesorg");
            if (yemBaseunit != null) {
                json.put("saleOrgUnit", setJson("number", yemSalesorg.getString("number")));
            }
            //销售员
            DynamicObject yemOperator = dataEntitie.getDynamicObject("yem_operator");
            if (yemOperator != null) {
                json.put("salePerson", setJson("number", yemOperator.getString("number")));
            }
            //送货地址
            json.put("sendAddress", dataEntitie.getString("yem_receiveaddress"));

            // 客户订单号 -- 合同号
            json.put("orderNumber", dataEntitie.getString("yem_contractnum"));

            jsonArray.add(json);
        }
        return jsonArray;
    }

    private String setWebService(JSONArray json) {
        //同步EAS暂存状态
//        String service = RequestEAS.getSaveService(json.toJSONString(), "007");
        //同步EAS审核状态
        String service = RequestEAS.getService(json.toJSONString(), "007");
        JSONObject jsonObject = JSON.parseObject(service);
        String status = jsonObject.getString("status");
        String msg = jsonObject.getString("msg");
        String errorMsgs = "";
        if (!"0".equals(status)) {
            JSONArray billErrors = jsonObject.getJSONArray("billErrors");
            int i = 1;
            for (Object billError : billErrors) {
                JSONObject js = (JSONObject) billError;
                JSONArray errorMsg = js.getJSONArray("errorMsgs");
                if (errorMsgs.length() > 0) {
                    errorMsgs = errorMsgs + "\n" + i + "、" + errorMsg.getString(0);
                } else {
                    errorMsgs = i + "、" + errorMsg.getString(0);
                }
                i++;
            }
            if (msg != null) {
                errorMsgs = msg + "\n" + errorMsgs;
            }

            //throw new KDBizException(dataEntitie.getString("billno")+errorMsgs);
        }

        return errorMsgs;
    }

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