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

import com.yem.wm.es.contractamtlist.util.FunUtil;
import com.yem.wm.utils.FunctionalCommon;
import com.yem.wm.utils.OrgFilterUtils;
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.dataentity.entity.OrmLocaleValue;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.AfterAddRowEventArgs;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.IFormView;
import kd.bos.form.control.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
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.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import org.apache.logging.log4j.util.StringBuilders;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.Date;
import java.util.EventObject;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 张立攀
 * @version 1.0
 * @description 发货通知单
 * @date 2023-09-01 9:33
 */
public class Delivernotice extends AbstractBillPlugIn implements BeforeF7SelectListener {
    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        FunctionalCommon.setBillType(this);//赋值对应视图单据类型
    }


    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        IFormView view = this.getView();
        String operateKey = e.getOperateKey();
        OperationResult operationResult = e.getOperationResult();
        switch (operateKey) {
            case "save":
                if (YEM.isNotEmpty(operationResult)) {
                    if (operationResult.isSuccess()) {
                        view.invokeOperation("refresh");
                    }
                }
                break;
            case "submit":
                //end by zhouc  2021-03-05
                //if (YEM.isNotEmpty(operationResult) && operationResult.isSuccess()) {
                if (YEM.isNotEmpty(operationResult)) {
                    view.invokeOperation("refresh");
                }
                break;
            case "audit":
                //end by zhouc  2021-03-05
                //if (YEM.isNotEmpty(operationResult) && operationResult.isSuccess()) {
                if (YEM.isNotEmpty(operationResult)) {
                    view.invokeOperation("refresh");
                }
                break;
            case "unsubmit":
                //end by zhouc  2021-03-05
                //if (YEM.isNotEmpty(operationResult) && operationResult.isSuccess()) {
                if (YEM.isNotEmpty(operationResult)) {
                    view.invokeOperation("refresh");
                }
                break;
            case "unaudit":
                //end by zhouc  2021-03-05
                //if (YEM.isNotEmpty(operationResult) && operationResult.isSuccess()) {
                if (YEM.isNotEmpty(operationResult)) {
                    view.invokeOperation("refresh");
                }
                break;
            case "contractamtviewreceipts":
                Map<String, Object> map = new HashMap();
                map.put("flag", "A");
                FunUtil.viewForm("yem_contractamtlistrealit", map, view);
                break;
            case "contractamtviewoccupy":
                map = new HashMap();
                map.put("flag", "B");
                FunUtil.viewForm("yem_contractamtlistoccupy", map, view);
                break;
            case "inventoryquery":
                inventoryQuery();
                break;
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs e) {
        super.beforeDoOperation(e);

        IFormView view = this.getView();
        FormOperate source = (FormOperate) e.getSource();
        String operateKey = source.getOperateKey();
        if ("save".equals(operateKey)) {

            IDataModel model = this.getModel();
            String isdeclare = (String) model.getValue("yem_isdeclare");
            String rep = "本票报关";
            String norep = "本票不报关";
            boolean isrep = "A".equals(isdeclare);
            String val = "A".equals(isdeclare) ? rep : norep;
            OrmLocaleValue comment = (OrmLocaleValue) model.getValue("yem_comment");
            String localeValue = comment.getLocaleValue();
            StringBuilder repSb = new StringBuilder();

//            if (localeValue == null || localeValue.isEmpty()) {
//                repSb.append(val);
//            } else if (localeValue.contains(rep) || localeValue.contains(norep)) {
//                localeValue = localeValue.replace(rep, "");
//                localeValue = localeValue.replace(norep, "");
//                repSb.append(val);
//            } else {
//                repSb.append(val);
//            }
//            repSb.append(" ").append(localeValue == null ? "" : localeValue.trim());
//
//            comment.setLocaleValue(repSb.toString());
//            model.setValue("yem_comment", comment);


            DynamicObject dataEntity = model.getDataEntity(true);
            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
            for (DynamicObject dynamicObject : collection) {
                String businesssort = dynamicObject.getString("yem_businesssort");
                if ("Z".equals(businesssort)) {
                    StringBuilder sb = new StringBuilder();
                    DynamicObjectCollection subCollection = dynamicObject.getDynamicObjectCollection("yem_es_salesorder_z");
                    for (DynamicObject subObject : subCollection) {
                        String vehicleno = subObject.getString("yem_vehicleno");
                        if (YEM.isNotEmpty(vehicleno)) {
                            sb.append(vehicleno).append("；");
                        }
                    }
                    if (sb.length() > 0) {
                        sb.deleteCharAt(sb.length() - 1);
                    }
                    dynamicObject.set("yem_remark", sb.toString());
                }
            }

            view.updateView("yem_es_materialinfo");
            view.updateView("yem_es_salesorder_z");
        }
    }

    public void inventoryQuery() {
        IFormView view = this.getView();
        EntryGrid materialInfo = view.getControl("yem_es_materialinfo");
        int[] selectRows = materialInfo.getSelectRows();
        if (selectRows.length != 1) {
            view.showErrorNotification("只允许选择一行库存查询！");
        } else {
            FunctionalCommon.viewForm("yem_delivernoticeinventor", null, view);
        }
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        BasedataEdit warehouse = this.getControl("yem_warehouse");
        warehouse.addBeforeF7SelectListener(this);
        BasedataEdit location = this.getControl("yem_location");
        location.addBeforeF7SelectListener(this);
        BasedataEdit yem_org = this.getControl("yem_org");
        yem_org.addBeforeF7SelectListener(this);
        BasedataEdit yem_companyorg = this.getControl("yem_companyorg");
        yem_companyorg.addBeforeF7SelectListener(this);
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String name = e.getProperty().getName();
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        switch (name) {
            case "yem_location":
                //库区根据仓库过滤
                setLocationFilter(e, model, view);
                break;
            case "yem_org":
            case "yem_companyorg"://财务组织
                DynamicObject value = (DynamicObject) this.getModel().getValue("org");
                e.addCustomQFilter(OrgFilterUtils.getOrgFilter(value));
                break;
            default:
                break;
        }
    }

    private void setLocationFilter(BeforeF7SelectEvent e, IDataModel model, IFormView view) {
        int row = e.getRow();
        DynamicObject wh = (DynamicObject) model.getValue("yem_warehouse", row);
        if (wh != null) {
            e.addCustomQFilter(new QFilter("group.id", QCP.equals, wh.get("id")));
        } else {
            view.showErrorNotification("请先选择仓库！");
            e.setCancel(true);
        }
    }

    @Override
    public void afterAddRow(AfterAddRowEventArgs e) {
        super.afterAddRow(e);
        IDataModel model = this.getModel();
        int rowIdx = e.getInsertRow();
        if (rowIdx >= 0) {
            Object org = model.getValue("yem_org");
            model.setValue("yem_e_deliverorg", org, rowIdx);
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        IDataModel model = this.getModel();
        int rowIndex = e.getChangeSet()[0].getRowIndex();
        super.propertyChanged(e);
        String name = e.getProperty().getName();
        if ("yem_org".equals(name)) {
            updateEntryDeliverOrg();
        }
        if ("yem_priceandtax".equals(name) || "yem_qty".equals(name)) {
            BigDecimal priceandtax = (BigDecimal) model.getValue("yem_priceandtax", rowIndex);
            BigDecimal qty = (BigDecimal) model.getValue("yem_qty", rowIndex);
            if (priceandtax != null && qty != null) {
                priceandtax = priceandtax.setScale(2, RoundingMode.HALF_UP);
                qty = qty.setScale(2, RoundingMode.HALF_UP);
                model.setValue("yem_amountandtax", priceandtax.multiply(qty), rowIndex);
            }
        }
    }

    private void updateEntryDeliverOrg() {
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        DynamicObject dataEntity = model.getDataEntity(true);
        DynamicObject org = dataEntity.getDynamicObject("yem_org");
        DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_es_materialinfo");
        for (DynamicObject dynamicObject : collection) {
            dynamicObject.set("yem_e_deliverorg", org);
        }
        view.updateView("yem_es_materialinfo");
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        duedate();
    }

    private void duedate() {
        LocalDate date = LocalDate.now();
        LocalDate localDate = date.plusMonths(1);
        LocalDate withDayOfMonth = localDate.withDayOfMonth(15);
        this.getModel().setValue("yem_duedate", withDayOfMonth);
    }
}
