package com.yem.wm.im.packplan.form;

import com.grapecity.documents.excel.L;
import com.yem.wm.es.Util.ViewInterfaceDocking;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.ConfirmCallBackListener;
import kd.bos.form.IFormView;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.MessageBoxResult;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

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

/**
 * @author xwudd
 * @date 13:38
 * @Description
 **/
public class PackPlanEdit extends AbstractBillPlugIn implements BeforeF7SelectListener {
    @Override
    public void registerListener(EventObject e) {
        BasedataEdit productmodel = this.getView().getControl("yem_productmodel");
        if(productmodel != null){
            productmodel.addBeforeF7SelectListener(this);
        }
        BasedataEdit appResourceNo = this.getView().getControl("yem_appresourceno");
        if(appResourceNo != null){
            appResourceNo.addBeforeF7SelectListener(this);
        }
        BasedataEdit yem_appresourcenos = this.getView().getControl("yem_appresourcenos");
        if(yem_appresourcenos != null){
            yem_appresourcenos.addBeforeF7SelectListener(this);
        }
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        IDataModel model = this.getModel();
        String key = e.getProperty().getName();
        switch (key){
            case "yem_productmodel":
                //产品型号根据产品类型过滤
                DynamicObject types = (DynamicObject)model.getValue("yem_producttypes");
                if(types == null){
                    this.getView().showMessage("请先选择产品类型");
                    e.setCancel(true);
                } else{
                    String number = types.getString("number");
                    e.addCustomQFilter(new QFilter("group.longnumber", QCP.like,"%" + number + "%"));
                }
                break;
            case "yem_appresourceno":
            case "yem_appresourcenos":
                //产品型号根据产品类型过滤
                DynamicObject productModel = (DynamicObject)model.getValue("yem_productmodel");
                if(productModel == null){
                    this.getView().showMessage("请先选择产品机型");
                    e.setCancel(true);
                } else{
                    e.addCustomQFilter(new QFilter("yem_products", QCP.equals,productModel.getPkValue()));
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        DynamicObject datas = this.getModel().getDataEntity(true);
        String key = e.getProperty().getName();
        switch (key){
            case "yem_appresourcenos":
                carryweight();
                break;
            case "yem_producttypes":
                this.getModel().setValue("yem_productmodel",null);
                this.getModel().setValue("yem_appresourcenos",null);
                break;
            case "yem_productmodel":
                this.getModel().setValue("yem_appresourcenos",null);
                break;
            case "yem_weight":
            case "yem_staqty":
            case "yem_weight_e":
                calcBodyWeight();
                break;

        }
    }

    /**
     * 计算机身重量
     */
    private void calcBodyWeight()
    {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_packplan_e");
        BigDecimal totalWeight = dataEntity.getBigDecimal("yem_weight");
        BigDecimal currWeight = BigDecimal.ZERO;
        for (DynamicObject dynamicObject : collection) {
            String splitname = dynamicObject.getString("yem_splitname").trim();
            if (!"机身".equals(splitname)) {
                BigDecimal yemWeightE = dynamicObject.getBigDecimal("yem_weight_e");
                BigDecimal yemStaqty = dynamicObject.getBigDecimal("yem_staqty");
                currWeight = currWeight.add(yemWeightE.multiply(yemStaqty));
            }
        }
        for (DynamicObject dynamicObject : collection) {
            int index = collection.indexOf(dynamicObject);
            String splitname = dynamicObject.getString("yem_splitname").trim();
            if ("机身".equals(splitname)) {
                BigDecimal calcedTotalWeight = totalWeight.subtract(currWeight).setScale(2, RoundingMode.HALF_UP);
                this.getModel().beginInit();
                model.setValue("yem_weight_e", calcedTotalWeight, index);
                this.getView().updateView("yem_packplan_e");
                this.getModel().endInit();
            }
        }
    }

    public void carryweight(){
        DynamicObject appresourcenos = (DynamicObject) this.getView().getModel().getValue("yem_appresourcenos");
        if (appresourcenos!=null){
            String number = appresourcenos.getString("number");
            DynamicObject materials = BusinessDataServiceHelper.loadSingle("bd_material", "netweight",
                    new QFilter[]{new QFilter("number", QCP.equals, number)});
            if (materials!=null){
                BigDecimal netweight = materials.getBigDecimal("netweight");
                this.getModel().setValue("yem_weight",netweight);
            }
//            BigDecimal netweight = materials.getBigDecimal("netweight");
//            for(DynamicObject material : materials){
//                BigDecimal netweight = material.getBigDecimal("netweight");
//                this.getModel().setValue("yem_weight",netweight);
//            }
        }
    }


    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String operateKey = e.getOperateKey();
        switch(operateKey){
            case "getdetachableinfo" :
                getDetachableLargeInfo();
                break;
        }
    }


    public void getDetachableLargeInfo(){
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        Map<String,Object> map = new HashMap();
        DynamicObject appResourceNo = (DynamicObject)model.getValue("yem_appresourcenos");
        if(YEM.isNotEmpty(appResourceNo)){
            Boolean isTwo = (Boolean)model.getValue("yem_istwo");
            if(isTwo){
                view.showConfirm("已获取过可拆卸大件信息，是否重复获取？", MessageBoxOptions.YesNo, new ConfirmCallBackListener("getdetachableinfo", this));
            }else{
                getPackPlan();
            }
        }else{
            view.showErrorNotification("请先填写使用资源号，再获取可拆卸大件信息！");
        }
    }

    @Override
    public void confirmCallBack(MessageBoxClosedEvent e) {
        super.confirmCallBack(e);
        MessageBoxResult result = e.getResult();
        String callBackId = e.getCallBackId();
        if(result == MessageBoxResult.Yes){
            if("getdetachableinfo".equals(callBackId)){
                getPackPlan();
            }
        }
    }

    public void getPackPlan(){
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        Map<String,Object> map = new HashMap();
        DynamicObject appResourceNo = (DynamicObject)model.getValue("yem_appresourcenos");
        int packPlans = model.getEntryRowCount("yem_packplan_e");
        if(packPlans > 0){
            int[] deleteRows = new int[packPlans - 1];
            String splitName = (String)model.getValue("yem_splitname", 0);
            if(!"机身".equals(splitName)){
                model.deleteEntryData("yem_packplan_e");
            }else{
                for (int i = 1; i < packPlans; i++) {
                    deleteRows[i - 1] = i;
                }
                model.deleteEntryRows("yem_packplan_e",deleteRows);
            }
        }
        map.put("pcode",appResourceNo.getString("number"));
        DynamicObject producttypes = (DynamicObject) model.getValue("yem_producttypes");
        if(producttypes==null){
            this.getView().showErrorNotification("请填写产品分类！");
            return;
        }
        long producttypesid = producttypes.getLong("id");
        List<Map> dockings = ViewInterfaceDocking.docking(ViewInterfaceDocking.DETACHABLE_LARGE_INFO, map,producttypesid);
        if(YEM.isNotEmpty(dockings)){
            model.setValue("yem_istwo",true);
            List<String> librarys = new ArrayList<>();
            DynamicObject[] disassemblyLibrarys = BusinessDataServiceHelper.load("yem_disassemblylibrary", "number,yem_materialnum,name", null);
            for (DynamicObject disassemblyLibrary : disassemblyLibrarys){
                librarys.add(disassemblyLibrary.getString("number"));
            }
            Map<String,DynamicObject> materialMap = new HashMap();
            DynamicObject[] materials = BusinessDataServiceHelper.load("bd_material", "id,number",
                    new QFilter[]{new QFilter("status", QCP.equals, "C")});
            for(DynamicObject material : materials){
                String number = material.getString("number");
                if(YEM.isNotEmpty(number)){
                    materialMap.put(number,material);
                }
            }
            for(Map docking : dockings){
                String cCode = (String)docking.get("ccode");
                BigDecimal qty = (BigDecimal)docking.get("qty");
                if(librarys.contains(cCode)){
                    int entryRow = model.createNewEntryRow("yem_packplan_e");
                    model.setValue("yem_picno",materialMap.get(cCode),entryRow);
                    model.setValue("yem_staqty",qty,entryRow);
                    model.setValue("yem_qtyamt",qty,entryRow);
                }
            }
            Boolean flag = false;
            BigDecimal entryWeight = BigDecimal.ZERO;
            packPlans = model.getEntryRowCount("yem_packplan_e");
            for (int i = 0; i < packPlans; i++) {
                Boolean isAuto = (Boolean)model.getValue("yem_isauto",i);
                if(isAuto){
                    flag = isAuto;
                }else{
                    entryWeight = entryWeight.add((BigDecimal) model.getValue("yem_weight_e",i));
                }
            }
            //机身构建行
            BigDecimal weightTotal = (BigDecimal)model.getValue("yem_weight");
            if(!flag){
                int row = model.insertEntryRow("yem_packplan_e", 0);
                model.setValue("yem_splitname","机身",0);
                model.setValue("yem_staqty",1,0);
                model.setValue("yem_qty",1,0);
                model.setValue("yem_qtyamt",1,0);
                model.setValue("yem_weight_e",weightTotal.subtract(entryWeight),0);
                model.setValue("yem_isauto",true,0);
            }else{
                model.setValue("yem_weight_e",weightTotal.subtract(entryWeight),0);
            }

        }
        view.invokeOperation("save");
    }
}
