package com.yem.wm.im.delivernotice.op;

import com.yem.em.utils.AtlasUtils;
import com.yem.wm.im.delivernotice.utils.DeliverNoticeUtilsEdit;
import com.yem.wm.utils.RequestCmmp;
import com.yem.wm.utils.StringUtils;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.EndOperationTransactionArgs;
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.OperationServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.math.BigDecimal;
import java.util.*;

import static com.yem.em.utils.AtlasUtils.seelctDyn;


/**
 * @author zhouc
 * @Description 发货通知单【审核】生成《整机档案》服务插件
 * @date 11:05
 **/
public class DeliverNoticeAssAuditOpEdit extends AbstractOperationServicePlugIn {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        List<String> keys = e.getFieldKeys();
        keys.add("yem_billtype");
//        keys.add("");
//        keys.add("");
//        keys.add("");
    }

    @Override
    public void endOperationTransaction(EndOperationTransactionArgs e) {
        super.endOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        for (DynamicObject dataEntitie : dataEntities) {
            dataEntitie = BusinessDataServiceHelper.loadSingle(dataEntitie.getPkValue(), dataEntitie.getDynamicObjectType().getName());
            DynamicObject yemBilltype = dataEntitie.getDynamicObject("yem_billtype");
            if (yemBilltype != null) {
                if (yemBilltype.getString("number").equals("yem_es_delivernotice_zj")) {
                    addDeliverNotice(dataEntitie);
                }
            }
        }
    }

    /**
     * 生成整机档案
     *
     * @param dataEntitie
     */
    public void addDeliverNotice(DynamicObject dataEntitie) {
        List list = new ArrayList<>();
        DynamicObjectCollection yem_es_materialinfo = dataEntitie.getDynamicObjectCollection("yem_es_materialinfo");
        for (int i = 0; i < yem_es_materialinfo.size(); i++) {
            DynamicObject materialinfo = yem_es_materialinfo.get(i);
            DynamicObjectCollection yem_es_salesorder_z = materialinfo.getDynamicObjectCollection("yem_es_salesorder_z");
            for (int j = 0; j < yem_es_salesorder_z.size(); j++) {
                DynamicObject salesorder_z = yem_es_salesorder_z.get(j);
                String yemDevicefilesid = salesorder_z.getString("yem_vehicleno");
                if (yemDevicefilesid != null && StringUtils.isNotEmpty(yemDevicefilesid)) {
                    list.add(yemDevicefilesid);
                }
            }
        }
        Map map = new HashMap<>();
        QFilter qFilter = new QFilter("number", QCP.in, list);
        DynamicObjectCollection data = QueryServiceHelper.query("yem_em_devicefiles", "id,number", new QFilter[]{qFilter}, null);
        if (data.size() > 0) {
            for (int j = 0; j < data.size(); j++) {
                DynamicObject dynamicObject = data.get(j);
                map.put(dynamicObject.getString("number"), dynamicObject.getString("number"));
            }
        }
        for (int i = 0; i < yem_es_materialinfo.size(); i++) {
            DynamicObject materialinfo = yem_es_materialinfo.get(i);
            DynamicObjectCollection yem_es_salesorder_z = materialinfo.getDynamicObjectCollection("yem_es_salesorder_z");
            for (int j = 0; j < yem_es_salesorder_z.size(); j++) {
                DynamicObject salesorder_z = yem_es_salesorder_z.get(j);
                String yemVehicleno = salesorder_z.getString("yem_vehicleno");
                if (map.size() > 0) {
                    if (map.get(yemVehicleno) == null) {
                        DynamicObject adddevicefiles = adddevicefiles(dataEntitie,materialinfo, salesorder_z);
                        OperationResult Operate = OperationServiceHelper.executeOperate("save",
                                adddevicefiles.getDynamicObjectType().getName(), new DynamicObject[]{adddevicefiles}, OperateOption.create());
                        if (Operate.isSuccess()) {
                            salesorder_z.set("yem_devicefilesid", adddevicefiles.getString("id"));
                        }
                    }
                } else {
                    DynamicObject adddevicefiles = adddevicefiles(dataEntitie,materialinfo, salesorder_z);
                    OperationResult Operate = OperationServiceHelper.executeOperate("save",
                            adddevicefiles.getDynamicObjectType().getName(), new DynamicObject[]{adddevicefiles}, OperateOption.create());
                    if (Operate.isSuccess()) {
                        salesorder_z.set("yem_devicefilesid", adddevicefiles.getString("id"));
                    }
                }
            }
        }
        SaveServiceHelper.save(new DynamicObject[]{dataEntitie});
    }

    public DynamicObject adddevicefiles(DynamicObject dataEntitie,DynamicObject materialinfo, DynamicObject submaterialinfo) {
        String yem_vehicleno = submaterialinfo.getString("yem_vehicleno");
        String yem_conbillnumber = materialinfo.getString("yem_conbillnumber");//合同编号
        BigDecimal yem_qty = materialinfo.getBigDecimal("yem_qty");
        DynamicObject dynamicObject = BusinessDataServiceHelper.newDynamicObject("yem_em_devicefiles");
        dynamicObject.set("status", "C");
        dynamicObject.set("enable", "1");
        dynamicObject.set("number", yem_vehicleno);
        dynamicObject.set("createorg", seelctDyn("bos_org", "number", "110"));
        DynamicObject yemMilltype = submaterialinfo.getDynamicObject("yem_milltype");
        if (yemMilltype != null) {
            dynamicObject.set("group", seelctDyn("yem_em_electronicgroup", "number", yemMilltype.getString("number")));
        }
        dynamicObject.set("yem_customer", dataEntitie.getDynamicObject("yem_customer"));
        dynamicObject.set("yem_salesorderno", materialinfo.getString("yem_conbillnumber"));
        String yemSourcebilltypeE = materialinfo.getString("yem_sourcebilltype_e");
        if (yemSourcebilltypeE.equals("yem_shippingdetails")) {
            dynamicObject.set("yem_shippingdetailno", materialinfo.getString("yem_sourcebillno_d"));
        }
        DynamicObject yemResourcescode = submaterialinfo.getDynamicObject("yem_resourcescode");
        if (yemResourcescode != null) {
            dynamicObject.set("yem_model", yemResourcescode);
            dynamicObject.set("yem_machinedata", Getmachinedata(submaterialinfo.getString("yem_vehicleno"), yemResourcescode));//订单日期
            dynamicObject.set("yem_analysistdate", Getanalysistdate(submaterialinfo.getString("yem_vehicleno"), yemResourcescode));
            String sql = "select DISTINCT product_color,color_name from VIEW_PLAN_PIN_WM  where PLAN_PIN='" + yem_vehicleno + "'";
            List<Map> fromCmmp = RequestCmmp.getFromCmmp(0l, sql, yemResourcescode.getDynamicObject("yem_productsgroup").getLong("id"));
            if (fromCmmp.size() > 0) {
                Map map = fromCmmp.get(0);
                dynamicObject.set("yem_compcode", map.get("product_color"));
                dynamicObject.set("yem_compname", map.get("color_name"));
            }
        }
        dynamicObject.set("yem_framenumber", yem_vehicleno);

        dynamicObject.set("yem_enginecode", submaterialinfo.getString("yem_engineno"));
        dynamicObject.set("yem_enginemodel", submaterialinfo.getString("yem_enginemodel"));
        dynamicObject.set("yem_enginevendor", submaterialinfo.getString("yem_enginevendor"));
        dynamicObject.set("yem_dateofpurchase", getdateofpurchase(materialinfo.getString("yem_conbillnumber")));//订单日期
        dynamicObject.set("yem_heqty", yem_qty);//数量
        if (yemResourcescode != null) {

            Map<String, DynamicObjectCollection> Gettracktaskconsole = DeliverNoticeUtilsEdit.Gettracktaskconsole(yem_conbillnumber, yemResourcescode, yem_vehicleno, "yem_multiconfig");
            //多功能
//            DynamicObjectCollection multiconfig = DeliverNoticeUtilsEdit.Gettracktaskconsole(yem_conbillnumber, yemResourcescode, yem_vehicleno, "yem_multiconfig");
            if (Gettracktaskconsole.containsKey("yem_multiconfig")) {
                DynamicObjectCollection multiconfig = Gettracktaskconsole.get("yem_multiconfig");
                if (multiconfig.size() > 0) {
                    //整机档案
                    DynamicObjectCollection yem_multiconfig = dynamicObject.getDynamicObjectCollection("yem_multiconfig");
                    yem_multiconfig.clear();
                    for (int i = 0; i < multiconfig.size(); i++) {
                        DynamicObject dynamicObject1 = multiconfig.get(i);
                        DynamicObject dynamicObject2 = yem_multiconfig.addNew();
                        dynamicObject2.set("yem_configurtype", dynamicObject1.getString("yem_configurtype"));//配置类型
                        dynamicObject2.set("yem_configurname", dynamicObject1.getString("yem_configurname"));//配置名称
                        dynamicObject2.set("yem_configurtypeen", dynamicObject1.getString("yem_configurtypeen"));//配置英文名称
                        dynamicObject2.set("yem_specification", dynamicObject1.getString("yem_specification_o"));//规格型号
                        dynamicObject2.set("yem_qty", dynamicObject1.getBigDecimal("yem_unitset"));//数量
                        dynamicObject2.set("yem_arguments", dynamicObject1.getString("yem_arguments"));//参数（mm）
                        dynamicObject2.set("yem_remark", dynamicObject1.getString("yem_remarkss"));//备注
                    }
                }
            }

            //加装
//            DynamicObjectCollection retrofitting = DeliverNoticeUtilsEdit.Gettracktaskconsole(yem_conbillnumber, yemResourcescode, yem_vehicleno, "yem_retrofitting");
            if (Gettracktaskconsole.containsKey("yem_retrofitting")) {
                DynamicObjectCollection retrofitting = Gettracktaskconsole.get("yem_retrofitting");
                if (retrofitting.size() > 0) {
                    //整机档案
                    DynamicObjectCollection yem_retrofitting = dynamicObject.getDynamicObjectCollection("yem_retrofitting");
                    yem_retrofitting.clear();
                    for (int i = 0; i < retrofitting.size(); i++) {
                        DynamicObject dynamicObject1 = retrofitting.get(i);
                        DynamicObject dynamicObject2 = yem_retrofitting.addNew();
                        dynamicObject2.set("yem_albumassemblyno", dynamicObject1.getDynamicObject("yem_albumassemblyno"));//物料编码
                        dynamicObject2.set("yem_materiel", dynamicObject1.getDynamicObject("yem_materiel1"));//物料编码
                        dynamicObject2.set("yem_unit1", dynamicObject1.getDynamicObject("yem_unit1"));//
                        dynamicObject2.set("yem_enname", dynamicObject1.getString("yem_enname"));//
                        dynamicObject2.set("yem_qty1", dynamicObject1.getBigDecimal("yem_qty1"));//数量
                        dynamicObject2.set("yem_desc", dynamicObject1.getString("yem_desc"));//备注
                    }
                }
            }
        }
        return dynamicObject;
    }

    //根据合同号查询合同签订日期
    public Date getdateofpurchase(String billno) {
        QFilter qFilter = new QFilter("billno", QCP.equals, billno);//替换零件编码
        DynamicObject yem_es_salesorder = BusinessDataServiceHelper.loadSingle("yem_es_salesorder",
                "id,yem_signdate"
                , new QFilter[]{qFilter});
        if (yem_es_salesorder != null) {
            Date yem_signdate = yem_es_salesorder.getDate("yem_signdate");
            return yem_signdate;
        }
        return null;
    }

    //获取整机上线时间
    public Date Getmachinedata(String yem_framenumber, DynamicObject yemResourcescode) {
        String Queryfield = AtlasUtils.Queryfield("PLAN_PIN", "INSTRUCTION_CODE", "JOB_TIME", "INSTRUCTION_NAME");
        String sql = "select distinct " + Queryfield + "  from VIEW_PLAN_JOB_WM where INSTRUCTION_NAME='上线'  and PLAN_PIN='" + yem_framenumber + "'";//where TO_CHAR (enable_time, 'yyyy-mm-dd') >= '2023-01-01'
        List<Map> fromCmmp = RequestCmmp.getFromCmmp(0L, sql, yemResourcescode.getDynamicObject("yem_productsgroup").getLong("id"));
        if (fromCmmp.size() > 0) {
            Map map = fromCmmp.get(0);
            Date job_time = (Date) map.get("job_time");
            return job_time;
        }
        return null;
    }

    //料单分析时间
    public Date Getanalysistdate(String yem_framenumber, DynamicObject yemResourcescode) {
        String Queryfield = AtlasUtils.Queryfield("plmlastupdate");
        String sql = "select distinct " + Queryfield + "  from VIEW_ANALYZE_TIME_WM where  plan_pin='" + yem_framenumber + "'";//where TO_CHAR (enable_time, 'yyyy-mm-dd') >= '2023-01-01'
        List<Map> fromCmmp = RequestCmmp.getFromCmmp(0L, sql, yemResourcescode.getDynamicObject("yem_productsgroup").getLong("id"));
        if (fromCmmp.size() > 0) {
            Map map = fromCmmp.get(0);
            Date job_time = (Date) map.get("plmlastupdate");
            return job_time;
        }
        return null;
    }

}
