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

import com.yem.wm.im.debcrednotenew.utils.DebCredUtils;
import com.yem.wm.utils.YEM;
import kd.bd.master.helper.MasterDataHelper;
import kd.bd.master.util.GroupStandardUtils;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.entity.BasedataEntityType;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.IDataModelChangeListener;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.property.BasedataProp;
import kd.bos.form.IFormView;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.AfterBindingDataEvent;
import kd.bos.form.field.events.BasedataEditListener;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.list.ListShowParameter;
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.util.EventObject;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class MerChantApplyEdit extends AbstractBillPlugIn implements BeforeF7SelectListener, BasedataEditListener, IDataModelChangeListener {
    @Override
    public void afterLoadData(EventObject e) {
        super.afterLoadData(e);
        BasedataEdit yemAssignorg = this.getView().getControl("yem_assignorg");
        yemAssignorg.setDisplayProp("org.number");
        doLockGroupCustom();
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        IDataModel model = this.getModel();
        String name = e.getProperty().getName();
        int row = e.getRow();
        switch (name) {
            case "yem_groupid":
                addGroupbeforeF7Select(model, e, "bd_customer");
                break;
            case "yem_group":
                addHeadGroupBeforeF7Select(e);
                break;
            default:
                break;
        }
    }

    private void addHeadGroupBeforeF7Select(BeforeF7SelectEvent e) {
        List<QFilter> customQFilters = e.getCustomQFilters();
        DynamicObject[] load = BusinessDataServiceHelper.load("bd_customergroup", "id, number, parent", new QFilter[]{new QFilter("enable", "=", "1")});

        Set<Long> son = new HashSet<>();

        Set<Long> parentId = new HashSet<>();
        for (DynamicObject dynamicObject : load) {
            DynamicObject parent = dynamicObject.getDynamicObject("parent");
            if (parent != null) {
                parentId.add(parent.getLong("id"));
            }
        }

        for (DynamicObject dynamicObject : load) {
            long id = dynamicObject.getLong("id");
            if (!parentId.contains(id)) {
                son.add(id);
            }
        }
        customQFilters.add(new QFilter("id", "in", son));
    }


    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        String operateKey = e.getOperateKey();
        OperationResult operationResult = e.getOperationResult();
        IFormView view = this.getView();
        if ("syneas".equals(operateKey)) {
            if (operationResult.isSuccess()) {
//                updateGroupCustom();
                doLockGroupCustom();
            }
            if (YEM.isNotEmpty(operationResult)) {
                view.invokeOperation("refresh");
            }
        }
        if ("save".equals(operateKey)) {
            if (YEM.isNotEmpty(operationResult)) {
//                view.invokeOperation("refresh");
            }
        }

        if ("audit".equals(operateKey)) {
            if (operationResult.isSuccess()) {
//                setDefaultGroupCustom();
                IDataModel model = this.getModel();
                String iscompclient = (String) model.getValue("yem_iscompclient");
                String easnumber = (String) model.getValue("yem_easnumber");
                String erpnumber = (String) model.getValue("yem_erpnumber");
                view.invokeOperation("refresh");
                model.updateCache();
                if ("B".equals(iscompclient)) {
                    DynamicObject single = BusinessDataServiceHelper.loadSingle("bd_customer", new QFilter[]{new QFilter("number", QCP.in, new String[]{erpnumber, easnumber})});
                    if (single != null) {
                        model.setValue("yem_groupcustomers", single);
                        DynamicObject dataEntity = model.getDataEntity(true);
                        SaveServiceHelper.update(dataEntity);
                        view.invokeOperation("refresh");
                    }
                }
            }
        }
    }

//    private void setDefaultGroupCustom() {
//        IDataModel model = this.getModel();
//        String erpnumber = (String) model.getValue("yem_erpnumber");
//        DynamicObject single = BusinessDataServiceHelper.loadSingle("bd_customer", new QFilter[]{new QFilter("number", QCP.equals, erpnumber)});
//        if (single != null) {
//            model.setValue("yem_groupcustomers", single);
//        }
//        DynamicObject dataEntity = model.getDataEntity(true);
//        SaveServiceHelper.update(dataEntity);
//    }

    private void updateGroupCustom() {
        IDataModel model = this.getModel();
        DynamicObject dataEntity = model.getDataEntity(true);


    }

    private void doLockGroupCustom() {
        IDataModel model = this.getModel();
        IFormView view = this.getView();
        boolean issyneas = (boolean) model.getValue("yem_issyneas");
        if (issyneas) {
            view.setEnable(false, "yem_groupcustomers");
        } else {
            view.setEnable(true, "yem_groupcustomers");
        }
    }


    public void addGroupbeforeF7Select(IDataModel model, BeforeF7SelectEvent beforeF7SelectEvent, String type) {
        int currentRowIndex = model.getEntryCurrentRowIndex("yem_merchantapply_e");
        DynamicObject entryRowEntity = model.getEntryRowEntity("yem_merchantapply_e", currentRowIndex);
        if (entryRowEntity != null) {
            Long useOrgId = GroupStandardUtils.getDataByType(null);
            Set<Long> useOrgIds = new HashSet(1);
            useOrgIds.add(useOrgId);
            Set<Long> groupOrgIds = GroupStandardUtils.getGroupOrgId(type, useOrgIds);
            Object standard = entryRowEntity.get("yem_standardid");
            if (currentRowIndex >= 0 && standard != null) {
                ListShowParameter listShowParameter = (ListShowParameter) beforeF7SelectEvent.getFormShowParameter();
                List<QFilter> qFilters = listShowParameter.getListFilterParameter().getQFilters();
                qFilters.add(new QFilter("standard", "=", ((DynamicObject) standard).getPkValue()));
                boolean isGroupLastNew = (new MasterDataHelper()).getGroupNew();
                if (isGroupLastNew) {
                    qFilters.add(new QFilter("isleaf", "=", "1"));
                }

                if (!groupOrgIds.isEmpty()) {
                    qFilters.add(new QFilter("createorg", "in", groupOrgIds));
                }

                listShowParameter.setCustomParam("groupStandard", ((DynamicObject) standard).getPkValue());
                listShowParameter.setCustomParam("useOrg", useOrgId.toString());
            }

        }
    }

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

        BasedataEdit yem_group = this.getView().getControl("yem_group");
        yem_group.addBeforeF7SelectListener(this);
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        IDataModel model = this.getModel();
//        DynamicObject[] customerGroupStandards = BusinessDataServiceHelper.load("bd_customergroupstandard", "id", null, "createtime desc");
//        DynamicObject waitgroupObj = BusinessDataServiceHelper.loadSingle("bd_customergroup",
//                new QFilter[]{new QFilter("number", QCP.equals, "waitgroup")});
//        for (DynamicObject customerGroupStandard : customerGroupStandards) {
//            int groupRowNum = model.createNewEntryRow("yem_merchantapply_e");
//            model.setValue("yem_standardid", customerGroupStandard, groupRowNum);
//            if (!customerGroupStandard.getString("number").equals("customerGroupStandard")) {
//                model.setValue("yem_groupid", waitgroupObj, groupRowNum);
//                this.getView().setEnable(false, groupRowNum, "yem_groupid");
//            }
//        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        IDataModel model = this.getModel();
        ChangeData changeData = e.getChangeSet()[0];
        int rowIndex = changeData.getRowIndex();
        Object newValue = changeData.getNewValue();
        Object oldValue = changeData.getOldValue();
        if ("yem_groupid".equals(e.getProperty().getName())) {
            int enrow = this.getModel().getEntryCurrentRowIndex("yem_merchantapply_e");
            String standardNum = ((DynamicObject) this.getModel().getValue("yem_standardid", enrow)).getString("number");
            if ("customerGroupStandard".equals(standardNum)) {
                if (((DynamicObject) this.getModel().getValue("yem_groupid", enrow)) != null) {
                    String groupNum = ((DynamicObject) this.getModel().getValue("yem_groupid", enrow)).getString("number");
//                    //获取苍穹分组下客户最大号
//                    QFilter qFilter = new QFilter("group.id", QCP.equals, ((DynamicObject) this.getModel().getValue("yem_groupid", enrow)).getLong("id"));//
//                    qFilter.and(new QFilter("status", QCP.equals, "C"));
//                    String selectfield = DynamicObjectUtil.getSelectfields("bd_customer", false);
//                    DynamicObjectCollection data = QueryServiceHelper.query("bd_customer",
//                            selectfield, new QFilter[]{qFilter}, "number DESC");
//                    if (data.size() > 0) {
//                        DynamicObject dynamicObject = data.get(0);
                    //系统编码
//                        DynamicObject obj = BusinessDataServiceHelper.newDynamicObject("bd_customer");
//                        obj.set("group",(DynamicObject) this.getModel().getValue("yem_groupid", enrow));
//                        //获取配置编码规则生成的编码
//                        CodeRuleInfo codeRule = CodeRuleServiceHelper.getCodeRule(obj.getDataEntityType().getName(), obj, groupNum);
//                        String number = CodeRuleServiceHelper.getNumber(codeRule, obj);
//                        model.setValue("yem_easnumber", number);
//                        model.setValue("yem_erpnumber", number);
//                    } else {
//                        String biggest = "WM" + groupNum + "00001";
//                        model.setValue("yem_easnumber", biggest);
//                        model.setValue("yem_erpnumber", biggest);
//                    }
                    //获取EAS编码最大值  end by zhouc 2024-03-20 禁用
//                    List<Map<String, Object>> maxCustomerNum = RequestEAS.getMaxCustomerNum(groupNum);
//                    for (Map<String, Object> stringObjectMap : maxCustomerNum) {-
//                        String fnumber = (String) stringObjectMap.get("fnumber");
//                        String[] split = fnumber.split(groupNum);
//                        String s = split[split.length - 1];
//                        Integer i = Integer.parseInt(s) + 1;
//                        String s1 = i.toString();
//                        int i1 = s.length() - s1.length();
//                        if (i1 < 0) {
//                            this.getView().showErrorNotification(
//                                    "获取EAS客户分类编码为：【" + groupNum + "】时已经超出最大长度,请联系EAS管理员维护");
//                            model.setValue("yem_easnumber", null);
//                            return;
//                        }
//                        for (int j = 0; j < i1; j++) {
//                            s1 = "0" + s1;
//                        }
//                        fnumber = groupNum + "" + s1;
//                        model.setValue("yem_easnumber", fnumber);
//                    }
                }
            }
        }

        if ("yem_assignorg".equals(e.getProperty().getName())) {
            DynamicObject value = (DynamicObject) newValue;
            if (value != null) {
                DynamicObject org = value.getDynamicObject("org");
                if (org != null) {
                    String number = org.getString("number");
                    if (number.equals("110")) {
                        DynamicObject object = DebCredUtils.seelctDyn("bos_org", "number", "116");
                        model.setValue("yem_finorg", object, rowIndex);
                    } else {
                        DynamicObject object = DebCredUtils.seelctDyn("bos_org", "number", number);
                        model.setValue("yem_finorg", object, rowIndex);
                    }
                }
            }
        }

        if ("yem_group".equals(e.getProperty().getName())) {
            DynamicObject value = (DynamicObject) newValue;
            if (value != null) {
                model.setValue("yem_groupid", value, 0);
            }
        }
    }

    /**
     * 获取字段最大号加1
     *
     * @return
     */
    public String biggest(String fnumber, String groupNum) {
        String[] split = fnumber.split(groupNum);
        String s = split[split.length - 1];
        Integer i = Integer.parseInt(s) + 1;
        String s1 = i.toString();
        int i1 = s.length() - s1.length();
        if (i1 < 0) {
//            this.getView().showErrorNotification(
//                    "获取EAS客户分类编码为：【" + groupNum + "】时已经超出最大长度,请联系EAS管理员维护");
//            model.setValue("yem_easnumber", null);
//            return;
        }
        for (int j = 0; j < i1; j++) {
            s1 = "0" + s1;
        }
        fnumber = groupNum + "" + s1;
        return fnumber;
    }

    @Override
    public void afterBindingData(AfterBindingDataEvent e) {
        BasedataEdit edit = (BasedataEdit) e.getSource();
        edit.setDisplayProp("org.number");
        Object v = e.getDataEntity();
        Object editSearchProp;
        Object displayProp = "";
        if (v == null) {
            return;
        }
        BasedataEntityType dt;
        if (((DynamicObject) v).getDataEntityType() instanceof BasedataEntityType) {
            dt = (BasedataEntityType) ((DynamicObject) v).getDataEntityType();
        } else {
            dt = (BasedataEntityType) ((BasedataProp) edit.getProperty()).getComplexType();
        }

        //获取数据包中的名称字段值
        String nameKey = dt.getNameProperty();

        //动态修改多选基础资料的显示属性为名称(部门)
        if ("yem_assignorg".equals(edit.getKey())) {
            nameKey = "org";
        }
        IDataEntityProperty p4 = dt.findProperty(nameKey);
        DynamicObject org = BusinessDataServiceHelper.loadSingle(((DynamicObject) v).get("id"), dt.getName()).getDynamicObject("org");
        displayProp = String.format("%s,%s", org.getString("name"), org.getString("number"));
        //设置显示属性
        e.setDisplayProp(displayProp.toString());
        //设置编辑显示属性
        e.setEditSearchProp(displayProp.toString());
    }

    @Override
    public void initialize() {
        super.initialize();
        this.getModel().addDataModelChangeListener(this);
        BasedataEdit yem_assignorg = this.getControl("yem_assignorg");
        yem_assignorg.addBasedataEditListener(this);
    }
}
