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


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.wm.utils.DynamicObjectUtil;
import com.yem.wm.utils.RequestEAS;
import com.yem.wm.utils.YEM;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.IFormView;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

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

/**
 * @author xwudd
 * @Description
 * @date 15:18
 **/
public class DeliverNoticeInventorEdit extends AbstractFormPlugin {


    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addClickListeners("btnok");
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        IFormView parentView = view.getParentView();
        IDataModel parentModel = parentView.getModel();
        EntryGrid materialInfo = parentView.getControl("yem_es_materialinfo");
        int[] selectRows = materialInfo.getSelectRows();
        DynamicObject org = (DynamicObject) parentModel.getValue("yem_org");
        DynamicObject materiel = (DynamicObject) parentModel.getValue("yem_materiel",selectRows[0]);
        DynamicObject warehouse = (DynamicObject) parentModel.getValue("yem_warehouse",selectRows[0]);
        if(YEM.isEmpty(org)){
            view.showErrorNotification("请填写库存组织！");
            return;
        }
        if(YEM.isEmpty(materiel) || YEM.isEmpty(warehouse)){
            view.showErrorNotification("请填写选中行的物料和仓库！");
            return;
        }
        JSONObject json = new JSONObject();
        json.put("start",0);
        json.put("len",1000);
        JSONArray storageOrgs = new JSONArray();
        String orgNumber = org.getString("number");
        storageOrgs.add(orgNumber);
        json.put("storageOrgs",storageOrgs);
        JSONArray warehouses = new JSONArray();
        String warehouseNumber = warehouse.getString("number");
        warehouses.add(warehouseNumber);
        String materialNumber = materiel.getString("number");
        json.put("warehouses",warehouses);
        json.put("materialNumFrom",materialNumber );//物料起--必填
        json.put("materialNumTo", materialNumber);//物料止--必填
        JSONArray easDatas = eas(json);
        if(YEM.isNotEmpty(easDatas) && easDatas.size() > 0){
            Map<Map<String, String>, BigDecimal> inventoryQtys = getInventoryQty(easDatas, org, (Long) parentModel.getValue("id"));
            Set<Map<String, String>> libraMapKeys = inventoryQtys.keySet();
            for (int i = 0; i < easDatas.size(); i++) {

                JSONObject easData = (JSONObject) easDatas.get(i);
                String materialNum = easData.getString("MaterialNumber");
                String warehouseNum = easData.getString("FWarehouseIDpk_hide");
                String locationNum = easData.getString("FLocationIDpk_hide");
                String lotNum = easData.getString("FLot");

                Map<String,String> mapKey = new HashMap<>();
                if(YEM.isNotEmpty(materialNum)){
                    mapKey.put("materiel",materialNum);
                }
                if(YEM.isNotEmpty(warehouseNum)){
                    mapKey.put("warehouse",warehouseNum);
                }
                if(YEM.isNotEmpty(locationNum)){
                    mapKey.put("location",locationNum);
                }
                if(YEM.isNotEmpty(lotNum)){
                    mapKey.put("lotNumber",lotNum);
                }
                BigDecimal inventoryQty = inventoryQtys.containsKey(mapKey)?inventoryQtys.get(mapKey):BigDecimal.ZERO;
                BigDecimal realQty = easData.getBigDecimal("FRealQty");
                BigDecimal heavenRealQty = realQty.subtract(inventoryQty);
                if(heavenRealQty.compareTo(BigDecimal.ZERO) > 0){
                    int entryRow = model.createNewEntryRow("yem_inventorytable");
                    model.setValue("yem_org",easData.get("FStorageOrgUnitIDpk_hide"),entryRow);//库存组织
                    model.setValue("yem_material",easData.get("MaterialNumber"),entryRow);//物料编码
                    model.setValue("yem_materialname",easData.get("MaterialName"),entryRow);//物料名称
                    model.setValue("yem_modelnum",easData.get("MaterialModel"),entryRow);//规格型号
                    model.setValue("yem_warehouse",easData.get("FWarehouseIDpk_hide"),entryRow);//仓库
                    model.setValue("yem_location",easData.get("FLocationIDpk_hide"),entryRow);//库位
                    model.setValue("yem_lot",easData.get("FLot"),entryRow);//批次
                    model.setValue("yem_inventoryunit",easData.get("INVENTORYUNITNAME"),entryRow);//库存计量单位
                    model.setValue("yem_useqty",easData.get("FRealQty"),entryRow);//可用数量
                    model.setValue("yem_heavenoccupyqty",inventoryQty,entryRow);//苍穹占用数量
                    model.setValue("yem_heavenuseqty",heavenRealQty,entryRow);//苍穹可用库存数量
                    model.setValue("yem_inventoryqty",easData.get("CURMATSTOREQTY"),entryRow);//库存数量
                    model.setValue("yem_unit",easData.get("FUnitIDpk_hide"),entryRow);//计量单位
                    model.setValue("yem_helpcode",easData.get("materialHelpCode"),entryRow);//助记码
                    model.setValue("yem_unitbase",easData.get("FBaseUnitIDpk_hide"),entryRow);//基本计量单位
                    model.setValue("yem_qty",easData.get("FCurStoreQty"),entryRow);//数量
                    model.setValue("yem_qtybase",easData.get("FBaseQty"),entryRow);//基本数量
                    model.setValue("yem_useqtybase",easData.get("FRealBaseQty"),entryRow);//可用基本数量
                    model.setValue("yem_translateunit",easData.get("FAssistUnitIDpk_hide"),entryRow);//辅助计量单位
                    model.setValue("yem_translateqty",easData.get("FCurStoreAssistQty"),entryRow);//辅助数量
                    model.setValue("yem_usetranslateqty",easData.get("FRealAssistQty"),entryRow);//可用辅助数量
                    model.setValue("yem_auxprop",easData.get("FAssistPropertyIDpk_hide"),entryRow);//辅助属性
                    model.setValue("yem_inventorytype",easData.get("FStoreTypeIDpk_hide"),entryRow);//库存类型
                    model.setValue("yem_inventorystatus",easData.get("FStoreStatusIDpk_hide"),entryRow);//库存状态
                }
            }
        }
    }

    public JSONArray eas(JSONObject json){
        String s = RequestEAS.InventoryListServiceFacadeGetData(json.toString());
        JSONObject result = JSONObject.parseObject(s);
        JSONArray list = result.getJSONArray("list");
        if(list.size() == 1000){
            json.put("start",(json.getIntValue("start") + 1) * json.getIntValue("len"));
            s = RequestEAS.InventoryListServiceFacadeGetData(json.toString());
            result = JSONObject.parseObject(s);
            list.addAll(result.getJSONArray("list"));
        }
        return list;
    }

    public Map<Map<String,String>, BigDecimal> getInventoryQty(JSONArray easDatas,DynamicObject org,Long id){
        List<String> materialNumbers = new ArrayList<>();
        List<String> warehouseNumbers = new ArrayList();
        List<String> locationNumbers = new ArrayList();
        List<String> lotNumbers = new ArrayList();
        Map<Map<String,String>, BigDecimal> map = new HashMap();
        for (int i = 0; i < easDatas.size(); i++) {
            JSONObject easData = (JSONObject)easDatas.get(i);
            String materialNum = easData.getString("MaterialNumber");
            String warehouseNum = easData.getString("FWarehouseIDpk_hide");
            String locationNum = easData.getString("FLocationIDpk_hide");
            String lotNum = easData.getString("FLot");
            if(YEM.isNotEmpty(materialNum)){
                materialNumbers.add(materialNum);
            }
            if(YEM.isNotEmpty(warehouseNum)){
                warehouseNumbers.add(warehouseNum);
            }
            if(YEM.isNotEmpty(locationNum)){
                locationNumbers.add(locationNum);
            }
            if(YEM.isNotEmpty(lotNum)){
                lotNumbers.add(lotNum);
            }
            QFilter qFilter = new QFilter("yem_org", QCP.equals, org.getPkValue());
            qFilter.and(new QFilter("id", QCP.not_equals, id));
            if(materialNumbers.size() > 0){
                qFilter.and(new QFilter("yem_es_materialinfo.yem_materiel.number", QCP.in, materialNum));
            }
            if(warehouseNumbers.size() > 0){
                qFilter.and(new QFilter("yem_es_materialinfo.yem_warehouse.name", QCP.in, warehouseNum));
            }
            if(locationNumbers.size() > 0){
                qFilter.and(new QFilter("yem_es_materialinfo.yem_location.name", QCP.in, locationNum));
            }
            if(lotNumbers.size() > 0){
                qFilter.and(new QFilter("yem_es_materialinfo.yem_lotnumber", QCP.in, lotNumbers));
            }
            qFilter.and(new QFilter("billstatus", QCP.in, new String[]{"B","A"}));
            String selectfields = DynamicObjectUtil.getSelectfields("yem_es_delivernotice", false);
            selectfields = DynamicObjectUtil.getEntrySelectfields(selectfields,"yem_es_delivernotice","yem_es_materialinfo",false);
            DynamicObject[] deliverNotices = BusinessDataServiceHelper.load("yem_es_delivernotice", selectfields, qFilter.toArray());

            for (DynamicObject deliverNotice : deliverNotices){
                DynamicObjectCollection queryMaterialInfos = deliverNotice.getDynamicObjectCollection("yem_es_materialinfo");
                for(DynamicObject queryMaterialInfo : queryMaterialInfos){
                    Map<String, String> keyMap = new HashMap<>();
                    DynamicObject material = queryMaterialInfo.getDynamicObject("yem_materiel");
                    if(YEM.isNotEmpty(material)){
                        keyMap.put("materiel",material.getString("number"));
                    }
                    DynamicObject warehouse = queryMaterialInfo.getDynamicObject("yem_warehouse");
                    if(YEM.isNotEmpty(warehouse)){
                        keyMap.put("warehouse",warehouse.getString("name"));
                    }
                    DynamicObject location = queryMaterialInfo.getDynamicObject("yem_location");
                    if(YEM.isNotEmpty(location)){
                        keyMap.put("location",location.getString("name"));
                    }
                    String lotNumber = queryMaterialInfo.getString("yem_lotnumber");
                    if(YEM.isNotEmpty(lotNumber)){
                        keyMap.put("lotNumber",lotNumber);
                    }
                    BigDecimal qty = queryMaterialInfo.getBigDecimal("yem_qty");
                    if(map.containsKey(keyMap)){
                        map.put(keyMap,qty.add(map.get(keyMap)));
                    }else{
                        map.put(keyMap,qty);
                    }
                }
            }
        }
        return map;
    }


    @Override
    public void click(EventObject e) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        IFormView parentView = view.getParentView();
        IDataModel parentModel = parentView.getModel();
        Control control = (Control)e.getSource();
        String key = control.getKey();
        if("btnok".equals(key)){
            EntryGrid materialInfo = parentView.getControl("yem_es_materialinfo");
            int[] materialInfoSelectRows = materialInfo.getSelectRows();
            EntryGrid inventoryTable = view.getControl("yem_inventorytable");
            int[] inventoryTableSelectRows = inventoryTable.getSelectRows();
            if(inventoryTableSelectRows.length != 1){
                view.showErrorNotification("请选择一行库存物料！");
                return;
            }
            BigDecimal qty = (BigDecimal)parentModel.getValue("yem_qty", materialInfoSelectRows[0]);
            BigDecimal heavenUseQty = (BigDecimal)model.getValue("yem_heavenuseqty", inventoryTableSelectRows[0]);
            if(heavenUseQty.compareTo(qty) < 0){
                parentModel.setValue("yem_qty",heavenUseQty,materialInfoSelectRows[0]);
            }
            String location = (String)model.getValue("yem_location", inventoryTableSelectRows[0]);
            DynamicObject whLocation = BusinessDataServiceHelper.loadSingle("yem_warearea", "id",
                    new QFilter[]{new QFilter("name", QCP.equals, location),//名称
                            new QFilter("yem_belong",QCP.equals,"A"),//所属为EAS
                            new QFilter("group.name",QCP.equals,this.getModel().getValue("yem_warehouse",materialInfoSelectRows[0]))});//仓库
            if(YEM.isNotEmpty(whLocation)){
                parentModel.setValue("yem_location",whLocation,materialInfoSelectRows[0]);
            }
            parentModel.setValue("yem_lotnumber",model.getValue("yem_lot",inventoryTableSelectRows[0]),materialInfoSelectRows[0]);
            parentView.invokeOperation("save");
            view.sendFormAction(parentView);
            view.close();
        }
    }
}
