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

import com.yem.wm.es.salesorder.utils.SalesOrderUtils;
import com.yem.wm.utils.YEM;
import kd.bos.bill.AbstractBillPlugIn;
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.AfterAddRowEventArgs;
import kd.bos.entity.datamodel.events.AfterDeleteRowEventArgs;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.property.BasedataProp;
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.AttachmentPanel;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.RefBillEdit;
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 kd.bos.servicehelper.AttachmentServiceHelper;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;

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

/**
 * @author xwudd
 * @date 14:15
 * @Description
 **/
public class DebCredNoteEdit extends AbstractBillPlugIn implements BeforeF7SelectListener {
    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        setMustInput();
    }

    @Override
    public void afterBindData(EventObject e) {
        IFormView view = this.getView();
        IDataModel model = view.getModel();
        FormShowParameter fsp = view.getFormShowParameter();
        OperationStatus status = fsp.getStatus();
        String appId = fsp.getAppId();
        if (OperationStatus.ADDNEW == status && "yem_im".equals(appId)) {
            String formId = fsp.getFormId();
            DynamicObject billType = BusinessDataServiceHelper.loadSingle("bos_billtype", "id",
                    new QFilter[]{new QFilter("number", QCP.equals, formId)});
            model.setValue("yem_billtype", billType);
        }
//        EnaCreditNoteDes();
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        RefBillEdit sourceCreditNo = (RefBillEdit) this.getControl("yem_sourcecreditno");
        sourceCreditNo.addBeforeF7SelectListener(this);
        RefBillEdit contractNo_d = (RefBillEdit) this.getControl("yem_contractno_d");
        contractNo_d.addBeforeF7SelectListener(this);
        RefBillEdit contractNo_s = (RefBillEdit) this.getControl("yem_contractno_s");
        contractNo_s.addBeforeF7SelectListener(this);
        RefBillEdit yem_debcrednoteno = (RefBillEdit) this.getControl("yem_debcrednoteno");
        yem_debcrednoteno.addBeforeF7SelectListener(this);
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String name = e.getProperty().getName();
        DynamicObject data = this.getModel().getDataEntity(true);
        switch (name) {
            case "yem_sourcecreditno":
//                DynamicObjectCollection dy = data.getDynamicObjectCollection("yem_creditnotesource");
//                if (dy != null && dy.size() > 0) {
//                    throw new KDBizException("已存在【贷记单来源明细】");
//                }
//                selectF7SourceCreditNo(e);//贷记单反写配件资金池功能完成后开启
                break;
            case "yem_contractno_s":
            case "yem_contractno_d":
                selectF7ContractNo(e);
                break;
            case "yem_debcrednoteno":
                DynamicObject yem_groupcusfields = data.getDynamicObject("yem_groupcusfields");
                if (yem_groupcusfields == null) {
                    throw new KDBizException("集团客户不能为空！");
                }
                DynamicObject yem_bd_products = data.getDynamicObject("yem_bd_products");
                if (yem_bd_products == null) {
                    throw new KDBizException("产品类型不能为空");
                }
                DynamicObject yem_currency = data.getDynamicObject("yem_currency");
                if (yem_currency == null) {
                    throw new KDBizException("结算币别不能为空");
                }
                QFilter qFilter = new QFilter("yem_billtype.number", QCP.equals, "yem_debcrednote_j");//
                qFilter.and(new QFilter("yem_groupcusfields.number", QCP.equals, yem_groupcusfields.getString("number")));
                qFilter.and(new QFilter("yem_bd_products.number", QCP.equals, yem_bd_products.getString("number")));
                qFilter.and(new QFilter("yem_currency.number", QCP.equals, yem_currency.getString("number")));
                DynamicObjectCollection Object = QueryServiceHelper.query("yem_debcrednote", "id,yem_amount,yem_towardwriteamt", qFilter.toArray());
                List list = new ArrayList<>();
                for (int i = 0; i < Object.size(); i++) {
                    DynamicObject dynamicObject = Object.get(i);
                    BigDecimal yem_amount = dynamicObject.getBigDecimal("yem_amount");
                    BigDecimal yem_towardwriteamt = dynamicObject.getBigDecimal("yem_towardwriteamt");
                    if (yem_amount.subtract(yem_towardwriteamt).compareTo(BigDecimal.ZERO) == 1) {
                        list.add(dynamicObject.getLong("id"));
                    }
                }
                e.addCustomQFilter(new QFilter("id", QCP.in, list));
                break;
        }
    }


    /**
     * @description 来源 去向分录的合同号
     * @author xwudd
     * @param[1] e
     * return
     * @time 2023/11/17 14:56
     */

    public void selectF7ContractNo(BeforeF7SelectEvent e) {
        IDataModel model = this.getModel();
        DynamicObject customer = (DynamicObject) model.getValue("yem_customer");
        Long customerId = YEM.isNotEmpty(customer) ? customer.getLong("id") : 0L;
        e.addCustomQFilter(new QFilter("yem_customer", QCP.in, customerId));
    }

    /**
     * @description 过滤来源贷记单号
     * @author xwudd
     * return
     * @time 2023/8/7 16:26
     */
    public void selectF7SourceCreditNo(BeforeF7SelectEvent e) {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject customer = (DynamicObject) model.getValue("yem_customer");
        DynamicObject products = (DynamicObject) model.getValue("yem_bd_products");
        DynamicObject yem_billtype = (DynamicObject) model.getValue("yem_billtype");
        if (YEM.isNotEmpty(customer) && YEM.isNotEmpty(products)) {
            List<Long> ids = new ArrayList<>();
            String number = yem_billtype.getString("number");
            if (number.equals("yem_debcrednote_a")) {

            } else {
                DynamicObject spCapitalPool = BusinessDataServiceHelper.loadSingle("yem_spcapitalpool", "id,yem_spcapitalpool_o.yem_residueavaamt,yem_spcapitalpool_o.yem_sourcebillid_o,",
                        new QFilter[]{new QFilter("yem_customer", QCP.equals, customer.getPkValue()),
                                new QFilter("yem_bd_products", QCP.equals, products.getPkValue())});
                if (YEM.isNotEmpty(spCapitalPool)) {
                    DynamicObjectCollection spCapitalPool_os = spCapitalPool.getDynamicObjectCollection("yem_spcapitalpool_o");
                    for (DynamicObject spCapitalPool_o : spCapitalPool_os) {
                        BigDecimal residueAvaAmt = spCapitalPool_o.getBigDecimal("yem_residueavaamt");
                        if (residueAvaAmt.compareTo(BigDecimal.ZERO) > 0) {
                            ids.add(spCapitalPool_o.getLong("yem_sourcebillid_o"));
                        }
                    }
                }
            }
            e.addCustomQFilter(new QFilter("id", QCP.in, ids));
        } else {
            view.showMessage("请先选择客户及产品类型！");
            e.setCancel(true);
        }
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs e) {
        super.beforeDoOperation(e);
        String operateKey = ((FormOperate) e.getSource()).getOperateKey();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        IFormView view = this.getView();
        // 双签附件回填
        if ("contractresigning".equals(operateKey)) {
            String billstatus = dataEntity.getString("billstatus");
            if ("C".equals(billstatus)) {
                FormShowParameter parameter = new FormShowParameter();
                parameter.setStatus(OperationStatus.ADDNEW);
                parameter.getOpenStyle().setShowType(ShowType.Modal);
                parameter.setFormId("yem_es_contractresign");
                parameter.setCloseCallBack(new CloseCallBack(this, "yem_es_contractresign"));
                view.showForm(parameter);
            } else {
                this.getView().showErrorNotification("当前贷记单还未审核，不允许回签！");
            }
        }
        if ("contractdelsigning".equals(operateKey)) {
            String yem_signconfirmstatus = dataEntity.getString("yem_counstat");
            if (yem_signconfirmstatus.equals("B")) {
                view.showErrorNotification("当前贷记单已经回签确认，禁止贷记单客户反回签！");
                return;
            }
            AttachmentPanel panel = getControl("attachmentpanel");
            List<Map<String, Object>> attachmentData = panel.getAttachmentData();
            if (attachmentData.isEmpty()) {
                return;
            }
            attachmentData.forEach(panel::remove);
            List<Map<String, Object>> attachments = AttachmentServiceHelper.getAttachments(dataEntity.getDynamicObjectType().getName(), dataEntity.getPkValue(), "yem_attachmentpanelap");
            dataEntity.set("yem_attachmentcountfield", attachments.size());
            dataEntity.set("yem_signconfirmstatus", "B");
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            view.invokeOperation("refresh");
        }
        if ("unaudit".equals(operateKey)) {
            String generate = (String) model.getValue("yem_generate");
            if ("B".equals(generate)) {//订单生成
                throw new KDBizException("贷记单生成方式为订单生成，不允许反审核！！");
            }
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        String actionId = e.getActionId();
        Object returnData = e.getReturnData();
        IDataModel model = this.getModel();
        if ("yem_es_contractresign".equals(actionId)) {
            putAttachmentData((Map<String, Object>) returnData, model, this.getView());
        }
    }

    public void putAttachmentData(Map<String, Object> attachInfor, IDataModel modal, IFormView view) {
        String entityId = view.getEntityId();
        view.invokeOperation("refresh");
        if (attachInfor != null) {
            List<Map<String, Object>> retData = (List<Map<String, Object>>) attachInfor.get("attach");
            Long userId = (Long) attachInfor.get("user");
            Date date = (Date) attachInfor.get("date");
            DynamicObject dataEntity = modal.getDataEntity(true);
            dataEntity.set("yem_signbackerid", userId);
            dataEntity.set("yem_signbackdate", date);
            dataEntity.set("yem_checkboxfield", true);
            dataEntity.set("yem_signconfirmstatus", "A");
            if (retData != null && !retData.isEmpty()) {
                for (Map<String, Object> map : retData) {
                    String url = (String) map.get("url");
                    String name = (String) map.get("name");
                    // 持久化附件到服务器
                    url = SalesOrderUtils.uploadTempfile(url, name);
                    map.put("url", url);
                    map.put("creator", UserServiceHelper.getCurrentUserId());
                    map.put("modifytime", new Date().getTime());
                }
                AttachmentServiceHelper.upload(entityId, dataEntity.getPkValue(), "attachmentpanel", retData);
            }
            List<Map<String, Object>> attachments = AttachmentServiceHelper.getAttachments(dataEntity.getDynamicObjectType().getName(), dataEntity.getPkValue(), "yem_attachmentpanelap");
            dataEntity.set("yem_attachmentcountfield", attachments.size());
            SaveServiceHelper.save(new DynamicObject[]{dataEntity});
            view.invokeOperation("refresh");
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String operateKey = e.getOperateKey();
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        DynamicObject dataEntity = model.getDataEntity(true);
        if ("actualocc".equals(operateKey)) {
            this.getView().invokeOperation("refresh");
        }
        if ("releasereality".equals(operateKey)) {
            this.getView().invokeOperation("refresh");
        }
        if ("submit".equals(operateKey)) {
            this.getView().invokeOperation("refresh");
        }
        if ("upsumamt".equals(operateKey)) {
            long yem_spcapitalpoolid = dataEntity.getLong("yem_spcapitalpoolid");//配件资金池id
            DynamicObject yem_spcapitalpool = BusinessDataServiceHelper.loadSingle(yem_spcapitalpoolid, "yem_spcapitalpool");
            if (yem_spcapitalpool != null) {

            }
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        String name = e.getProperty().getName();
        switch (name) {
            case "yem_sourcecreditno":
//                EnaCreditNoteDes();
                break;
            case "yem_debcredtype":
                setMustInput();
                break;
            default:
                break;
        }
    }

    private void setMustInput() {
        String yemDebcredtype = getModel().getValue("yem_debcredtype").toString();
        if ("DN".equals(yemDebcredtype)) {
//            BasedataEdit yem_debittype = this.getView().getControl("yem_debittype");
//            yem_debittype.setMustInput(true);
//            BasedataProp yem_debittypeProp = (BasedataProp) yem_debittype.getProperty();
//            yem_debittypeProp.setMustInput(true);
            BasedataEdit yem_credittype = this.getView().getControl("yem_credittype");
            yem_credittype.setMustInput(false);
            BasedataProp yem_credittypeProp = (BasedataProp) yem_credittype.getProperty();
            yem_credittypeProp.setMustInput(false);
        } else if ("CN".equals(yemDebcredtype)) {
//            BasedataEdit yem_debittype = this.getView().getControl("yem_debittype");
//            yem_debittype.setMustInput(false);
//            BasedataProp yem_debittypeProp = (BasedataProp) yem_debittype.getProperty();
//            yem_debittypeProp.setMustInput(false);
            BasedataEdit yem_credittype = this.getView().getControl("yem_credittype");
            yem_credittype.setMustInput(true);
            BasedataProp yem_credittypeProp = (BasedataProp) yem_credittype.getProperty();
            yem_credittypeProp.setMustInput(true);
        } else {
//            BasedataEdit yem_debittype = this.getView().getControl("yem_debittype");
//            yem_debittype.setMustInput(false);
//            BasedataProp yem_debittypeProp = (BasedataProp) yem_debittype.getProperty();
//            yem_debittypeProp.setMustInput(false);
            BasedataEdit yem_credittype = this.getView().getControl("yem_credittype");
            yem_credittype.setMustInput(false);
            BasedataProp yem_credittypeProp = (BasedataProp) yem_credittype.getProperty();
            yem_credittypeProp.setMustInput(false);
        }
    }

    @Override
    public void afterAddRow(AfterAddRowEventArgs e) {
        super.afterAddRow(e);
        String name = e.getEntryProp().getName();
        if ("yem_creditnotesource".equals(name)) {
//            EnaCreditNoteDes();
        }
    }

    @Override
    public void afterDeleteRow(AfterDeleteRowEventArgs e) {
        super.afterDeleteRow(e);
        String name = e.getEntryProp().getName();
        if ("yem_creditnotesource".equals(name)) {
//            EnaCreditNoteDes();
        }
    }

    /**
     * @description 贷记单去向锁定性控制
     * @author xwudd
     * return
     * @time 2023/11/15 11:36
     */

    public void EnaCreditNoteDes() {
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        DynamicObject sourceCreditNo = (DynamicObject) model.getValue("yem_sourcecreditno");
        int creditNoteSource = model.getEntryRowCount("yem_creditnotesource");
        if (YEM.isEmpty(sourceCreditNo) && creditNoteSource <= 0) {
            view.setEnable(false, "yem_tabpageap");
        } else {
            view.setEnable(true, "yem_tabpageap");
        }
    }
}
