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.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.ExtendedDataEntity;
import kd.bos.entity.operate.result.OperateErrorInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.AddValidatorsEventArgs;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
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.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;

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

/**
 * @author 涛
 * @date 2023/10/19
 * 调拨订单标准服务插件
 */
public class YemTransferorderService  extends AbstractOperationServicePlugIn {
    private final static Log log = LogFactory.getLog(YemTransferorderService.class);
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_supfinorg");
        fieldKeys.add("yem_cusfinorg");
        fieldKeys.add("yem_outdept");
        fieldKeys.add("yem_businessdirection");
        fieldKeys.add("yem_applyuser");
        fieldKeys.add("yem_supstockorg");
        fieldKeys.add("yem_cusstockorg");
        fieldKeys.add("yem_indept");
        fieldKeys.add("yem_abstract");
        fieldKeys.add("yem_department");
        fieldKeys.add("yem_currency");
        fieldKeys.add("yem_exrate");
        fieldKeys.add("yem_includingtax");
        fieldKeys.add("yem_initialization");
        fieldKeys.add("yem_expenseitemedit");
        fieldKeys.add("yem_rdprojects");
        fieldKeys.add("yem_project");
        fieldKeys.add("yem_materiel");
        fieldKeys.add("yem_batch");
        fieldKeys.add("yem_needtransfer");
        fieldKeys.add("yem_productdate");
        fieldKeys.add("yem_duedate");
        fieldKeys.add("yem_unit");
        fieldKeys.add("yem_qty");
        fieldKeys.add("yem_baseunit");
        fieldKeys.add("yem_assistunit");
        fieldKeys.add("yem_price");
        fieldKeys.add("yem_assistqty");
        fieldKeys.add("yem_deliveryinventoryorg");
        fieldKeys.add("yem_shippersalesorg");
        fieldKeys.add("yem_deliverywarehouse");
        fieldKeys.add("yem_deliveryposition");
        fieldKeys.add("yem_receinventoryorg");
        fieldKeys.add("yem_receinventory");
        fieldKeys.add("yem_receposition");
        fieldKeys.add("yem_cuswarehouse");
        fieldKeys.add("yem_discountmethod");
        fieldKeys.add("yem_pricediscountrate");
        fieldKeys.add("yem_price");
        fieldKeys.add("yem_taxrate");
        fieldKeys.add("yem_pricetax");
        fieldKeys.add("yem_realitypricetax");
        fieldKeys.add("yem_amt");
        fieldKeys.add("yem_locamt");
        fieldKeys.add("yem_amounttax");
        fieldKeys.add("yem_amountfield1");
        fieldKeys.add("yem_amttax");
        fieldKeys.add("yem_baseamttax");
        fieldKeys.add("yem_planindate");
        fieldKeys.add("yem_planoutdate");
        fieldKeys.add("yem_arrangeshippingqty");
        fieldKeys.add("yem_tickoutqty");
        fieldKeys.add("yem_tickinqty");
        fieldKeys.add("yem_tickpayqtybase");
        fieldKeys.add("yem_tivkoutreceqtybase");
        fieldKeys.add("yem_amountfield2");
        fieldKeys.add("yem_tickcollectionamt");
        fieldKeys.add("yem_tivkdelicereceqty");
        fieldKeys.add("yem_remark");
        fieldKeys.add("yem_uncontrolledqty");
        fieldKeys.add("yem_qtyexceedsratio");
        fieldKeys.add("yem_qtyshortagerate");
        fieldKeys.add("yem_lifesoopcustomer");
        fieldKeys.add("yem_totalpurreturnqty");
        fieldKeys.add("yem_totasalereturnqty");
        fieldKeys.add("yem_totalpurretqtybase");
        fieldKeys.add("yem_totasaleretqtybase");
        fieldKeys.add("yem_biztype");
        fieldKeys.add("yem_bizdate");
        fieldKeys.add("creator");
        fieldKeys.add("createtime");
        fieldKeys.add("yem_baseqty");
        fieldKeys.add("yem_gift");
        fieldKeys.add("yem_businesssort");
        fieldKeys.add("yem_gift");

    }

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        String operationKey = e.getOperationKey();
        try {
            //同步EAS
            if("syneas".equals(operationKey)){
                DynamicObject[] dataEntities = e.getDataEntities();
                for (DynamicObject dataEntity: dataEntities) {
                    Object pkValue = dataEntity.getPkValue();
                    DynamicObject dynamicObject =
                            BusinessDataServiceHelper.loadSingle(pkValue, dataEntity.getDynamicObjectType());
                    DynamicObject[] transferorder = new DynamicObject[]{dynamicObject};
                    JSONArray json = getJSON(transferorder);
                }
            }

        }catch (Exception ex){
            log.error("同步EAS异常请联系管理员:"+ex.getMessage());
            throw new KDBizException("同步EAS异常"+ex.getMessage());
        }
    }


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

            JSONObject json = new JSONObject();
            //单据编号
            json.put("number",dataEntitie.getString("billno"));
            //供应方财务组织
            DynamicObject yemSupfinorg = dataEntitie.getDynamicObject("yem_supfinorg");
            if (yemSupfinorg!=null){
                json.put("issueCompanyOrgUnit",setJson("number",yemSupfinorg.getString("number")));
            }
            //需求方财务组织
            DynamicObject yemCusfinorg = dataEntitie.getDynamicObject("yem_cusfinorg");
            if (yemCusfinorg!=null){
                json.put("receiptCompanyOrgUnit",setJson("number",yemCusfinorg.getString("number")));
            }
            //调出部门
            DynamicObject yemOutdept = dataEntitie.getDynamicObject("yem_outdept");
            if (yemOutdept!=null){
                json.put("issueAdminOrgUnit",setJson("number",yemOutdept.getString("number")));
            }
            //业务方向
            json.put("bizDirection",dataEntitie.getInt("yem_businessdirection"));
            //领料人
            DynamicObject yemApplyuser = dataEntitie.getDynamicObject("yem_applyuser");
            if (yemApplyuser!=null){
                json.put("person",setJson("number",yemApplyuser.getString("number")));
            }
            //业务类型 yem_biztype
            DynamicObject yemBiztype = dataEntitie.getDynamicObject("yem_biztype");
            if (yemBiztype!=null){
                //json.put("bizType",setJson("number",yemBiztype.getString("number")));
                json.put("bizType",setJson("number","310"));
            }

            //供应方库存组织
            DynamicObject yemSupstockorg = dataEntitie.getDynamicObject("yem_supstockorg");
            if (yemSupstockorg!=null){
                json.put("issueStorageOrgUnit",setJson("number",yemSupstockorg.getString("number")));
            }
            //需求方库存组织
            DynamicObject yemCusstockorg = dataEntitie.getDynamicObject("yem_cusstockorg");
            if (yemCusstockorg!=null){
                json.put("receiptStorageOrgUnit",setJson("number",yemCusstockorg.getString("number")));
            }
            //调入部门
            DynamicObject yemIndept = dataEntitie.getDynamicObject("yem_indept");
            if (yemIndept!=null){
                json.put("receiptAdminOrgUnit",setJson("number",yemIndept.getString("number")));
            }
            //摘要
            json.put("description",dataEntitie.getString("yem_abstract"));
            //领料部门
            DynamicObject yemDepartment = dataEntitie.getDynamicObject("yem_department");
            if (yemDepartment!=null){
                json.put("department",setJson("number",yemDepartment.getString("number")));
            }
            //业务日期
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            String yemBizdate = fmt.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("isInTax",dataEntitie.getBoolean("yem_includingtax"));
            //初始化
            json.put("isInitBill",dataEntitie.getBoolean("yem_initialization"));
            //费用项目
            DynamicObject yemExpenseitemedit = dataEntitie.getDynamicObject("yem_expenseitemedit");
            if (yemExpenseitemedit!=null){
                json.put("feeProjet",setJson("number",yemExpenseitemedit.getString("number")));
            }
            //研发项目
            DynamicObject yemRdprojects = dataEntitie.getDynamicObject("yem_rdprojects");
            if (yemRdprojects!=null){
                json.put("yfproject",setJson("number",yemRdprojects.getString("number")));
            }
            //工程项目
            DynamicObject yemProject = dataEntitie.getDynamicObject("yem_project");
            if (yemProject!=null){
                json.put("enProject",setJson("number",yemProject.getString("number")));
            }

            //审核人
            DynamicObject auditor = dataEntitie.getDynamicObject("auditor");
            if (auditor!=null){
                //json.put("auditor",setJson("number",auditor.getString("number")));
                //json.put("auditor",setJson("number","00003"));
            }
            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);
            }

            //明细信息分录
            //商品明细
            DynamicObjectCollection yem_es_materialinfocoll = dataEntitie.getDynamicObjectCollection("yem_es_materialinfo");
            JSONArray entry = getEntry(yem_es_materialinfocoll,dataEntitie);
            json.put("entry",entry);
            jsonArray.add(json);
            log.debug(dataEntitie.getString("billno")+"调拨订单同步EASjson"+jsonArray.toJSONString());
            setWebService(jsonArray,dataEntitie);
        }

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

        for (DynamicObject yem_es_materialinfo: yem_es_materialinfocoll) {
            //如果是赠品不获取价格
            boolean yemGift = yem_es_materialinfo.getBoolean("yem_gift");
            if(yemGift){
                //如果配件类型没有价格提示
            }else if("P".equals(yem_es_materialinfo.getString("yem_businesssort"))){

                if (yem_es_materialinfo.getBigDecimal("yem_pricetax") == null || yem_es_materialinfo.getBigDecimal("yem_pricetax").compareTo(BigDecimal.ZERO) < 1) {
                    throw new KDBizException("商品明细中配件未获取到调拨价格无法同步EAS！");
                }
            }
            JSONObject json = new JSONObject();
            //苍穹分录ID
            json.put("plmeid",yem_es_materialinfo.getPkValue());
            //物料编码
            DynamicObject yemMateriel = yem_es_materialinfo.getDynamicObject("yem_materiel");
            if (yemMateriel!=null){
                json.put("material",setJson("number",yemMateriel.getString("number")));
            }
            //辅助属性
            //json.put("assistProperty",yem_es_materialinfo.getString("yem_assistnature"));
            //批次
            json.put("lot",yem_es_materialinfo.getString("yem_batch"));
            //需求传递
            json.put("isMrpCal",yem_es_materialinfo.getBoolean("yem_needtransfer"));
            //生产日期
            SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            Date yemProductdate = yem_es_materialinfo.getDate("yem_productdate");
            if (yemProductdate!=null){
                String yemProductdates = fmt.format(yemProductdate);
                json.put("mfg",yemProductdates);
            }
            //到期日期
            Date yemDuedate = yem_es_materialinfo.getDate("yem_duedate");
            if (yemDuedate!=null){
                String yemDuedates = fmt.format(yemDuedate);
                json.put("exp",yemDuedates);
            }
            //计量单位
            DynamicObject yemUnit = yem_es_materialinfo.getDynamicObject("yem_unit");
            if (yemUnit!=null){
                json.put("unit",setJson("number",yemUnit.getString("number")));
            }
            //数量
            json.put("qty",yem_es_materialinfo.getBigDecimal("yem_qty"));
            //基本计量单位
            DynamicObject yemBaseunit = yem_es_materialinfo.getDynamicObject("yem_baseunit");
            if (yemBaseunit!=null){
                json.put("baseUnit",setJson("number",yemBaseunit.getString("number")));
            }
            //基本数量
            json.put("baseQty",yem_es_materialinfo.getBigDecimal("yem_baseqty"));

            //辅助计量单位
            DynamicObject yemAssistunit = yem_es_materialinfo.getDynamicObject("yem_assistunit");
            if (yemAssistunit!=null){
                json.put("assistQty",setJson("number",yemAssistunit.getString("number")));
            }
            //单价
            json.put("price",yem_es_materialinfo.getBigDecimal("yem_price"));
            //辅助数量
            json.put("assistQty",yem_es_materialinfo.getBigDecimal("yem_assistqty"));
            //发货库存组织
            DynamicObject yemDeliveryinventoryorg = yem_es_materialinfo.getDynamicObject("yem_deliveryinventoryorg");
            if (yemDeliveryinventoryorg!=null){
                json.put("issueStorageOrgUnit",setJson("number",yemDeliveryinventoryorg.getString("number")));
            }
            //发货方销售组织
            DynamicObject yemShippersalesorg = yem_es_materialinfo.getDynamicObject("yem_shippersalesorg");
            if (yemShippersalesorg!=null){
                json.put("issueSaleOrgUnit",setJson("number",yemShippersalesorg.getString("number")));
            }
            //发货仓库
            DynamicObject yemDeliverywarehouse = yem_es_materialinfo.getDynamicObject("yem_deliverywarehouse");
            if (yemDeliverywarehouse!=null){
                json.put("issueWarehouse",setJson("number",yemDeliverywarehouse.getString("number")));
            }
            //发货库位 yem_deliveryposition
            DynamicObject yemDeliveryposition = yem_es_materialinfo.getDynamicObject("yem_deliveryposition");
            if (yemDeliveryposition!=null){
                json.put("issueLocation",setJson("number",yemDeliveryposition.getString("number")));
            }
            //收货库存组织
            DynamicObject yemReceinventoryorg = yem_es_materialinfo.getDynamicObject("yem_receinventoryorg");
            if (yemReceinventoryorg!=null){
                json.put("receiveStorageOrgUnit",setJson("number",yemReceinventoryorg.getString("number")));
            }
            //收货仓库
            DynamicObject yemReceinventory = yem_es_materialinfo.getDynamicObject("yem_receinventory");
            if (yemReceinventory!=null){
                json.put("receiptWarehouse",setJson("number",yemReceinventory.getString("number")));
            }
            //收货库位
            DynamicObject yemReceposition = yem_es_materialinfo.getDynamicObject("yem_receposition");
            if (yemReceposition!=null){
                json.put("receiptLocation",setJson("number",yemReceposition.getString("number")));
            }
            //需求仓库
            DynamicObject yemCuswarehouse = yem_es_materialinfo.getDynamicObject("yem_cuswarehouse");
            if (yemCuswarehouse!=null){
                json.put("requireWarehouse",setJson("number",yemCuswarehouse.getString("number")));
            }
            //赠品
            json.put("isPresent",yem_es_materialinfo.getBoolean("yem_gift"));
            //折扣方式
            String yemDiscountmethod = yem_es_materialinfo.getString("yem_discountmethod");
            if (yemDiscountmethod!=null){
                if ("A".equals(yemDiscountmethod)){//折扣比率
                    json.put("discountType",0);
                }else if("B".equals(yemDiscountmethod)){//单位折扣额
                    json.put("discountType",1);
                }
            }
            //单位折扣率
            json.put("discountRate", yem_es_materialinfo.getBigDecimal("yem_pricediscountrate"));
            //实际单价
            json.put("actualPrice", yem_es_materialinfo.getBigDecimal("yem_price"));
            //税率%
            json.put("taxRate", yem_es_materialinfo.getBigDecimal("yem_taxrate"));
            //含税单价
            json.put("taxPrice", yem_es_materialinfo.getBigDecimal("yem_pricetax"));
            //实际含税单价
            json.put("actualTaxPrice", yem_es_materialinfo.getBigDecimal("yem_realitypricetax"));
            //金额
                json.put("amount", yem_es_materialinfo.getBigDecimal("yem_amt"));
            //本位币金额
            json.put("localAmount", yem_es_materialinfo.getBigDecimal("yem_locamt"));
            //税额
            json.put("tax", yem_es_materialinfo.getBigDecimal("yem_amounttax"));
            //本位币税额
            json.put("localTax", yem_es_materialinfo.getBigDecimal("yem_amountfield1"));
            //价税合计
            json.put("taxAmount", yem_es_materialinfo.getBigDecimal("yem_amttax"));
            //本位币价税合计
            json.put("localTaxAmount", yem_es_materialinfo.getBigDecimal("yem_baseamttax"));
            //计划调入日期
            Date yemPlanindate = yem_es_materialinfo.getDate("yem_planindate");
            if (yemPlanindate!=null){
                json.put("receiptPlanDate", fmt.format(yemPlanindate));
            }

            //计划调出日期
            Date yemPlanoutdate = yem_es_materialinfo.getDate("yem_planoutdate");
            if (yemPlanoutdate!=null){
                json.put("issuePlanDate", fmt.format(yemPlanoutdate));
            }
            //安排发运数量
            json.put("planDeliveryQty", yem_es_materialinfo.getBigDecimal("yem_arrangeshippingqty"));
            //累计出库数量
            json.put("issueQty", yem_es_materialinfo.getBigDecimal("yem_tickoutqty"));
            //累计入库数量
            json.put("receiptQty", yem_es_materialinfo.getBigDecimal("yem_tickinqty"));
            //累计应付基本数量
            json.put("purInvoiceBaseQty", yem_es_materialinfo.getBigDecimal("yem_tickpayqtybase"));
            //累计应收基本数量
            json.put("saleInvoiceBaseQty", yem_es_materialinfo.getBigDecimal("yem_tivkoutreceqtybase"));
            //累计付款金额
            json.put("totalAccountPayable", yem_es_materialinfo.getBigDecimal("yem_amountfield2"));
            //累计收款金额
            json.put("totalAccountReceivable", yem_es_materialinfo.getBigDecimal("yem_tickcollectionamt"));
            //累计通知发货数量
            json.put("totalIssueQty", yem_es_materialinfo.getBigDecimal("yem_tivkdelicereceqty"));
            //TODO 行状态先不穿 看看传过去是不是默认
            //备注
            json.put("remark", yem_es_materialinfo.getString("yem_remark"));
            //不控制数量
            json.put("notControlQty", yem_es_materialinfo.getBigDecimal("yem_uncontrolledqty"));
            //数量超出比率%
            json.put("qtyOverRate", yem_es_materialinfo.getBigDecimal("yem_qtyexceedsratio"));
            // 数量短缺比率%
            json.put("qtyLackRate", yem_es_materialinfo.getBigDecimal("yem_qtyshortagerate"));
            //补货方式
            //直送客户
            DynamicObject yemLifesoopcustomer = yem_es_materialinfo.getDynamicObject("yem_lifesoopcustomer");
            if (yemLifesoopcustomer!=null){
                json.put("directCustomer",setJson("number",yemLifesoopcustomer.getString("number")));
            }
            //累计采购退货数量
            json.put("totalPurReturnBaseQty", yem_es_materialinfo.getBigDecimal("yem_totalpurreturnqty"));
            //累计销售退货数量
            json.put("totalSaleReturnBaseQty", yem_es_materialinfo.getBigDecimal("yem_totasalereturnqty"));
            //累计采购退货基本数量
            json.put("totalPurReturnQty", yem_es_materialinfo.getBigDecimal("yem_totalpurretqtybase"));
            //累计销售退货基本数量
            json.put("totalSaleReturnBaseQty", yem_es_materialinfo.getBigDecimal("yem_totasaleretqtybase"));
            jsonArray.add(json);
        }
        return jsonArray;
    }

    private void setWebService(JSONArray json,DynamicObject dataEntitie){
        String service = RequestEAS.getService(json.toJSONString(), "004");
        JSONObject jsonObject = JSON.parseObject(service);
        String status = jsonObject.getString("status");
        String msg = jsonObject.getString("msg");
        if (!"0".equals(status)){
            JSONArray billErrors = jsonObject.getJSONArray("billErrors");
            String errorMsgs = "";
            int i = 1;
            for (Object billError: billErrors) {
                JSONObject js = (JSONObject) billError;
//                errorMsgs = js.getString("errorMsgs");
                if (errorMsgs.length() > 0) {
                    errorMsgs = errorMsgs + "\n" + i+"、"+js.getString("errorMsgs");
                } else {
                    errorMsgs = i+"、"+js.getString("errorMsgs");
                }
                i++;
            }
            dataEntitie.set("yem_synfalt",msg + "\n" + errorMsgs);
            SaveServiceHelper.update(dataEntitie);
//            throw new KDBizException(msg + errorMsgs);
            this.operationResult.addErrorInfo(
                    new ValidationErrorInfo(
                            "", dataEntitie.getPkValue(), 0, 0, "err", "同步EAS失败", msg + errorMsgs, ErrorLevel.Error));
        }else {
            dataEntitie.set("yem_iseas",true);
            dataEntitie.set("yem_synfalt","同步EAS成功！");
            SaveServiceHelper.update(dataEntitie);
        }
    }

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

}
