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.dataentity.entity.LocaleString;
import kd.bos.entity.ValueMapItem;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.entity.property.ComboProp;
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.*;

/**
 * @author 涛
 * @date 2023/12/04
 * 订单产品需求单_配件调拨计划WMI-服务插件-同步CMMP 其他领料申请
 */
public class OrderProReqBillWMI extends AbstractOperationServicePlugIn {
    private final static Log log = LogFactory.getLog(OrderProReqBillWMI.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_gcxm");
        fieldKeys.add("yem_yfxm");
        fieldKeys.add("yem_fyxm");
        fieldKeys.add("yem_iscmmpapply");
        fieldKeys.add("yem_bd_products");

    }

    @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) {
            dataEntity = BusinessDataServiceHelper.loadSingle(dataEntity.getPkValue(), dataEntity.getDynamicObjectType().getName());
            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"));
            }

            //单据状态
            json.put("main state","30");

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

            //调入部门编码
            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 receiverUserid = dataEntity.getDynamicObject("yem_receiveruser");
            if (receiverUserid!=null){
                json.put("receiver_userid",receiverUserid.getString("yem_easid"));
            }
            //工程项目
            DynamicObject yem_gcxm = dataEntity.getDynamicObject("yem_gcxm");
            if (yem_gcxm!=null){
                json.put("gcxm_code",yem_gcxm.getString("number"));
                json.put("gcxm_name",yem_gcxm.getString("name"));
                json.put("gcxm_fid",yem_gcxm.getString("yem_easid"));
            }
            //研发项目
            DynamicObject yem_yfxm = dataEntity.getDynamicObject("yem_yfxm");
            if (yem_yfxm!=null){
                json.put("yfxm_code",yem_yfxm.getString("number"));
                json.put("yfxm_name",yem_yfxm.getString("name"));
                json.put("yfxm_fid",yem_yfxm.getString("yem_easid"));
            }
            //费用项目
            DynamicObject yem_fyxm = dataEntity.getDynamicObject("yem_fyxm");
            if (yem_fyxm!=null){
                json.put("fyxm_code",yem_fyxm.getString("number"));
                json.put("fyxm_name",yem_fyxm.getString("name"));
                json.put("fyxm_fid",yem_fyxm.getString("yem_easid"));
            }

            //默认值
            //单据状态
            json.put("main_state","30");
            //物料用途：zc正常、lf料废、pj配件
            json.put("mater_usage","ZC");
            //一级单据类型编码
            json.put("type_one_code","35");
            //一级单据类型名称
            json.put("type_one_name","其他出库单");

            String typetwo = dataEntity.getString("yem_typetwo");

            Map<String, Object> downList = getDownList("yem_orderproreqbill", "yem_typetwo");

            //二级单据类型编码
            json.put("type_two_code", typetwo);
            String name = "";
            if (downList.containsKey(typetwo)) {
                LocaleString localeString = (LocaleString) downList.get(typetwo);
                name = localeString.getLocaleValue();
            }
            //二级单据类型名称
            json.put("type_two_name", name);


            //eas单据类型
            json.put("djlx_fid","50957179-0105-1000-e000-0177c0a812fd463ED552");
            //eas业务类型
            json.put("ywlx_fid","Nz878AEgEADgAABMwKg/GiQHQ1w=");
            //eas事务类型
            json.put("swlx_fid","DawAAAAPoCGwCNyn");
            //eas更新类型唯一值
            json.put("gxlx_fid","8r0AAAAEaOnC73rf");

            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("apply_code",dataEntity.getString("billno"));
                //物料用途: Zc正常、|料废、pj配件
                entry.put("mater_usage","ZC");
                //明细状态
                entry.put("detail_state","30");
                //已分配数量
                entry.put("fp_num","0");
                entry.put("TYPE_ONE_CODE","35");
                entry.put("TYPE_ONE_NAME","其他出库单");
                entry.put("TYPE_TWO_CODE","3510");
                entry.put("TYPE_TWO_NAME","其他出库");

                //仓库代码
                DynamicObject yemWarehouse = esMaterial.getDynamicObject("yem_warehouse");
                if (yemWarehouse!=null){
                    entry.put("wh_code",yemWarehouse.getString("number"));
                    entry.put("wh_name",yemWarehouse.getString("name"));
                }

                DynamicObject yemMateriel = esMaterial.getDynamicObject("yem_materiel");
                if (yemMateriel!=null){
                    //物料代码
                    entry.put("mater_code",yemMateriel.getString("number"));
                    //物料名称
                    entry.put("mater_name",yemMateriel.getString("name"));
                    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("specification",yemMateriel.getString("modelnum"));
                }
                //需求数量
                entry.put("order_num",esMaterial.getString("yem_qty"));
                // 制造商编码
                entry.put("supplier_code",esMaterial.getString("yem_manufacturer"));
                // 制造商名称
                entry.put("supplier_name",esMaterial.getString("yem_manufacturername"));


                //调入保管员编码
                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"));


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

                //库区编码
                DynamicObject warearea = esMaterial.getDynamicObject("yem_warearea");
                if (warearea!=null){
                    entry.put("area_code",warearea.getString("number"));
                    entry.put("area_name",warearea.getString("name"));
                    entry.put("area_fid",warearea.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");
            //如果单据类型等于配件调拨计划 并且 仓库类型为VMI
            if ("yem_orderproreqbill_DB".equals(number)&&"V".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/outApply/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_iscmmpapply",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));
        }

    }
    /**
     * @param fromMark  表单标识
     * @param fieldMark 字段标识
     * @return Map<String, Object>下拉列表键值对，key为下拉值，value为下拉标题(多语言）
     */
    public static Map<String, Object> getDownList(String fromMark, String fieldMark) {

        DynamicObject dynamicObject = BusinessDataServiceHelper.newDynamicObject(fromMark);
        ComboProp iDataEntityProperty = (ComboProp) dynamicObject.getDataEntityType().getProperties().get(fieldMark);
        HashMap<String, Object> mapSetResult = new HashMap<>(16);

        for (ValueMapItem comboItem : iDataEntityProperty.getComboItems()) {
            String key = comboItem.getValue();
            LocaleString value = comboItem.getName();
            mapSetResult.put(key, value);
        }

        return mapSetResult;
    }
}
