package com.yem.em.bd.devicefiles.task;

import com.yem.wm.utils.RequestCmmp;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.exception.KDException;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

public class SynDiscrepancyFromCMMPTask extends AbstractTask {
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        DynamicObject[] devicefiles = BusinessDataServiceHelper.load("yem_em_devicefiles", "id",
                new QFilter[]{new QFilter("yem_isdiscrepancy", QCP.equals, false),
                new QFilter("number",QCP.equals,"567006LFKPW299193")});
        for (DynamicObject devicefile : devicefiles) {
            //整机档案（已对比领料差异为否）
            devicefile = BusinessDataServiceHelper.loadSingle(devicefile.get("id"), "yem_em_devicefiles");
            //获取数据链接
            long bd_productsgroupid = devicefile.getLong("yem_model.yem_productsgroup.id");
            DynamicObjectCollection yemDiscrepancy = devicefile.getDynamicObjectCollection("yem_discrepancy");

            List<Map> fromCmmpWithConnId = RequestCmmp.getFromCmmp(null,
                        "SELECT mater_code,mater_name,sum(order_num) count from VIEW_MATERDETAIL_WM where plan_pin = '" + devicefile.getString("yem_framenumber") + "' GROUP BY mater_code,mater_name",bd_productsgroupid);
            Map<String, Integer> partMap = new HashMap<String, Integer>();
            //遍历查询总成图册明细中物料及数量
            String modelnum = devicefile.getString("yem_model.number");
            //yem_em_cmmptable-CMMP部件明细表
            DynamicObject cmmptable = BusinessDataServiceHelper.loadSingle("yem_em_cmmptable", "id",
                    new QFilter[]{new QFilter("number", QCP.equals, modelnum).and(new QFilter("status",QCP.equals,"C"))});
            if(cmmptable==null){
                continue;
            }
            cmmptable = BusinessDataServiceHelper.loadSingle(cmmptable.getLong("id"), "yem_em_cmmptable");
            //总成部件
            //一级总成

            for (DynamicObject cmmptableEntry : cmmptable.getDynamicObjectCollection("yem_entryentity")) {
                //一级总成数量
                int yemQty = cmmptableEntry.getInt("yem_qty");
                //一级总成物料编码
                String yemCcode = cmmptableEntry.getString("yem_ccode");
                DynamicObject assatlasdetObj = BusinessDataServiceHelper.loadSingle("yem_em_assatlasdet", "id",
                        new QFilter[]{new QFilter("number", QCP.equals, yemCcode),new QFilter("status",QCP.equals,"C")});
                assatlasdetObj = BusinessDataServiceHelper.loadSingle(assatlasdetObj.getLong("id"),"yem_em_assatlasdet");
                DynamicObjectCollection zctcmxEntrys = assatlasdetObj.getDynamicObjectCollection("yem_entryentity");
                for (DynamicObject zctcmxEntry : zctcmxEntrys) {
                    partMap = getMaterialAndqty(partMap, zctcmxEntry, yemQty);
                }
            }
            yemDiscrepancy.clear();
            //构建整机档案领料差异分录
            for (int j = 0; j < fromCmmpWithConnId.size(); j++) {
                Map map1 = fromCmmpWithConnId.get(j);
                String mater_code = (String) map1.get("mater_code");
                String mater_name = (String) map1.get("mater_name");
                BigDecimal count = (BigDecimal) map1.get("count");
                if (partMap.containsKey(mater_code)) {//图册中有CMMP中数据
                    //CMMP领料-图册
                    int i = count.intValue() - partMap.get(mater_code);
                    if (i == 0) {
                        fromCmmpWithConnId.remove(j);
                        j--;
                        continue;
                    } else {
                        DynamicObject dynamicObject = yemDiscrepancy.addNew();
                        dynamicObject.set("yem_subqty", i);
                        dynamicObject.set("yem_partmateriel", BusinessDataServiceHelper.loadSingle("bd_material", new QFilter[]{new QFilter("number", QCP.equals, mater_code)}));
                        dynamicObject.set("yem_partqty", partMap.get(mater_code));
                        dynamicObject.set("yem_mater_code", mater_code);
                        dynamicObject.set("yem_mater_name", mater_name);
                        dynamicObject.set("yem_cmmpqty", count);
                        fromCmmpWithConnId.remove(j);
                        j--;
                    }
                    partMap.remove(mater_code);
                } else {//图册中没有CMMP物料
                    DynamicObject dynamicObject = yemDiscrepancy.addNew();
                    dynamicObject.set("yem_subqty", count);
                    dynamicObject.set("yem_mater_code", mater_code);
                    dynamicObject.set("yem_mater_name", mater_name);
                    dynamicObject.set("yem_cmmpqty", count);
                    fromCmmpWithConnId.remove(j);
                    j--;
                }
            }
            //CMMP中没有图册中物料
            Set<Map.Entry<String, Integer>> entries = partMap.entrySet();
            for (Map.Entry<String, Integer> entry : entries) {
                DynamicObject dynamicObject = yemDiscrepancy.addNew();
                dynamicObject.set("yem_partmateriel", BusinessDataServiceHelper.loadSingle("bd_material", new QFilter[]{new QFilter("number", QCP.equals, entry.getKey())}));
                dynamicObject.set("yem_partqty", entry.getValue());
                dynamicObject.set("yem_subqty", 0 - entry.getValue());
            }
            devicefile.set("yem_isdiscrepancy", true);
            SaveServiceHelper.save(new DynamicObject[]{devicefile});
        }
    }

    /**
     * @param partMap            key 物料编码 Value数量
     * @param zctcmxEntry 分录对象
     * @param yemAssqty          上层数量
     * @return
     */
    private Map<String, Integer> getMaterialAndqty(Map<String, Integer> partMap, DynamicObject zctcmxEntry, int yemAssqty) {
        if(zctcmxEntry.getBoolean("yem_iscomp")){
            String bjbm = zctcmxEntry.getString("yem_partasspartlib.number");
            yemAssqty = yemAssqty*zctcmxEntry.getInt("yem_partqty");
            DynamicObject bjObj = BusinessDataServiceHelper.loadSingle("yem_em_assatlasdet", "id",
                    new QFilter[]{new QFilter("number", QCP.equals, bjbm), new QFilter("status", QCP.equals, "C")});
            bjObj = BusinessDataServiceHelper.loadSingle(bjObj.getLong("id"),"yem_em_assatlasdet");
            DynamicObjectCollection bjColls = bjObj.getDynamicObjectCollection("yem_entryentity");
            for (DynamicObject bjCollObj : bjColls) {
                partMap = getMaterialAndqty(partMap, bjCollObj, yemAssqty);
            }
        }else{//通过总成部件查询零件（yem_em_assatlasdet）其中yem_entryentity分录里是否部件为否的（yem_iscomp）的数量及物料编码
            if (partMap.containsKey(zctcmxEntry.getString("yem_partasspartlib.number"))) {
                Integer qty = partMap.get(zctcmxEntry.getString("yem_partasspartlib.number"));
                partMap.put(zctcmxEntry.getString("yem_partasspartlib.number"), (qty + zctcmxEntry.getInt("yem_partqty")) * yemAssqty);
            } else {
                partMap.put(zctcmxEntry.getString("yem_partasspartlib.number"), zctcmxEntry.getInt("yem_partqty") * yemAssqty);
            }
        }

        return partMap;
    }
}
