package com.yem.ia.intebilllogon.form;

import com.yem.em.utils.CommonEmUtils;
import com.yem.ia.intebilllogon.Utils.GetDocumentTypeUtils;
import com.yem.wm.bc.common.CommonUtils;
import com.yem.wm.utils.StringUtils;
//import json.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yem.wm.utils.YunzhijiaUtils;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.dataentity.metadata.IDataEntityType;
import kd.bos.dataentity.metadata.clr.DataEntityPropertyCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.designer.botp.EntityParseHelper;
import kd.bos.entity.*;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.events.ChangeData;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.entity.property.*;
import kd.bos.entity.tree.TreeNode;
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.Control;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.field.MulBasedataEdit;
import kd.bos.form.field.TextEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.plugin.IFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.metadata.dao.MetaCategory;
import kd.bos.metadata.dao.MetadataDao;
import kd.bos.metadata.entity.EntityMetadata;
import kd.bos.metadata.form.ControlAp;
import kd.bos.metadata.form.FormMetadata;
import kd.bos.metadata.treebuilder.FormTreeBuilder;
import kd.bos.metadata.treebuilder.PropTreeBuildOption;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.MetadataServiceHelper;

import java.util.*;

/**
 * @author zhouc
 * @date 2023/8/15 20:06
 * @className IntebilllogonFormPlugIn
 * @description 智能审批单据注册表单插件
 */
public class IntebilllogonFormPlugIn extends AbstractBillPlugIn implements BeforeF7SelectListener {

    @Override
    public void beforePropertyChanged(PropertyChangedArgs e) {
        super.beforePropertyChanged(e);
        IFormView view = this.getView();
        IDataModel model = this.getModel();
        String name = e.getProperty().getName();
        ChangeData changeData = e.getChangeSet()[0];
        int rowIndex = changeData.getRowIndex();
        Object newValue = changeData.getNewValue();
        Object oldValue = changeData.getOldValue();
        if (name.equals("yem_erpfiledformid")) {
            if (newValue != null && ((String) newValue).length() == 0) {
                model.setValue("yem_erpfiledformname", "", rowIndex);
                model.setValue("yem_erpfiledformid", null, rowIndex);
                model.setValue("yem_erpfiledtype", "", rowIndex);
                model.setValue("yem_filedtypename", "", rowIndex);
                model.setValue("yem_identifierbasic", "", rowIndex);
            }
        }
        if (name.equals("yem_erpfiledformid1")) {
            if (newValue != null && ((String) newValue).length() == 0) {
                model.setValue("yem_erpfiledformid1", null, rowIndex);
                model.setValue("yem_erpfiledformname1", null, rowIndex);
                model.setValue("yem_erpfiledtype1", "", rowIndex);
                model.setValue("yem_filedtypename1", "", rowIndex);
                model.setValue("yem_identifierbasic1", "", rowIndex);
            }
        }
        if (name.equals("yem_erpfiledformid1")) {
            int row = this.getModel().getEntryCurrentRowIndex("yem_signentryentity");
            String yem_parentcontainer = (String) model.getValue("yem_parentcontainer", row);
            if (StringUtils.isNotEmpty(yem_parentcontainer)) {
                model.setValue("yem_parentcontainer", "", row);
                model.setValue("yem_parentname", "", row);
            }
        }
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) throws KDBizException {
        super.afterDoOperation(e);
        String key = e.getOperateKey();
//        boolean success = e.getOperationResult().isSuccess();
        IDataModel model = this.getModel();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        if ("pullfromyzj".equals(key)) {
            String url = YunzhijiaUtils.yzjurl + "/cmmpapi/cmmp/viewFormDef.do?tokenId=" + model.getValue("yem_tokenid");
            String param = "{\"formCodeId\":\"" + model.getValue("yem_yzjid") + "\"}";
            String result = "";
            try {
                result = YunzhijiaUtils.doPost(url, param);
            } catch (Exception ex) {
                throw new KDBizException(String.format("接口调用异常%s", ex.getMessage()));
            }
            buildForm(model, result);
//            getView().updateView();
        }
    }

    private void buildForm(IDataModel model, String result) {
        JSONObject json = JSONObject.parseObject(result);
        Boolean success = json.getBoolean("success");
        if (success) {
            JSONObject data = json.getJSONObject("data");
            if (data != null) {
                JSONObject formInfo = data.getJSONObject("formInfo");
                if (formInfo != null) {
                    JSONObject widgetMap = formInfo.getJSONObject("widgetMap");//表头字段
                    for (String headKey : widgetMap.keySet()) {//字段标识
                        JSONObject fieldJson = widgetMap.getJSONObject(headKey);//字段对象
                        String title = fieldJson.getString("title");//标题
                        String type = fieldJson.getString("type");//类型
                        System.out.println(headKey + " " + title + " " + type);
                        String stype = getType(type);
                        //通过审批字段标识-yem_iaformid获取行号
                        //判断是否有该标识
                        boolean b = false;
                        DynamicObjectCollection yemSignentryentitys = (DynamicObjectCollection) model.getValue("yem_signentryentity");
                        for (int i = 0; i < yemSignentryentitys.size(); i++) {
                            DynamicObject yemSignentryentity = yemSignentryentitys.get(i);
                            String yemIaformid = yemSignentryentity.getString("yem_iaformid");
                            //删除没用的数据行
                            if (!widgetMap.containsKey(yemIaformid) && "H".equals(yemSignentryentity.getString("yem_iaentitytype"))) {
                                model.deleteEntryRow("yem_signentryentity", i);
                                i--;
                            }
                            if (headKey.equals(yemIaformid)) {
                                buildHeadEntry(model, headKey, fieldJson, title, type, stype, i);
                                b = true;
                            }
                        }
                        //增行
                        if (!b) {
                            int e1RowNum = model.createNewEntryRow("yem_signentryentity");
                            buildHeadEntry(model, headKey, fieldJson, title, type, stype, e1RowNum);
                        }
                    }
                    JSONObject detailMap = formInfo.getJSONObject("detailMap");//分录字段
                    for (String detailKey : detailMap.keySet()) {//detailKey分录标识
                        JSONObject detailJson = detailMap.getJSONObject(detailKey);
                        String detailTitle = detailJson.getString("title");//分录名称
                        JSONObject widgetVosJson = detailJson.getJSONObject("widgetVos");//分录字段Json
                        //通过审批字段标识-yem_iaformid获取行号
                        //判断是否有该标识
                        boolean b = false;
                        DynamicObjectCollection yemSignentryentitys = (DynamicObjectCollection) model.getValue("yem_signentryentity");
                        int entryrow = -1;
                        for (int i = 0; i < yemSignentryentitys.size(); i++) {
                            DynamicObject yemSignentryentity = yemSignentryentitys.get(i);
                            String yemIaformid = yemSignentryentity.getString("yem_iaformid");
                            //删除没用的数据行
                            if (!detailMap.containsKey(yemIaformid) && "D".equals(yemSignentryentity.getString("yem_iaentitytype"))) {
                                yemSignentryentitys.remove(i);
                                i--;
                            }
                            if (detailKey.equals(yemIaformid)) {
                                b = true;
                                entryrow = buildHentry(model, detailKey, detailTitle, i);
                            }
                        }
                        //增行
                        if (!b) {
                            int e1RowNum = model.createNewEntryRow("yem_signentryentity");
                            entryrow = buildHentry(model, detailKey, detailTitle, e1RowNum);
                        }
                        DynamicObject yemSignentryentity = ((DynamicObjectCollection) this.getModel().getValue("yem_signentryentity")).get(entryrow);
                        DynamicObjectCollection yemSubentryentitys = yemSignentryentity.getDynamicObjectCollection("yem_subentryentity");
                        for (String eField : widgetVosJson.keySet()) {//eField分录字段标识
                            JSONObject eFieldJson = widgetVosJson.getJSONObject(eField);
                            String etitle = eFieldJson.getString("title");//标题
                            String etype = eFieldJson.getString("type");//类型
                            boolean b1 = false;
                            DynamicObject yemSubentryentity = null;
                            for (int i = 0; i < yemSubentryentitys.size(); i++) {
                                yemSubentryentity = yemSubentryentitys.get(i);
                                String yemIaformid1 = yemSubentryentity.getString("yem_iaformid1");
                                //删除没用的数据行
                                if (!widgetVosJson.containsKey(yemIaformid1) && "D".equals(yemSubentryentity.getString("yem_iaentitytype1"))) {
                                    yemSubentryentitys.remove(i);
                                    i--;
                                }
                                if (eField.equals(yemIaformid1)) {
                                    b1 = true;
                                    buildEentry(eField, eFieldJson, etitle, etype, yemSubentryentity);
                                }
                            }
                            if (!b1) {
                                yemSubentryentity = yemSubentryentitys.addNew();
                                buildEentry(eField, eFieldJson, etitle, etype, yemSubentryentity);
                            }
                            System.out.println(detailKey + " " + detailTitle + " " + eField + " " + etitle + " " + etype);
                        }
                        yemSignentryentity.set("yem_subentryentity", yemSubentryentitys);


                    }
                } else {
                    throw new KDBizException("接口返回数据为空！");
                }
            } else {
                throw new KDBizException("接口返回数据为空！");
            }

        } else {
            throw new KDBizException(json.getString("error"));
        }
    }

    private static int buildHentry(IDataModel model, String detailKey, String detailTitle, int i) {
        model.setValue("yem_iaentitytype", "D", i);//审批实体类型
        model.setValue("yem_iaformid", detailKey, i);//审批字段标识
        model.setValue("yem_ianame", detailTitle, i);//审批字段名称
        model.setValue("yem_iatype", "分录", i);//审批字段类型
        return i;
    }

    /**
     * 构建单头字段
     *
     * @param model
     * @param headKey   审批字段标识
     * @param fieldJson 单头JSON
     * @param title     审批字段标识
     * @param type      审批字段名称
     * @param stype     审批字段类型
     * @param i         分录行号
     */
    private static void buildHeadEntry(IDataModel model, String headKey, JSONObject fieldJson, String title, String type, String stype, int i) {
        if ("numberWidget".equals(type) || "moneyWidget".equals(type)) {
            int yem_iaaccuracy = fieldJson.getIntValue("decimalDigit");//精度
            model.setValue("yem_iaaccuracy", yem_iaaccuracy, i);
        }
        model.setValue("yem_iaentitytype", "H", i);//审批实体类型
        model.setValue("yem_iaformid", headKey, i);//审批字段标识
        model.setValue("yem_ianame", title, i);//审批字段名称
        model.setValue("yem_iatype", stype, i);//审批字段类型
    }

    /**
     * 构建子分录
     *
     * @param eField            审批字段标识
     * @param eFieldJson        子分录json
     * @param etitle            审批字段名称
     * @param etype             审批字段类型
     * @param yemSubentryentity 子分录对象
     */
    private static void buildEentry(String eField, JSONObject eFieldJson, String etitle, String etype, DynamicObject yemSubentryentity) {
        yemSubentryentity.set("yem_iaentitytype1", "D");//审批实体类型
        yemSubentryentity.set("yem_iaformid1", eField);//审批字段标识
        yemSubentryentity.set("yem_ianame1", etitle);//审批字段名称
        String etpype1 = getType(etype);
        yemSubentryentity.set("yem_iatype1", etype);//审批字段类型
        if ("numberWidget".equals(etype) || "moneyWidget".equals(etype)) {
            int yem_iaaccuracy = eFieldJson.getIntValue("decimalDigit");//精度
            yemSubentryentity.set("yem_iaaccuracy1", yem_iaaccuracy);
        }
    }

    private static String getType(String type) {
        String stype = "";
        switch (type) {
            case "dateRangeWidget":
                stype = "日期区间";
                break;
            case "departmentSelectWidget":
                stype = "部门选择";
                break;
            case "relatedWidget":
                stype = "关联审批";
                break;
            case "textWidget":
                stype = "单行文本框";
                break;
            case "radioWidget":
                stype = "单选框";
                break;
            case "attachmentWidget":
                stype = "附件";
                break;
            case "arithmeticWidget":
                stype = "运算";
                break;
            case "checkboxWidget":
                stype = "多选框";
                break;
            case "numberWidget":
                stype = "数字";
                break;
            case "describeWidget":
                stype = "说明文字";
                break;
            case "personSelectWidget":
                stype = "人员选择";
                break;
            case "serialNumWidget":
                stype = "流水号";
                break;
            case "dateWidget":
                stype = "申请日期";
                break;
            case "imageWidget":
                stype = "图片";
                break;
            case "moneyWidget":
                stype = "金额";
                break;
            case "textAreaWidget":
                stype = "多行文本框";
                break;
            case "kingGridWidget":
                stype = "政务版发文";
                break;
            default:
                break;
        }
        return stype;
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
//        TextEdit yem_erpfiledformid = this.getView().getControl("yem_erpfiledformid");
//        yem_erpfiledformid.addButtonClickListener(this);
        this.addClickListeners("yem_erpfiledformid", "yem_erpfiledformid1", "yem_parentcontainer");
        MulBasedataEdit mEdit = this.getView().getControl("yem_billtype");
        mEdit.addBeforeF7SelectListener(this);
    }

    @Override
    public void click(EventObject evt) {
        super.click(evt);
        Control c = (Control) evt.getSource();
        String key = c.getKey().toLowerCase();
        if (key.equals("yem_erpfiledformid")) {
//            selectfield();
            openSrcFieldList("yem_erpfiledformid");
        }
        if (key.equals("yem_erpfiledformid1")) {
            openSrcFieldList("yem_erpfiledformid1");
        }
        if (key.equals("yem_parentcontainer")) {
            int row = this.getModel().getEntryCurrentRowIndex("yem_signentryentity");
            Boolean yem_issubentry = (Boolean) this.getModel().getValue("yem_issubentry", row);
            String yem_iaentitytype = (String) this.getModel().getValue("yem_iaentitytype", row);
            if (yem_issubentry && yem_iaentitytype.equals("D")) {
                openSrcFieldList("yem_parentcontainer");
            } else {
                this.getView().showErrorNotification("【是否子单据体】为否或者【审批实体类型】为单据头，禁止选择子单据体标识！");
            }
        }
    }

    /**
     * @MethodName openSrcFieldList
     * @Author SC
     * @Description 打开 单据字段选择
     * @Date 14:36 2023/7/18
     * @Param
     **/
    private void openSrcFieldList(String Tpye) {
        int row = this.getModel().getEntryCurrentRowIndex("mappingentity");
        Object yem_formid = this.getModel().getValue("yem_formid");
        if (yem_formid != null) {
            String targetFieldValue = (String) this.getModel().getValue("yem_ianame", row);
            String xBillId = (String) ((DynamicObject) yem_formid).getPkValue();
            MainEntityType xBillMainType = MetadataServiceHelper.getDataEntityType((String) xBillId);
            IDataEntityProperty targetProperty = xBillMainType.findProperty(targetFieldValue);
            PropTreeBuildOption option = new PropTreeBuildOption(null, targetProperty);
            option.setIncludeParentEntity(true);
            option.setIncludeChildEntity(true);
            option.setIncludePKField(true);
            TreeNode srcBillNode = FormTreeBuilder.buildDynamicPropertyTree((MainEntityType) xBillMainType,
                    (PropTreeBuildOption) option);
            this.showSrcFieldForm(srcBillNode, Tpye);
        } else {
            this.getView().showErrorNotification("ERP对象为空，禁止选择！");
        }

    }

    /**
     * @MethodName showSrcFieldForm
     * @Author SC
     * @Description 打开 源单表单
     * @Date 14:37 2023/7/18
     * @Param [srcBillNode] [kd.bos.entity.tree.TreeNode]
     **/
    private void showSrcFieldForm(TreeNode srcBillNode, String type) {
        FormShowParameter showParameter = new FormShowParameter();
        showParameter.setFormId("botp_selectfield");
        String nodesJson = SerializationUtils.toJsonString((Object) srcBillNode);
        showParameter.getCustomParams().put("treenodes", nodesJson);
        if (type.equals("yem_erpfiledformid")) {
            showParameter.setCloseCallBack(new CloseCallBack((IFormPlugin) this, "sourcefieldcallback"));
        }
        if (type.equals("yem_erpfiledformid1")) {
            showParameter.setCloseCallBack(new CloseCallBack((IFormPlugin) this, "sourcefieldcallback1"));
        }
        if (type.equals("yem_parentcontainer")) {
            showParameter.setCloseCallBack(new CloseCallBack((IFormPlugin) this, "yem_parentcontainer"));
        }
        showParameter.getOpenStyle().setShowType(ShowType.Modal);
        this.getView().showForm(showParameter);
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent e) {
        super.closedCallBack(e);
        String actionId = e.getActionId();
        IDataModel model = this.getModel();
        Object returnData = e.getReturnData();
        DynamicObject dataEntity = this.getModel().getDataEntity(true);
        if (actionId.equals("sourcefieldcallback")) {
            if (returnData != null) {
                String fieldId = returnData.toString();
                int row = this.getModel().getEntryCurrentRowIndex("yem_signentryentity");
                Object srcBill = this.getModel().getValue("yem_formid");
                String srcBillId = (String) ((DynamicObject) srcBill).getPkValue();
                MainEntityType srcbillMainType = MetadataServiceHelper.getDataEntityType((String) srcBillId);
                String fieldCaption = EntityParseHelper.buildPropFullCaption((EntityType) srcbillMainType, (String) fieldId);
//                FormMetadata taskMeta = (FormMetadata) MetadataDao.readRuntimeMeta(MetadataDao.getIdByNumber(srcbillMainType.getName(), MetaCategory.Form), MetaCategory.Form);
//                List<ControlAp<?>> items = taskMeta.getItems();
                Map<String, IDataEntityProperty> fields = srcbillMainType.getAllFields();
                String[] sourceItems = fieldId.split("\\.");
                if (sourceItems.length == 1) {
                    model.setValue("yem_erpfiledformid", fieldId, row);
                    model.setValue("yem_erpfiledformname", fieldCaption, row);
                    model.setValue("yem_erpfiledtype", "entity", row);
                }
                if (fieldId.contains(".id") || fieldId.equals("id")) {
                    model.setValue("yem_erpfiledformid", fieldId, row);
                    model.setValue("yem_erpfiledformname", fieldCaption, row);
                    model.setValue("yem_erpfiledtype", "long", row);
                }
                if (fields.get(fieldId) instanceof BasedataProp) {
                    BasedataProp field = (BasedataProp) fields.get(fieldId);
                    IDataEntityType fieldType = field.getParent();
                    if (fieldType != null) {
                        String name = field.getDisplayName().getLocaleValue_zh_CN();
                        String type = field.getFilterControlType();
                        String dynamicpropertyen = field.getBaseEntityId();
                        model.setValue("yem_erpfiledformid", fieldId, row);
                        model.setValue("yem_erpfiledformname", fieldCaption, row);
                        model.setValue("yem_erpfiledtype", type, row);
                        model.setValue("yem_filedtypename", dynamicpropertyen, row);
                        model.setValue("yem_identifierbasic", "number", row);
                    }
                } else if (fields.get(fieldId) instanceof FieldProp) {
                    FieldProp field = (FieldProp) fields.get(fieldId);
                    IDataEntityType fieldType = field.getParent();
                    if (fieldType != null) {
                        String name = field.getDisplayName().getLocaleValue_zh_CN();
                        String type = field.getFilterControlType();
                        model.setValue("yem_erpfiledformid", fieldId, row);
                        model.setValue("yem_erpfiledformname", fieldCaption, row);
                        model.setValue("yem_erpfiledtype", type, row);
                    }
                } else if (fields.get(fieldId + "_startdate") instanceof DateProp) {
                    DateProp fieldstart = (DateProp) fields.get(fieldId + "_startdate");
                    IDataEntityType fieldTypestart = fieldstart.getParent();
                    if (fieldTypestart != null) {
                        String name = fieldstart.getDisplayName().getLocaleValue_zh_CN();
                        String type = fieldstart.getFilterControlType();
                        model.setValue("yem_erpfiledformid", fieldId + "_startdate", row);
                        model.setValue("yem_erpfiledformname", fieldCaption, row);
                        model.setValue("yem_erpfiledtype", type, row);
                    }
                    DateProp fieldend = (DateProp) fields.get(fieldId + "_enddate");
                    IDataEntityType fieldTypeend = fieldend.getParent();
                    if (fieldTypeend != null) {
                        String name = fieldend.getDisplayName().getLocaleValue_zh_CN();
                        String type = fieldend.getFilterControlType();
                        model.setValue("yem_erpfiledformid", fieldId + "_enddate", row);
                        model.setValue("yem_erpfiledformname", fieldCaption, row);
                        model.setValue("yem_erpfiledtype", type, row);
                    }
                } else if (fields.get(fieldId) instanceof MulBasedataProp) {
                    MulBasedataProp field = (MulBasedataProp) fields.get(fieldId);
                    IDataEntityType fieldType = field.getParent();
                    if (fieldType != null) {
                        String name = field.getDisplayName().getLocaleValue_zh_CN();
                        String type = field.getFilterControlType();
                        model.setValue("yem_erpfiledformid", fieldId, row);
                        model.setValue("yem_erpfiledformname", fieldCaption, row);
                        model.setValue("yem_erpfiledtype", type, row);
                    }
                }
            }
        }
        if (actionId.equals("sourcefieldcallback1")) {
            if (returnData != null) {
                String fieldId = returnData.toString();
                int row = this.getModel().getEntryCurrentRowIndex("yem_subentryentity");
                Object srcBill = this.getModel().getValue("yem_formid");
                String srcBillId = (String) ((DynamicObject) srcBill).getPkValue();
                MainEntityType srcbillMainType = MetadataServiceHelper.getDataEntityType((String) srcBillId);
                Map<String, IDataEntityProperty> fell = srcbillMainType.getAllFields();
                String fieldCaption = EntityParseHelper.buildPropFullCaption((EntityType) srcbillMainType, (String) fieldId);
                String[] sourceItems = fieldCaption.split("\\.");
                if (sourceItems.length > 3) {
                    return;
                }
                Map<String, IDataEntityProperty> fields = srcbillMainType.getAllFields();
                //判断是字段集合
                if (fields.get(fieldId) != null) {
                    IDataEntityType fieldTypes = fields.get(fieldId).getParent();
                    if (fieldTypes instanceof BillEntityType) {//单据头
                        model.setValue("yem_erpentitytype1", "H", row);
                    }
                    if (fieldTypes instanceof EntryType) {//单据体
                        model.setValue("yem_erpentitytype1", "D", row);
                    }
                    if (fieldTypes instanceof SubEntryType) {//子单据体
                        model.setValue("yem_erpentitytype1", "S", row);
                    }
                }
                if (fieldId.contains(".id") || fieldId.equals("id")) {
                    model.setValue("yem_erpfiledformid1", fieldId, row);
                    model.setValue("yem_erpfiledformname1", fieldCaption, row);
                    model.setValue("yem_erpfiledtype1", "long", row);
                }
                if (fields.get(fieldId) instanceof BasedataProp) {
                    BasedataProp field = (BasedataProp) fields.get(fieldId);
                    IDataEntityType fieldType = field.getParent();
                    if (fieldType != null) {
                        String name = field.getDisplayName().getLocaleValue_zh_CN();
                        String type = field.getFilterControlType();
                        String dynamicpropertyen = field.getBaseEntityId();
                        model.setValue("yem_erpfiledformid1", fieldId, row);
                        model.setValue("yem_erpfiledformname1", name, row);
                        model.setValue("yem_erpfiledtype1", type, row);
                        model.setValue("yem_filedtypename1", dynamicpropertyen, row);
                        model.setValue("yem_identifierbasic1", "number", row);
                    }
                } else if (fields.get(fieldId) instanceof FieldProp) {
                    FieldProp field = (FieldProp) fields.get(fieldId);
                    IDataEntityType fieldType = field.getParent();
                    if (fieldType != null) {
                        String name = field.getDisplayName().getLocaleValue_zh_CN();
                        String type = field.getFilterControlType();
                        model.setValue("yem_erpfiledformid1", fieldId, row);
                        model.setValue("yem_erpfiledformname1", name, row);
                        model.setValue("yem_erpfiledtype1", type, row);
                    }
                } else if (fields.get(fieldId + "_startdate") instanceof DateProp) {
                    DateProp fieldstart = (DateProp) fields.get(fieldId + "_startdate");
                    IDataEntityType fieldTypestart = fieldstart.getParent();
                    if (fieldTypestart != null) {
                        String name = fieldstart.getDisplayName().getLocaleValue_zh_CN();
                        String type = fieldstart.getFilterControlType();
                        model.setValue("yem_erpfiledformid1", fieldId + "_startdate", row);
                        model.setValue("yem_erpfiledformname1", name, row);
                        model.setValue("yem_erpfiledtype1", type, row);
                    }
                    DateProp fieldend = (DateProp) fields.get(fieldId + "_enddate");
                    IDataEntityType fieldTypeend = fieldend.getParent();
                    if (fieldTypeend != null) {
                        String name = fieldend.getDisplayName().getLocaleValue_zh_CN();
                        String type = fieldend.getFilterControlType();
                        model.setValue("yem_erpfiledformid1", fieldId + "_enddate", row);
                        model.setValue("yem_erpfiledformname1", name, row);
                        model.setValue("yem_erpfiledtype1", type, row);
                    }
                } else if (fields.get(fieldId) instanceof MulBasedataProp) {
                    MulBasedataProp field = (MulBasedataProp) fields.get(fieldId);
                    IDataEntityType fieldType = field.getParent();
                    if (fieldType != null) {
                        String name = field.getDisplayName().getLocaleValue_zh_CN();
                        String type = field.getFilterControlType();
                        model.setValue("yem_erpfiledformid1", fieldId, row);
                        model.setValue("yem_erpfiledformname1", name, row);
                        model.setValue("yem_erpfiledtype1", type, row);
                    }
                }
            }
        }

        if (actionId.equals("yem_parentcontainer")) {
            if (returnData != null) {
                String fieldId = returnData.toString();
                int row = this.getModel().getEntryCurrentRowIndex("yem_signentryentity");
                Object srcBill = this.getModel().getValue("yem_formid");
                String srcBillId = (String) ((DynamicObject) srcBill).getPkValue();
                MainEntityType srcbillMainType = MetadataServiceHelper.getDataEntityType((String) srcBillId);
                String fieldCaption = EntityParseHelper.buildPropFullCaption((EntityType) srcbillMainType, (String) fieldId);
                FormMetadata taskMeta = (FormMetadata) MetadataDao.readRuntimeMeta(MetadataDao.getIdByNumber(srcbillMainType.getName(), MetaCategory.Form), MetaCategory.Form);
                List<ControlAp<?>> items = taskMeta.getItems();
                Map<String, IDataEntityProperty> fields = srcbillMainType.getAllFields();
                String[] sourceItems = fieldId.split("\\.");
                if (sourceItems.length == 1) {
                    model.setValue("yem_parentcontainer", fieldId, row);
                    model.setValue("yem_parentname", fieldCaption, row);
//                    model.setValue("yem_erpfiledtype", "entity", row);
                }
            }
        }
    }

    public static String getEntityKeyWithLang(String langName, MainEntityType dt, String fieldKey) {
        String[] splitKey = fieldKey.split("\\.");
        StringBuilder builder = new StringBuilder();

        for (int i = 0; i < splitKey.length; ++i) {
            String curSplitKey = splitKey[i];
            String name = curSplitKey;
            if (builder.length() != 0) {
                builder.append('.');
            }

            IDataEntityProperty property = dt.findProperty(curSplitKey);
            if (property == null && i > 0) {
                IDataEntityProperty preProperty = dt.findProperty(splitKey[i - 1]);
                if (preProperty instanceof BasedataProp) {
                    BasedataProp prop = (BasedataProp) preProperty;
                    MainEntityType baseDt = EntityMetadataCache.getDataEntityType(prop.getBaseEntityId());
                    IDataEntityProperty baseProperty = baseDt.findProperty(curSplitKey);
                    name = (String) baseProperty.getDisplayName().get(langName);
                }
            } else if (property != null) {
                name = (String) property.getDisplayName().get(langName);
            }

            builder.append(name);
        }

        return builder.toString();
    }

    @Override
    public void beforeF7Select(BeforeF7SelectEvent e) {
        String key = e.getProperty().getName();
        DynamicObject bill = this.getModel().getDataEntity(true);
        ListShowParameter ListshowParameter = (ListShowParameter) e.getFormShowParameter();
        if (key.equals("yem_billtype")) {
            DynamicObject yemFormid = bill.getDynamicObject("yem_formid");
            if (yemFormid != null) {
                QFilter q1 = new QFilter("billformid.number", QFilter.in, yemFormid.getString("number"));
                ListshowParameter.getListFilterParameter().setFilter(q1);
            } else {
                this.getView().showErrorNotification("未选择【ERP业务对象】，禁止选择单据类型！");
                e.setCancel(true);
            }
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        IDataModel model = this.getModel();
        String name = e.getProperty().getName();
        ChangeData changeData = e.getChangeSet()[0];
        Object newValue = changeData.getNewValue();
        Object oldValue = changeData.getOldValue();
        int rowIndex = changeData.getRowIndex();
        DynamicObject bill = model.getDataEntity(true);
        if ("yem_billtype".equals(name)) {
            List list = new ArrayList<>();
            DynamicObjectCollection yem_billtype = bill.getDynamicObjectCollection("yem_billtype");
            if (yem_billtype.size() > 0) {
                for (int i = 0; i < yem_billtype.size(); i++) {
                    DynamicObject dynamicObject = yem_billtype.get(i);
                    DynamicObject fbasedataid = dynamicObject.getDynamicObject("fbasedataid");
                    list.add(fbasedataid.getString("id"));
                }
            }
            if (list.size() > 0) {
                model.setValue("yem_billtypetext", String.join("、", list));
            }
            setisvmi();
        }
        if ("yem_formid".equals(name)) {
            if (oldValue != null && newValue != null) {
                String oldnumber = ((DynamicObject) oldValue).getString("number");
                String newnumber = ((DynamicObject) newValue).getString("number");
                if (!oldnumber.equals(newnumber)) {
                    model.setValue("yem_billtype", null);
                    model.setValue("yem_billtypetext", null);
                    model.setValue("yem_isvmi", null);
                    model.setValue("yem_yzjid", null);
                }
            }
            salesordertype();
        }
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        setisvmi();
        salesordertype();
    }

    /**
     * 设置仓库可见性
     */
    public void setisvmi() {
        Boolean fag = false;
        IDataModel model = this.getModel();
        DynamicObject bill = model.getDataEntity(true);
        DynamicObjectCollection yem_billtype = bill.getDynamicObjectCollection("yem_billtype");
        if (yem_billtype.size() > 0) {
            for (int i = 0; i < yem_billtype.size(); i++) {
                DynamicObject dynamicObject = yem_billtype.get(i);
                DynamicObject fbasedataid = dynamicObject.getDynamicObject("fbasedataid");
                String number = fbasedataid.getString("number");
                if ("yem_orderproreqbill_DB".equals(number)) {
                    fag = true;
                }
            }
        }
        if (fag) {
            this.getView().setVisible(true, "yem_isvmi");
        } else {
            this.getView().setVisible(false, "yem_isvmi");
        }
    }

    /**
     * 设置类型可见性
     */
    public void salesordertype() {
        IDataModel model = this.getModel();
        DynamicObject bill = model.getDataEntity(true);
        DynamicObject yem_formid = bill.getDynamicObject("yem_formid");
        if (yem_formid != null) {
            String number = yem_formid.getString("number");
            if ("yem_es_contactbook".equals(number)) {
                this.getView().setVisible(true, "yem_procbilltype");
                this.getView().setVisible(false, "yem_salesordertype");
            } else if ("yem_placeexamine".equals(number)) {//下单审批
                this.getView().setVisible(false, "yem_procbilltype");
                this.getView().setVisible(true, "yem_salesordertype");
            } else {
                this.getView().setVisible(false, "yem_procbilltype");
                this.getView().setVisible(false, "yem_salesordertype");
            }
        } else {
            this.getView().setVisible(false, "yem_procbilltype");
            this.getView().setVisible(false, "yem_salesordertype");
        }
    }
}
