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.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.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.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author 涛
 * @date 2023/12/04
 * 订单产品需求单_配件采购计划-服务插件-同步CMMP 其他领料申请
 */
public class OrderProReqBillCG extends AbstractOperationServicePlugIn {
    private final static Log log = LogFactory.getLog(OrderProReqBillCG.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_receiveruser");
        fieldKeys.add("yem_arrivedate");
        fieldKeys.add("yem_buyerr");
        fieldKeys.add("yem_iscmmppj");
        fieldKeys.add("yem_bd_products");
        fieldKeys.add("yem_qualitierr");

    }

    @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("need_code",dataEntity.getString("billno"));

            //外贸系统单据创建人对应的EAS用户，统一按工号传递。
            DynamicObject creator = dataEntity.getDynamicObject("creator");
            if (creator!=null){
                json.put("plmcreator",creator.getString("number"));
                json.put("need_userid",creator.getString("number"));
            }

            //SimpleDateFormat fmtTime = new SimpleDateFormat();
            //DateTimeFormatter fmtTime = 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);
            json.put("need_date",localDateTime);
            //申请原因
            json.put("reason_code",dataEntity.getString("yem_reasoncode"));
            //申请人
//            DynamicObject applyuser = dataEntity.getDynamicObject("yem_applyuser");
//            if (applyuser!=null){
//                json.put("plmcreator",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"));
            }
            //到货日期
            String yemArrivedate = fmtDate.format(dataEntity.getDate("yem_arrivedate"));
            json.put("arrive_date",yemArrivedate);

            //默认值
            //单据状态
            json.put("main_state","30");
            //是否计划增补
            json.put("is_planadd","0");

            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();

                //创建人
                entry.put("plmcreator",creator.getString("number"));

                //更新人
                entry.put("plmupdator",creator.getString("number"));
                //创建日期
                entry.put("plmcreatedate",localDateTime);
                //更新时间
                entry.put("plmlastupdate",localDateTime);
                //申请单号
                entry.put("need_code",dataEntity.getString("billno"));



                DynamicObject yemMateriel = esMaterial.getDynamicObject("yem_materiel");
                if (yemMateriel!=null){
                    //物料代码
                    entry.put("mater_code",yemMateriel.getString("number"));
                    //物料名称
                    entry.put("mater_name",yemMateriel.getString("name"));
                    DynamicObject baseunit = yemMateriel.getDynamicObject("baseunit");
                    if (baseunit!=null){
                        //单位
                        entry.put("unit_code",baseunit.getString("number"));
                    }
                    //规格型号
                     entry.put("specification",yemMateriel.getString("modelnum"));
                }
                //需求数量
                entry.put("need_num",esMaterial.getString("yem_qty"));
                //提交数量
                entry.put("tj_num",esMaterial.getString("yem_qty"));
                // 制造商编码
                entry.put("supplier_code",esMaterial.getString("yem_manufacturer"));
                // 制造商名称
                entry.put("supplier_name",esMaterial.getString("yem_manufacturername"));
                //到货日期
                entry.put("arrive_date",yemArrivedate);
                //仓库代码
                DynamicObject yemWarehouse = esMaterial.getDynamicObject("yem_warehouse");
                if (yemWarehouse!=null){
                    entry.put("wh_code",yemWarehouse.getString("number"));
                    entry.put("wh_name",yemWarehouse.getString("name"));
                }
                //调入保管员编码
                DynamicObject whman = esMaterial.getDynamicObject("yem_whman");
                if (whman!=null){
                    entry.put("stocker_code",whman.getString("number"));
                    entry.put("stocker_name",whman.getString("name"));
                }
                //备注
                entry.put("detail_remark",esMaterial.getString("yem_remarks1"));

                //提报部门编码
                if (depcode!=null){
                    entry.put("dep_code",depcode.getString("number"));
                    entry.put("dep_name",depcode.getString("name"));
                }
                //采购员编码
                DynamicObject yemBuyerr = esMaterial.getDynamicObject("yem_buyerr");
                DynamicObject qualitierr = esMaterial.getDynamicObject("yem_qualitierr");
                if (yemBuyerr!=null){
                    entry.put("buyer_code",yemBuyerr.getString("number"));
                }
                if (qualitierr!=null){
                    entry.put("checker_code",qualitierr.getString("number"));
                }
                //供应商编码
                DynamicObject sup = esMaterial.getDynamicObject("yem_sup");
                if (sup!=null){
                    entry.put("sup_code",sup.getString("number"));
                    entry.put("sup_name",sup.getString("name"));
                }

                //默认值
                //物料用途：zc正常、lf料废、pj配件
                entry.put("mater_usage","ZC");
                //明细状态
                entry.put("detail_state","30");
                //已分配数量
                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");
            //如果单据类型等于配件采购计划
            if ("yem_orderproreqbill_CG".equals(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 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/purNeed/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_iscmmppj",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));
        }

    }

}
