package com.yem.wm.im.orderproreqbill.from;

import com.yem.wm.utils.FunctionalCommon;
import com.yem.wm.utils.YEM;
import kd.bos.bill.OperationStatus;
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.entity.operate.result.OperationResult;
import kd.bos.exception.KDBizException;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.events.PreOpenFormEventArgs;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.FormOperate;
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.operation.SaveServiceHelper;

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

/**
 * @author zhouc
 * @date 2023/8/15 11:52
 * @className orderproreqbillFromEdit
 * @description 订单产品需求单表单插件
 */
public class orderproreqbillFromEdit extends AbstractFormPlugin implements BeforeF7SelectListener {
    @Override
    public void preOpenForm(PreOpenFormEventArgs e) {
        super.preOpenForm(e);
        FormShowParameter fsp = e.getFormShowParameter();
        String billtype  = fsp.getFormConfig().getEntityTypeId();
        String FormId = fsp.getFormId();
        if(FormId.equals("yem_orderproreqbill")){
            fsp.setFormId("yem_orderproreqbill_zz");
            fsp.setCaption("订单产品需求单");//_配件自制计划
        }

//        DynamicObject yem_billtype = (DynamicObject) this.getView().getModel().getValue("yem_billtype");
//        if (yem_billtype != null) {
//            String billtype = yem_billtype.getString("number");
//            if (billtype.equals("yem_orderproreqbill_CG")) {//配件采购计划
//                fsp.setFormId("yem_orderproreqbill_cg");
//            } else if (billtype.equals("yem_orderproreqbill_DB")) {//配件调拨计划
//                fsp.setFormId("yem_orderproreqbill_db");
//            }else if (billtype.equals("yem_orderproreqbill_WG")) {//整机外购计划
//                fsp.setFormId("yem_orderproreqbill_wg");
//            }else if (billtype.equals("yem_orderproreqbill_ZJ")) {//整机自制计划
//                fsp.setFormId("yem_orderproreqbill_zj");
//            }else if (billtype.equals("yem_orderproreqbill_ZZ")) {//配件自制计划
//                fsp.setFormId("yem_orderproreqbill_zz");
//            }else {
//                fsp.setFormId("yem_orderproreqbill");
//            }
//        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        IDataModel model = this.getModel();
        DynamicObject yem_billtype = (DynamicObject) model.getValue("yem_billtype");
        if (yem_billtype != null) {
            String billtype = yem_billtype.getString("number");
//            if (billtype.equals("yem_orderproreqbill_CG")) {//配件采购计划
////                fsp.setFormId("yem_orderproreqbill_cg");
//                setbilltype("yem_orderproreqbill_cg");
//            } else if (billtype.equals("yem_orderproreqbill_DB")) {//配件调拨计划
////                fsp.setFormId("yem_orderproreqbill_db");
//                setbilltype("yem_orderproreqbill_db");
//            }else if (billtype.equals("yem_orderproreqbill_WG")) {//整机外购计划
////                fsp.setFormId("yem_orderproreqbill_wg");
//                setbilltype("yem_orderproreqbill_wg");
//            }else if (billtype.equals("yem_orderproreqbill_ZJ")) {//整机自制计划
////                fsp.setFormId("yem_orderproreqbill_zj");
//                setbilltype("yem_orderproreqbill_zj");
//            }else if (billtype.equals("yem_orderproreqbill_ZZ")) {//配件自制计划
////                fsp.setFormId("yem_orderproreqbill_zz");
//                setbilltype("yem_orderproreqbill_zz");
//            }
        }
        IFormView view = this.getView();
        FormShowParameter fsp = view.getFormShowParameter();
        Map<String, Object> params = fsp.getCustomParams();
        if (params.containsKey("iscopy")) {
            boolean iscopy = (boolean) params.get("iscopy");
            if (!iscopy) {
                model.setValue("yem_currencybase", BusinessDataServiceHelper.loadSingle("bd_currency", new QFilter[]{new QFilter("number", QCP.equals, "CNY")}));
            }
        }
        setTechnicalSupport();
    }
    public void  setbilltype(String number){
        OperationStatus status = this.getView().getFormShowParameter().getStatus();
        if(OperationStatus.ADDNEW == status) {
            QFilter qFilter = new QFilter("number", QCP.equals, number);
            DynamicObject billType = BusinessDataServiceHelper.loadSingle("bos_billtype", "id", qFilter.toArray());
            this.getModel().setValue("yem_billtype", billType);
        }
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        BasedataEdit dept = this.getControl("yem_dept");
        dept.addBeforeF7SelectListener(this);
        BasedataEdit applyInventoryOrg = this.getControl("yem_applyinventoryorg");
        applyInventoryOrg.addBeforeF7SelectListener(this);
        // 申请部门
        BasedataEdit depcode = this.getControl("yem_depcode");
        depcode.addBeforeF7SelectListener(this);
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String name = e.getProperty().getName();
        switch (name){
            case "yem_dept" :
            case "yem_applyinventoryorg" :
            case "yem_depcode":
                selectDept(e);
                break;
        }
    }

    /**
     * @description 过滤当前组织下的部门
     * @author xwudd
     * @param[1] e
     * return
     * @time 2023/10/19 10:53
     */

    public void selectDept(BeforeF7SelectEvent e){
        IDataModel model = this.getModel();
        DynamicObject org = (DynamicObject)model.getValue("org");
        if(YEM.isNotEmpty(org)){
            long id = org.getLong("id");
            Set orgUserDeps = FunctionalCommon.getOrgUserDeps(id);
            e.addCustomQFilter(new QFilter("id", QCP.in, orgUserDeps));
        }
    }

    /**
     * 批量新增行
     */
    @Override
    public void afterDoOperation(AfterDoOperationEventArgs args)
    {
        super.afterDoOperation(args);
        String operateKey = args.getOperateKey();
        OperationResult operationResult = args.getOperationResult();
        if ("batchcreate".equals(operateKey) && operationResult.isSuccess()) {
            this.getModel().batchCreateNewEntryRow("yem_es_materialinfo",10);
        }
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        EntryGrid entryGrid = this.getControl("yem_es_materialinfo");
        int[] selectRows = entryGrid.getSelectRows();
        if ("orderclose".equals(operateKey)) {
            if (selectRows.length > 0) {
                DynamicObject dynamicObject = collection.get(selectRows[0]);
                Map<String, Object> map = new HashMap<>();
                map.put("yem_materiel", dynamicObject.getLong("yem_materiel.id"));
                map.put("yem_qty", dynamicObject.getBigDecimal("yem_qty"));

                FormShowParameter parameter = new FormShowParameter();
                parameter.setCustomParams(map);
                parameter.setStatus(OperationStatus.ADDNEW);
                parameter.getOpenStyle().setShowType(ShowType.Modal);
                parameter.setFormId("yem_orderrequire_close");
                parameter.setCloseCallBack(new CloseCallBack(this, "yem_orderrequire_close"));
                view.showForm(parameter);
            } else {
                view.showErrorNotification("未选择数据");
            }
        }

        if ("unorderclose".equals(operateKey)) {
            if (selectRows.length > 0) {
                DynamicObject dynamicObject = collection.get(selectRows[0]);
                BigDecimal closeQuantity = dynamicObject.getBigDecimal("yem_closecount");
                writeBackCloseQuantity(false, selectRows[0], closeQuantity);

                dynamicObject.set("yem_closecount", BigDecimal.ZERO);
                dynamicObject.set("yem_closepeople", null);
                dynamicObject.set("yem_closingtime", null);
                dynamicObject.set("yem_closereson", "");

                this.getView().updateView("yem_es_materialinfo");
                view.showSuccessNotification("反关闭成功");
            } else {
                view.showErrorNotification("未选择数据");
            }
        }

        if("audit".equals(operateKey)){
            if (YEM.isNotEmpty(operationResult)) {
                view.invokeOperation("refresh");
            }
        }
        if("unaudit".equals(operateKey)){
            if (YEM.isNotEmpty(operationResult)) {
                view.invokeOperation("refresh");
            }
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args)
    {
        super.beforeDoOperation(args);
        FormOperate formOperate = (FormOperate) args.getSource();
        String operateKey = formOperate.getOperateKey();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        if ("save".equals(operateKey) || "submit".equals(operateKey)) {
            generateOrderTitle(model);


            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            for (DynamicObject dynamicObject : collection) {
                int index = collection.indexOf(dynamicObject);
                BigDecimal qty = dynamicObject.getBigDecimal("yem_qty");
                BigDecimal closecount = dynamicObject.getBigDecimal("yem_closecount");
                if (YEM.isNotEmpty(closecount)) {
                    if (qty.compareTo(closecount) < 0) {
                        throw new KDBizException("商品明细第" + (index + 1) + "行，关闭数量不允许超出数量");
                    }
                }
            }
        }
    }

    private void generateOrderTitle(IDataModel model) {
        StringBuilder sb = new StringBuilder();

        DynamicObject operator = (DynamicObject) model.getValue("yem_operator");
        if (YEM.isNotEmpty(operator)) {
            sb.append(operator.getString("name")).append(" ");
        }
        DynamicObject clientcountry = (DynamicObject) model.getValue("yem_clientcountry");
        if (YEM.isNotEmpty(clientcountry)) {
            sb.append(clientcountry.get("name")).append(" ");
        }
        String billno = (String) model.getValue("yem_hth");
        if (YEM.isNotEmpty(billno)) {
            sb.append(billno).append(" ");
        }
        DynamicObject billtype = (DynamicObject) model.getValue("yem_billtype");
        if (YEM.isNotEmpty(billtype)) {
            sb.append(billtype.get("name")).append(" ");
        }
        model.setValue("yem_ordertitle", sb.toString());
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e)
    {
        super.propertyChanged(e);
        String name = e.getProperty().getName();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        int rowIndex = e.getChangeSet()[0].getRowIndex();
        if ("yem_qty".equals(name) || "yem_closecount".equals(name)) {
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            DynamicObject dynamicObject = collection.get(rowIndex);
            BigDecimal qty = dynamicObject.getBigDecimal("yem_qty");
            BigDecimal closecount = dynamicObject.getBigDecimal("yem_closecount");
            int index = collection.indexOf(dynamicObject);
            if (YEM.isNotEmpty(closecount)) {
                if (qty.compareTo(closecount) < 0) {
                    this.getView().showErrorNotification("关闭数量不允许超出数量");
                    throw new KDBizException("商品明细第" + (index + 1) + "行，关闭数量不允许超出数量");
                }
            }
        }

        if ("yem_ifsupportg".equals(name)) {
            setTechnicalSupport();
        }
    }

    /**
     * 如果分录中存在一行是否技术支持  为是，保存时，表头置为是；
     */
    private void setTechnicalSupport()
    {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        Set<String> set = new HashSet<>();
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        for (DynamicObject dynamicObject : collection) {
            set.add(dynamicObject.getString("yem_ifsupportg"));
            if ("A".equals(dynamicObject.getString("yem_ifsupportg"))) {
                break;
            }
        }

        if (set.contains("A")) {
            model.setValue("yem_ifsupport", "A");
        } else {
            model.setValue("yem_ifsupport", "B");
        }

    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e)
    {
        super.closedCallBack(e);
        String actionId = e.getActionId();
        Object returnData = e.getReturnData();
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        if ("yem_orderrequire_close".equals(actionId)) {
            Map<String, Object> map = (Map<String, Object>) returnData;
            EntryGrid entryGrid = this.getControl("yem_es_materialinfo");
            int[] selectRows = entryGrid.getSelectRows();
            if (selectRows.length < 1 || map == null) {
                return;
            }
            int currRow = selectRows[0];
            if (map.containsKey("yem_closequantity")) {
                model.setValue("yem_closecount", map.get("yem_closequantity"), currRow);
            }
            if (map.containsKey("yem_closereson")) {
                model.setValue("yem_closereson", map.get("yem_closereson"), currRow);
            }
            if (map.containsKey("yem_closepeople")) {
                model.setValue("yem_closepeople", map.get("yem_closepeople"), currRow);
            }
            if (map.containsKey("yem_closingtime")) {
                model.setValue("yem_closingtime", map.get("yem_closingtime"), currRow);
            }

            BigDecimal closeQuantity = BigDecimal.ZERO;

            if (map.containsKey("yem_closequantity")) {
                closeQuantity = (BigDecimal) map.get("yem_closequantity");
            }

            DynamicObject dataEntity = model.getDataEntity(true);
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            for (DynamicObject dynamicObject : collection) {
                int index = collection.indexOf(dynamicObject);
                BigDecimal qty = dynamicObject.getBigDecimal("yem_qty");
                BigDecimal closecount = dynamicObject.getBigDecimal("yem_closecount");
                if (YEM.isNotEmpty(closecount)) {
                    if (qty.compareTo(closecount) < 0) {
                        throw new KDBizException("商品明细第" + (index + 1) + "行，关闭数量不允许超出数量");
                    }
                }
            }

            writeBackCloseQuantity(true, currRow, closeQuantity);
            view.invokeOperation("save");
        }
    }

    /**
     * 需要将关闭数量更新到对应跟单任务控制台-备料信息-关闭数量字段
     * @param isSum
     * @param currRow
     * @param closeQuantity
     */
    private void writeBackCloseQuantity(boolean isSum, int currRow, BigDecimal closeQuantity)
    {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        DynamicObject dynamicObject = collection.get(currRow);
        long sourcebillid = dynamicObject.getLong("yem_sourcebillid_d");
        long sourceentryid = dynamicObject.getLong("yem_sourceentryid");
        DynamicObject single = BusinessDataServiceHelper.loadSingle(sourcebillid, "yem_tracktaskconsole");
        if (single == null) {
            return;
        }

        DynamicObjectCollection salesorder = single.getDynamicObjectCollection("yem_es_salesorder_r");
        for (DynamicObject object : salesorder) {
            Object pkValue = object.getPkValue();
            if (pkValue.equals(sourceentryid)) {
                if (isSum) {
                    object.set("yem_closecount", object.getBigDecimal("yem_closecount").add(closeQuantity));
                } else {
                    object.set("yem_closecount", object.getBigDecimal("yem_closecount").subtract(closeQuantity));
                }

                // 备料数量
                BigDecimal stockqty = object.getBigDecimal("yem_stockqty");
                // 关联订单需求表数量
                BigDecimal qtyfield6 = object.getBigDecimal("yem_qtyfield6");
                // 关闭数量
                BigDecimal closecount = object.getBigDecimal("yem_closecount");
                object.set("yem_lastcanorderqty", stockqty.subtract(qtyfield6).add(closecount));
            }
        }

        SaveServiceHelper.update(single);
    }
}
