package com.yem.wm.syn.eas.form.fi;

import com.alibaba.fastjson.JSON;
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.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.IFormView;
import kd.bos.form.control.events.BeforeItemClickEvent;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.list.ListFilterParameter;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

import java.util.EventObject;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 付款申请单表单插件
 */
public class PayapplyFrom extends AbstractBillPlugIn implements BeforeF7SelectListener
{


    @Override
    public void addItemClickListeners(String... keys)
    {
        super.addItemClickListeners(keys);
        //  this.addItemClickListeners("bar_unsubmit");
    }



    @Override
    public void beforeItemClick(BeforeItemClickEvent evt)
    {
        super.beforeItemClick(evt);
        String itemKey = evt.getItemKey();
        if (!"bar_unsubmit".equals(itemKey)) {
            return;
        }
        IFormView view = this.getView();
        IDataModel model = view.getModel();
        Boolean yemIseas = (Boolean) model.getValue("yem_iseas");
        if (yemIseas) {
            view.showTipNotification("已同步EAS不允许手动撤销");
            evt.setCancel(true);
        }

    }

    @Override
    public void afterCreateNewData(EventObject e)
    {
        super.afterCreateNewData(e);
        String currSelectedOrg = this.getView().getParentView().getPageCache().get("currSelectedOrg");
        Object parse = JSON.parse(currSelectedOrg);
        IDataModel model = this.getModel();
        if (parse != null) {
            List<Long> longs = (List<Long>) parse;
            if (longs.isEmpty()) {
                return;
            }
            model.setValue("yem_applyorg", longs.get(0));
            model.setValue("yem_payorg", longs.get(0));
            model.setValue("yem_purorg", longs.get(0));
        }
    }


    @Override
    public void registerListener(EventObject e)
    {
        super.registerListener(e);
        BasedataEdit appdepartment = this.getControl("yem_appdepartment");
        appdepartment.addBeforeF7SelectListener(this);

        BasedataEdit yem_e_asstact = this.getControl("yem_e_asstact");
        yem_e_asstact.addBeforeF7SelectListener(this);

        BasedataEdit financialorg = this.getControl("yem_financialorg");
        financialorg.addBeforeF7SelectListener(this);

    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e)
    {
        String key = e.getProperty().getName();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        // 申请部门                              财务组织
        if ("yem_appdepartment".equals(key) || "yem_financialorg".equals(key)) {
            DynamicObject applyorg = dataEntity.getDynamicObject("yem_applyorg");
            e.addCustomQFilter(OrgFilterUtils.getOrgFilter(applyorg));
        }
        //往来户
        if ("yem_e_asstact".equals(key)) {
            //财务组织
            Object yemFinancialorg = model.getValue("yem_financialorg");
            if (yemFinancialorg==null){
                this.getView().showTipNotification("请先选择财务组织!");
                e.setCancel(true);
                return;
            }
            DynamicObject financialorg = (DynamicObject) yemFinancialorg;
            //获取类型
            int i = model.getEntryCurrentRowIndex("yem_applaydetail");
            DynamicObject yemApplaydetail = model.getEntryRowEntity("yem_applaydetail", i);
            String yemEAsstacttype = yemApplaydetail.getString("yem_e_asstacttype");
            if ("bd_supplier".equals(yemEAsstacttype)){
                DynamicObject[] yemSupliercompanycoll = BusinessDataServiceHelper.load("yem_supliercompanyinfo", "createorg,yem_supplier", new QFilter[]{new QFilter("createorg.id", QCP.equals, financialorg.getPkValue())});
                Set<Long> strArray = new HashSet<>();


                for (int j = 0; j < yemSupliercompanycoll.length; j++) {
                    DynamicObject suplier = yemSupliercompanycoll[j];
                    DynamicObject yem_supplier = suplier.getDynamicObject("yem_supplier");
                    strArray.add(yem_supplier.getLong("id"));
                }
                QFilter qFilter = new QFilter("id", QCP.in, strArray);

                ListShowParameter formShowParameter = (ListShowParameter) e.getFormShowParameter();

                ListFilterParameter listFilterParameter = formShowParameter.getListFilterParameter();
                listFilterParameter.setFilter(qFilter);
            }else if("bd_customer".equals(yemEAsstacttype)){
                DynamicObject[] customercompanycoll = BusinessDataServiceHelper.load("yem_customercompanyinfo", "createorg,yem_customer", new QFilter[]{new QFilter("createorg.id", QCP.equals, financialorg.getPkValue())});
                Set<Long> strArray = new HashSet<>();
                for (int j = 0; j < customercompanycoll.length; j++) {
                    DynamicObject customer = customercompanycoll[j];
                    DynamicObject yem_customer = customer.getDynamicObject("yem_customer");
                    strArray.add(yem_customer.getLong("id"));
                }
                QFilter qFilter = new QFilter("id", QCP.in, strArray);
                ListShowParameter formShowParameter = (ListShowParameter) e.getFormShowParameter();
                ListFilterParameter listFilterParameter = formShowParameter.getListFilterParameter();
                listFilterParameter.setFilter(qFilter);
            }
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e)
    {
        super.propertyChanged(e);
        ChangeData changeData = e.getChangeSet()[0];
        int rowIndex = changeData.getRowIndex();
        String name = e.getProperty().getName();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);
        if ("yem_e_asstact".equals(name) || "yem_e_asstacttype".equals(name)) {

            model.setValue("yem_e_assacct", null, rowIndex);
            model.setValue("yem_e_bebank", null, rowIndex);
            model.setValue("yem_account", null, rowIndex);

            DynamicObjectCollection collection = dataEntity.getDynamicObjectCollection("yem_applaydetail");
            DynamicObject dynamicObject = collection.get(rowIndex);
            // 往来户类型
            String asstacttype = dynamicObject.getString("yem_e_asstacttype");
            if (YEM.isEmpty(asstacttype)) return;
            // 往来户
            DynamicObject asstact = dynamicObject.getDynamicObject("yem_e_asstact");
            if (asstact == null) return;
            long id = asstact.getLong("id");

            DynamicObject customer = BusinessDataServiceHelper.loadSingle(id, asstacttype);
            if (customer == null) return;
            DynamicObjectCollection entryBank = customer.getDynamicObjectCollection("entry_bank");
            if (entryBank.isEmpty()) return;
            boolean hasDefault = false;
            for (DynamicObject bank : entryBank) {
                if (bank.getBoolean("isdefault_bank")) {
                    dynamicObject.set("yem_e_assacct", bank.getString("accountname"));
                    dynamicObject.set("yem_e_bebank", bank.getDynamicObject("bank"));
                    dynamicObject.set("yem_account", bank.getString("bankaccount"));
                    hasDefault = true;
                }
            }
            if (!hasDefault) {
                DynamicObject bank = entryBank.get(0);
                dynamicObject.set("yem_e_assacct", bank.getString("accountname"));
                dynamicObject.set("yem_e_bebank", bank.getDynamicObject("bank"));
                dynamicObject.set("yem_account", bank.getString("bankaccount"));
            }
            this.getView().updateView("yem_applaydetail");
        }
    }
}
