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

import com.alibaba.fastjson.JSONObject;
import com.yem.wm.es.Util.MaterialVehicleNoCMMP;
import com.yem.wm.es.Util.ViewInterfaceDocking;
import com.yem.wm.utils.DynamicObjectUtil;
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.entity.datamodel.events.BizDataEventArgs;
import kd.bos.form.FormShowParameter;
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 kd.bos.servicehelper.QueryServiceHelper;

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

/**
 * @author xwudd
 * @date 15:22
 * @Description
 **/
public class PlanPinEdit 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();
        FormShowParameter fsp = view.getFormShowParameter();
        JSONObject product = fsp.getCustomParam(MaterialVehicleNoCMMP.productCode);
        String productCode = product.getString("number");
        Map<String, Object> map = new HashMap<>();
        map.put(MaterialVehicleNoCMMP.productCode, productCode);
        Long cpfl = fsp.getCustomParam("yem_bd_products");
        List<Map> dockings = ViewInterfaceDocking.docking(ViewInterfaceDocking.PLAN_PIN, map, cpfl);
        //获取所有整机一使用整机编码
        Map<String, String> getzjbm = getzjbm();
        for (Map docking : dockings) {
            if (!getzjbm.containsKey(docking.get(MaterialVehicleNoCMMP.planPin))) {
                int productInfoRows = model.createNewEntryRow("yem_productinfos");
                model.setValue("yem_resourcescode", product.getLong("id"), productInfoRows);//资源号编码
                model.setValue("yem_productname", docking.get(MaterialVehicleNoCMMP.productName), productInfoRows);//产品名称
                model.setValue("yem_planpinfield", docking.get(MaterialVehicleNoCMMP.planPin), productInfoRows);//整机编号
                model.setValue("yem_productcolor", docking.get(MaterialVehicleNoCMMP.productColor), productInfoRows);//产品颜色编码
                model.setValue("yem_productmodel", docking.get(MaterialVehicleNoCMMP.productModel), productInfoRows);//机型
                model.setValue("yem_planname", docking.get(MaterialVehicleNoCMMP.planName), productInfoRows);//计划类型
                model.setValue("yem_publishdate", docking.get(MaterialVehicleNoCMMP.publishDate), productInfoRows);//发布日期
                model.setValue("yem_stocknum", docking.get(MaterialVehicleNoCMMP.stockNum), productInfoRows);//库存数量
                model.setValue("yem_canusenum", docking.get(MaterialVehicleNoCMMP.canuseNum), productInfoRows);//可用数量
            }
        }
    }

    @Override
    public void click(EventObject e) {
        super.click(e);
        Control control = (Control) e.getSource();
        String key = control.getKey();
        switch (key) {
            case "btnok":
                trackTaskBackFill();
                break;
        }
    }

    public void trackTaskBackFill() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        IFormView parentView = view.getParentView();
        IDataModel parentModel = parentView.getModel();
        int currentRowIndex = parentModel.getEntryCurrentRowIndex("yem_es_salesorder_r");
        int rowIndexCount = parentModel.getEntryRowCount("yem_es_salesorder_z");
        BigDecimal stockQty = (BigDecimal) parentModel.getValue("yem_stockqty", currentRowIndex);

        EntryGrid productInfos = view.getControl("yem_productinfos");
        int[] selectRows = productInfos.getSelectRows();
        int length = selectRows.length;
        FormShowParameter fsp = view.getFormShowParameter();
        String type = fsp.getCustomParam("type");
        if ("A".equals(type)) {
            if (stockQty.compareTo(new BigDecimal(rowIndexCount + length)) < 0) {
                view.showErrorNotification(String.format("整机生产信息已有%s条数据，现选%s条数据，合计%s条数据，大于备料数量%s，请重新选择！", rowIndexCount, length, rowIndexCount + length, stockQty.setScale(2)));
            } else {
                for (int selectRow : selectRows) {
                    int entryRow = parentModel.createNewEntryRow("yem_es_salesorder_z");
                    parentModel.setValue("yem_resourcescode", model.getValue("yem_resourcescode", selectRow), entryRow, currentRowIndex);
                    parentModel.setValue("yem_vehicleno", model.getValue("yem_planpinfield", selectRow), entryRow, currentRowIndex);
                    parentModel.setValue("yem_milltype", parentModel.getValue("yem_productmodelb", currentRowIndex), entryRow, currentRowIndex);
                    parentModel.setValue("yem_prepareway", parentModel.getValue("yem_stockway", currentRowIndex), entryRow, currentRowIndex);
                }
                parentView.invokeOperation("save");
                view.sendFormAction(parentView);
                view.close();
            }
        }
        if ("B".equals(type)) {
            EntryGrid saleProductInfos = parentView.getControl("yem_es_salesorder_z");
            int[] saleProductInfosSelectRows = saleProductInfos.getSelectRows();
            if (productInfos.getSelectRows().length >= 0) {
                for (int selectRow : selectRows) {
                    parentModel.setValue("yem_vehicleno", model.getValue("yem_planpinfield", selectRow), saleProductInfosSelectRows[0], currentRowIndex);
                }
                parentView.invokeOperation("save");
                view.sendFormAction(parentView);
                view.close();
            } else {
                view.showErrorNotification("改制资源，只允许单行改制！");
            }
        }

    }


    public Map<String, String> getzjbm() {
        Map<String, String> map = new HashMap<>();
        QFilter qFilter = new QFilter("yem_billtype.number", QCP.equals, "yem_tracktaskconsole_zj");//
        qFilter.and(new QFilter("yem_es_salesorder_r.yem_es_salesorder_z.yem_vehicleno", QCP.not_equals, null));
        DynamicObjectCollection data = QueryServiceHelper.query("yem_tracktaskconsole",
                "yem_es_salesorder_r.yem_es_salesorder_z.yem_vehicleno", new QFilter[]{qFilter}, null);
        for (int i = 0; i < data.size(); i++) {
            DynamicObject dynamicObject = data.get(i);
            String yem_vehicleno = dynamicObject.getString("yem_es_salesorder_r.yem_es_salesorder_z.yem_vehicleno");
            if (yem_vehicleno.length() > 0) {
                map.put(yem_vehicleno, yem_vehicleno);
            }
        }
        return map;
    }


//    public void renewSaleOrderInfo(){
//        IFormView view = this.getView();
//        IDataModel model = this.getModel();
//        EntryGrid productInfos = view.getControl("yem_productinfos");
//        int[] selectRows = productInfos.getSelectRows();
//        IFormView parentView = view.getParentView();
//        IDataModel parentModel = parentView.getModel();
//        int stockEntryRow = parentModel.getEntryCurrentRowIndex("yem_es_salesorder_r");
//        long entryId = (long)parentModel.getValue("yem_entrtyid", stockEntryRow);
//        DynamicObjectCollection materialInfos = parentModel.getEntryEntity("yem_es_materialinfo");
//        for(DynamicObject materialInfo : materialInfos){
//            long id = materialInfo.getLong("id");
//            if(id == entryId){
//                String sourceBillType = materialInfo.getString("yem_sourcebilltype_e");
//                long sourceBillId = materialInfo.getLong("yem_sourcebillid_d");
//                DynamicObject saleOrder = BusinessDataServiceHelper.loadSingle(sourceBillId, sourceBillType);
//                if(YEM.isNotEmpty(saleOrder)){
//                    DynamicObjectCollection saleMaterialInfos = saleOrder.getDynamicObjectCollection("yem_es_materialinfo");
//                    for(DynamicObject saleMaterialInfo : saleMaterialInfos){
//                        long sourceEntryId = materialInfo.getLong("yem_sourceentryid");
//                        long saleMaterialInfoId = saleMaterialInfo.getLong("id");
//                        if(saleMaterialInfoId == sourceEntryId){
//                            DynamicObjectCollection saleProductInfos = saleMaterialInfo.getDynamicObjectCollection("yem_es_salesorder_z");
//
//                        }
//                    }
//                }
//            }
//        }
//    }
}
