package com.yem.wm.syn.cmmp.addnew;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.wm.syn.eas.YemOrderproreqbillWGService;
import com.yem.wm.syn.utils.HttpClient;
import com.yem.wm.utils.RequestCmmp;
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.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.sdk.util.KHttpClientUtils;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 涛
 * @date 2023/12/04
 * 订单产品需求单_配件调拨计划-服务插件-同步CMMP
 */
public class OrderProReqBill extends AbstractOperationServicePlugIn {
    private final static Log log = LogFactory.getLog(OrderProReqBill.class);
    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> fieldKeys = e.getFieldKeys();
        fieldKeys.add("yem_billtype");
        fieldKeys.add("creator");
        fieldKeys.add("createtime");
        fieldKeys.add("yem_indepcode");
        fieldKeys.add("yem_reasoncode");
        fieldKeys.add("yem_applyuser");
        fieldKeys.add("yem_bizdate");
        fieldKeys.add("yem_contremark");
        fieldKeys.add("yem_depcode");
        fieldKeys.add("yem_es_materialinfo");
        fieldKeys.add("yem_materiel");
        fieldKeys.add("yem_isvmi");
        fieldKeys.add("yem_qty");
        fieldKeys.add("yem_manufacturer");
        fieldKeys.add("yem_manufacturername");
        fieldKeys.add("yem_remarks1");
        fieldKeys.add("yem_warehouse");
        fieldKeys.add("yem_whman");
        fieldKeys.add("yem_outwhcode");
        fieldKeys.add("yem_outstockercode");
        fieldKeys.add("yem_whlocation");
        fieldKeys.add("yem_warearea");
        fieldKeys.add("yem_outpositioncode");
        fieldKeys.add("yem_outareacode");
        fieldKeys.add("yem_stockbatch");
        fieldKeys.add("yem_sup");
        fieldKeys.add("yem_transfercode");
        fieldKeys.add("yem_callinorg");
        fieldKeys.add("yem_calloutorg");
        fieldKeys.add("yem_retrievecode");
        fieldKeys.add("yem_retrievecode");
        fieldKeys.add("yem_bd_products");
        fieldKeys.add("yem_iscmmp");

    }

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        //获取配件调拨计划
        DynamicObject[] dataEntite = isBillType(dataEntities);
        if (dataEntite.length==0){
            return;
        }
        getJSON(dataEntite);
    }

    private void getJSON(DynamicObject[] dataEntities) {
        for (DynamicObject dataEntity: dataEntities) {
            JSONObject json = new JSONObject();
            //申请单号
            json.put("apply_code",dataEntity.getString("billno"));
            //外贸系统单据创建人对应的EAS用户，统一按工号传递。
            DynamicObject creator = dataEntity.getDynamicObject("creator");
            if (creator!=null){
                json.put("plmcreator",creator.getString("number"));
            }

            //SimpleDateFormat fmtTime = new mater_usage= DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
            //创建日期
            Date createtime = dataEntity.getDate("createtime");
            Instant createtimeinstant = createtime.toInstant();
            ZoneId zoneId = ZoneId.systemDefault();
            LocalDateTime localDateTime = createtimeinstant.atZone(zoneId).toLocalDateTime();
            json.put("plmcreatedate",localDateTime);

            //调入部门编码
            DynamicObject yemIndepcode = dataEntity.getDynamicObject("yem_indepcode");
            if (yemIndepcode!=null){
                json.put("in_dep_code",yemIndepcode.getString("number"));
                //调入部门名称
                json.put("in_dep_name",yemIndepcode.getString("name"));
            }
            //申请原因
            json.put("reason_code",dataEntity.getString("yem_reasoncode"));
            //申请人
            DynamicObject applyuser = dataEntity.getDynamicObject("yem_applyuser");
            if (applyuser!=null){
                json.put("apply_userid",applyuser.getString("number"));
            }

            //申请日期
            SimpleDateFormat fmtDate = new SimpleDateFormat("yyyy-MM-dd");
            String yemBizdate = fmtDate.format(dataEntity.getDate("yem_bizdate"));
            json.put("apply_date",yemBizdate);
            //备注
            json.put("main_remark",dataEntity.getString("yem_contremark"));
            //申请部门编码
            DynamicObject depcode = dataEntity.getDynamicObject("yem_depcode");
            if (depcode!=null){
                json.put("dep_code",depcode.getString("number"));
                json.put("dep_name",depcode.getString("name"));
                json.put("dep_fid",depcode.getString("yem_easid"));
            }

            //调入仓库代码
            DynamicObject yem_transfercode = dataEntity.getDynamicObject("yem_transfercode");
            if (yem_transfercode!=null){
                json.put("in_wh_code",yem_transfercode.getString("number"));
                json.put("in_wh_name",yem_transfercode.getString("name"));
                json.put("in_wh_fid",yem_transfercode.getString("yem_easid"));

            }
            //调出仓库代码
            DynamicObject yem_retrievecode = dataEntity.getDynamicObject("yem_retrievecode");
            if (yem_retrievecode!=null){
                json.put("out_wh_code",yem_retrievecode.getString("number"));
                json.put("out_wh_name",yem_retrievecode.getString("name"));
                json.put("out_wh_fid",yem_retrievecode.getString("yem_easid"));
            }


            //调入库存组织
            DynamicObject yem_callinorg = dataEntity.getDynamicObject("yem_callinorg");
            if (yem_callinorg!=null){
                json.put("in_wh_org_fid",yem_callinorg.getString("yem_easid"));
            }

            //调出库存组织
            DynamicObject yem_calloutorg = dataEntity.getDynamicObject("yem_calloutorg");
            if (yem_calloutorg!=null){
                json.put("out_wh_org_fid",yem_calloutorg.getString("yem_easid"));
            }

            //默认值
            //物料用途：zc正常、lf料废、pj配件
            json.put("mater_usage","ZC");
            //单据状态
            json.put("main_state","30");
            //一级单据类型编码
            json.put("type_one_code","80");
            //一级单据类型名称
            json.put("type_one_name","调拨单");
            //二级单据类型编码
            json.put("type_two_code","8010");
            //二级单据类型名称
            json.put("type_two_name","普通调拨入库跨仓库");
            //eas单据类型
            json.put("djlx_fid","50957179-0105-1000-e003-3152c0a812fd463ED552");
            //eas业务类型
            json.put("ywlx_fid","d8e80652-011b-1000-e000-04c5c0a812202407435C");
            //eas更新类型唯一值
            json.put("gxlx_fid","8r0AAAAEaOjC73rf");
            //入库物料用途
            json.put("in_mater_usage","ZC");


            JSONObject jsonObject = new JSONObject();
            jsonObject.put("bill",json);
            JSONObject jsonentry = new JSONObject();
            JSONArray jsonArray = new JSONArray();
            DynamicObjectCollection yemEsMaterialcoll = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            for (DynamicObject esMaterial: yemEsMaterialcoll) {
                JSONObject entry = new JSONObject();
                DynamicObject yemMateriel = esMaterial.getDynamicObject("yem_materiel");
                if (yemMateriel!=null){
                    //物料代码
                    entry.put("mater_code",yemMateriel.getString("number"));
                    //物料名称
                    entry.put("mater_name",yemMateriel.getString("name"));
                    //id
                    entry.put("mater_fid",yemMateriel.getString("yem_easid"));
                    DynamicObject baseunit = yemMateriel.getDynamicObject("baseunit");
                    if (baseunit!=null){
                        DynamicObject dynamicObject = QueryServiceHelper.queryOne(baseunit.getDataEntityType().getName(), "id,yem_easid", new QFilter[]{new QFilter("id", QCP.equals, baseunit.getPkValue())});
                        //单位
                        entry.put("unit_code",baseunit.getString("number"));
                        entry.put("unit_fid",dynamicObject.getString("yem_easid"));
                    }
                }
                entry.put("plmcreator",creator.getString("number"));
                entry.put("plmcreatedate",localDateTime);
                //需求数量
                entry.put("order_num",esMaterial.getString("yem_qty"));
                entry.put("apply_code",dataEntity.getString("billno"));
                //已确认数量
                entry.put("qr_num",esMaterial.getString("yem_qty"));
                // 制造商编码
                entry.put("supplier_code",esMaterial.getString("yem_manufacturer"));
                // 制造商名称
                entry.put("supplier_name",esMaterial.getString("yem_manufacturername"));
                //备注
                entry.put("detail_remark",esMaterial.getString("yem_remarks1"));
                //调入仓库代码
                DynamicObject yemWarehouse = esMaterial.getDynamicObject("yem_warehouse");
                if (yemWarehouse!=null){
                    entry.put("out_wh_code",yemWarehouse.getString("number"));
                    entry.put("out_wh_name",yemWarehouse.getString("name"));

                }
                //调入保管员编码
                DynamicObject whman = esMaterial.getDynamicObject("yem_whman");
                if (whman!=null){
                    entry.put("out_stocker_code",whman.getString("number"));
                    entry.put("out_stocker_name",whman.getString("name"));
                }
                //调出仓库代码 yem_outwhcode
                DynamicObject outwhcode = esMaterial.getDynamicObject("yem_outwhcode");
                if (outwhcode!=null){

                    entry.put("in_wh_code",outwhcode.getString("number"));
                    entry.put("in_wh_name",outwhcode.getString("name"));
                }

                //调出保管员编码
                DynamicObject outstockercode = esMaterial.getDynamicObject("yem_outstockercode");
                if (outstockercode!=null){


                    entry.put("in_stocker_code",outstockercode.getString("number"));
                    entry.put("in_stocker_name",outstockercode.getString("name"));
                }

                //库位编码
                DynamicObject whlocation = esMaterial.getDynamicObject("yem_whlocation");
                if (whlocation!=null){
                    entry.put("out_position_code",whlocation.getString("number"));
                    entry.put("out_position_name",whlocation.getString("name"));
                }

                //库区编码
                DynamicObject warearea = esMaterial.getDynamicObject("yem_warearea");
                if (warearea!=null){
                    entry.put("out_area_code",warearea.getString("number"));
                    entry.put("out_area_name",warearea.getString("name"));
                    entry.put("in_area_fid",warearea.getString("yem_easid"));
                }

                //调出库位编码
                DynamicObject outpositioncode = esMaterial.getDynamicObject("yem_outpositioncode");
                if (outpositioncode!=null){
                    entry.put("in_position_code",outpositioncode.getString("number"));
                    entry.put("in_position_name",outpositioncode.getString("name"));
                }

                //调出库区编码
                DynamicObject outareacode = esMaterial.getDynamicObject("yem_outareacode");
                if (outareacode!=null){
                    entry.put("in_area_code",outareacode.getString("number"));
                    entry.put("in_area_name",outareacode.getString("name"));
                    entry.put("out_area_fid",outareacode.getString("yem_easid"));
                }
                //调出库存批次号
                entry.put("stock_batch",esMaterial.getString("yem_stockbatch"));
                //供应商编码
                DynamicObject sup = esMaterial.getDynamicObject("yem_sup");
                if (sup!=null){
                    entry.put("sup_code",sup.getString("number"));
                    entry.put("sup_name",sup.getString("name"));
                }
                //默认值
                //明细状态
                entry.put("detail_state","30");
                //物料用途：zc正常、lf料废、pj配件
                entry.put("mater_usage","ZC");
                //已分配数量
                entry.put("fp_num","0");

                jsonArray.add(entry);
            }
            jsonentry.put("entry",jsonArray);
            jsonObject.putAll(jsonentry);
            setData(dataEntity,jsonObject);
        }

    }




    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");
            String number = yemBilltype.getString("number");
            String yemIsvmi = dataEntity.getString("yem_isvmi");
            //如果单据类型等于配件调拨计划 并且 仓库类型为正常仓库
            if ("yem_orderproreqbill_DB".equals(number)&&"C".equals(yemIsvmi)){
                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 void setData(DynamicObject dataEntity,JSONObject jsonObject){
        //产品类型
        DynamicObject yem_bd_products = dataEntity.getDynamicObject("yem_bd_products");
        Long productsId = RequestCmmp.getTopCplx(yem_bd_products);
        DynamicObject cmmpconfig = QueryServiceHelper.queryOne("yem_cmmpconfig", "yem_ip,yem_port,yem_num",
                new QFilter[]{new QFilter("yem_cmmpconfigentry.yem_bd_productsgroupn.id", QCP.equals, productsId)});

         if (cmmpconfig == null){
            this.operationResult.addErrorInfo(new ValidationErrorInfo("",dataEntity.getPkValue(), 0,0,"err","同步CMMP",dataEntity.getString("billno")+"同步CMMP失败:未找到产品类型为"+yem_bd_products.getString("name")+"的CMMP配置,请联系管理员确认!", ErrorLevel.Error));
            return;
        }
        String database = cmmpconfig.getString("yem_num");
        String ip = cmmpconfig.getString("yem_ip");
        String port = cmmpconfig.getString("yem_port");
        try {
            String url = "http://"+ip+":"+port+"/gateway/cosmic/cmmp/dbApply/add/"+database;
            String data = HttpClient.post(url,jsonObject.toJSONString());
            JSONObject json = JSON.parseObject(data);
            String status = json.getString("status");
            if (!"0".equals(status)){
                String billErrors = json.getString("billErrors");
                this.operationResult.addErrorInfo(new ValidationErrorInfo("",dataEntity.getPkValue(), 0,0,"err","同步CMMP",dataEntity.getString("billno")+"同步CMMP失败:"+billErrors, ErrorLevel.Error));
            }
            dataEntity.set("yem_iscmmp",true);
            SaveServiceHelper.update(dataEntity);

        }catch (Exception e){
            this.operationResult.addErrorInfo(new ValidationErrorInfo("",dataEntity.getPkValue(), 0,0,"err","同步CMMP",dataEntity.getString("billno")+"同步CMMP失败:"+e.getMessage(), ErrorLevel.Error));
        }

    }

}
