package yem.base.common.module.meta.propselect.helper;

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.dynamicobject.DynamicProperty;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.property.BasedataProp;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.ShowType;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.plugin.AbstractFormPlugin;
import yem.base.common.utils.YEM;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * 字段选择帮助类
 *
 * @author longh
 * @description:
 * @date 2022年6月30日 上午10:11:18
 */
public class MetaPropertyHelper {
    private static final String KEY_FORM = "yem_base_metaproperty";

    /**
     * 弹出字段选择器
     *
     * @param plugin
     * @param actionId CloseCallBack - actionId
     * @param formKey  表单实体标识
     * @param isMulti  是否多选
     */
    public static void showPropertySelect(AbstractFormPlugin plugin, String actionId, String formKey, boolean isMulti) {
        showPropertySelect(plugin, actionId, formKey, isMulti, null);
    }

    /**
     * 弹出字段选择器
     *
     * @param plugin
     * @param actionId   CloseCallBack - actionId
     * @param formKey    表单实体标识
     * @param isMulti    是否多选
     * @param entityKeys 子实体标识
     */
    public static void showPropertySelect(AbstractFormPlugin plugin, String actionId, String formKey, boolean isMulti, Collection<String> entityKeys) {
        FormShowParameter fsp = new FormShowParameter();
        fsp.getOpenStyle().setShowType(ShowType.Modal);
        fsp.setFormId(KEY_FORM);
        fsp.setCustomParam("entityKey", formKey);
        fsp.setCustomParam("alone", entityKeys != null && entityKeys.size() > 0);
        fsp.setCustomParam("showKeys", entityKeys);
        fsp.setCustomParam("isMulti", isMulti);
        fsp.setCloseCallBack(new CloseCallBack(plugin, actionId));
        plugin.getView().showForm(fsp);
    }

    /**
     * 根据选择器结果回填单据体字段信息
     *
     * @param model
     * @param e
     * @param entryKey   单据体Key
     * @param colNo      记录全编码字段Key
     * @param col        记录全名称字段Key
     * @param ableExsist 是否可重复
     */
    public static void callBackEntryData(IDataModel model, ClosedCallBackEvent e, String entryKey, String colNo, String col, boolean ableExsist) {
        DynamicObjectCollection data = (DynamicObjectCollection) e.getReturnData();
        if (YEM.isNotEmpty(data)) {
            Set<String> exsistCols = new HashSet<>();
            for (DynamicObject row : model.getEntryEntity(entryKey)) {
                exsistCols.add(row.getString(colNo));
            }
            for (int i = 0; i < data.size(); ++i) {
                DynamicObject info = data.get(i);
                String fullnumber = info.getString("yem_fullnumber");
                String fullname = info.getString("yem_fullname");
                if (ableExsist || !exsistCols.contains(fullnumber)) {
                    int index;
                    if (i == 0) {
                        index = model.getEntryCurrentRowIndex(entryKey);
                    } else {
                        index = model.createNewEntryRow(entryKey);
                    }
                    model.setValue(colNo, fullnumber, index);
                    model.setValue(col, fullname, index);
                }
            }
        }
    }

    public static void callBackEntryDataSample(IDataModel model, ClosedCallBackEvent e, String entryKey, String colNo, String col, boolean ableExsist) {
        DynamicObjectCollection data = (DynamicObjectCollection) e.getReturnData();
        if (YEM.isNotEmpty(data)) {
            Set<String> exsistCols = new HashSet<>();
            for (DynamicObject row : model.getEntryEntity(entryKey)) {
                exsistCols.add(row.getString(colNo));
            }
            for (int i = 0; i < data.size(); ++i) {
                DynamicObject info = data.get(i);
                String fullnumber = info.getString("yem_number");
                String fullname = info.getString("yem_name");
                if (ableExsist || !exsistCols.contains(fullnumber)) {
                    int index;
                    if (i == 0) {
                        index = model.getEntryCurrentRowIndex(entryKey);
                    } else {
                        index = model.createNewEntryRow(entryKey);
                    }
                    model.setValue(colNo, fullnumber, index);
                    model.setValue(col, fullname, index);
                }
            }
        }
    }

    /**
     * 根据选择器结果回填表头字段信息
     *
     * @param model
     * @param e
     * @param colNo 记录全编码字段Key
     * @param col   记录全名称字段Key
     */
    public static void callBackBillData(IDataModel model, ClosedCallBackEvent e, String colNo, String col) {
        DynamicObjectCollection data = (DynamicObjectCollection) e.getReturnData();
        if (YEM.isNotEmpty(data)) {
            for (DynamicObject info : data) {
                String fullnumber = info.getString("yem_fullnumber");
                String fullname = info.getString("yem_fullname");
                model.setValue(colNo, fullnumber);
                model.setValue(col, fullname);
                break;
            }
        }
    }

    public static void callBackEntryData(IDataModel model, ClosedCallBackEvent e, String entryKey, String subEntryKey, String colNo, String col, boolean ableExsist) {
        DynamicObjectCollection data = (DynamicObjectCollection) e.getReturnData();
        if (YEM.isNotEmpty(data)) {
            Set<String> exsistCols = new HashSet<>();
            for (DynamicObject row : model.getEntryEntity(entryKey)) {
                DynamicObjectCollection subEntry = row.getDynamicObjectCollection(subEntryKey);
                for (DynamicObject subRow : subEntry) {
                    exsistCols.add(subRow.getString(colNo));
                }
            }
            int entryCurrentRowIndex = model.getEntryCurrentRowIndex(entryKey);
            for (int i = 0; i < data.size(); ++i) {
                DynamicObject info = data.get(i);
                String fullnumber = info.getString("yem_fullnumber");
                String fullname = info.getString("yem_fullname");
                if (ableExsist || !exsistCols.contains(fullnumber)) {
                    int index;
                    if (i == 0) {
                        index = model.getEntryCurrentRowIndex(subEntryKey);
                    } else {
                        index = model.createNewEntryRow(subEntryKey);
                    }
                    model.setValue(colNo, fullnumber, index, entryCurrentRowIndex);
                    model.setValue(col, fullname, index, entryCurrentRowIndex);
                }
            }
        }
    }

    public static void callBackEntryDataSample(IDataModel model, ClosedCallBackEvent e, String entryKey, String subEntryKey, String colNo, String col, boolean ableExsist) {
        DynamicObjectCollection data = (DynamicObjectCollection) e.getReturnData();
        if (YEM.isNotEmpty(data)) {
            Set<String> exsistCols = new HashSet<>();
            for (DynamicObject row : model.getEntryEntity(entryKey)) {
                DynamicObjectCollection subEntry = row.getDynamicObjectCollection(subEntryKey);
                for (DynamicObject subRow : subEntry) {
                    exsistCols.add(subRow.getString(colNo));
                }
            }
            int entryCurrentRowIndex = model.getEntryCurrentRowIndex(entryKey);
            for (int i = 0; i < data.size(); ++i) {
                DynamicObject info = data.get(i);
                String fullnumber = info.getString("yem_number");
                String fullname = info.getString("yem_name");
                if (ableExsist || !exsistCols.contains(fullnumber)) {
                    int index;
                    if (i == 0) {
                        index = model.getEntryCurrentRowIndex(subEntryKey);
                    } else {
                        index = model.createNewEntryRow(subEntryKey);
                    }
                    model.setValue(colNo, fullnumber, index, entryCurrentRowIndex);
                    model.setValue(col, fullname, index, entryCurrentRowIndex);
                }
            }
        }
    }

    /**
     * 获取当前语言环境单据字段名称
     *
     * @param entityName
     * @param fieldKey
     * @return
     */
    public static String getEntityLangName(String entityName, String fieldKey) {
        String langName = RequestContext.get().getLang().name();
        MainEntityType dt = EntityMetadataCache.getDataEntityType(entityName);
        return getEntityLangName(langName, dt, fieldKey);
    }

    /**
     * 获取指定语言环境单据字段名称
     *
     * @param langName
     * @param dt
     * @param fieldKey
     * @return
     */
    public static String getEntityLangName(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 = baseProperty.getDisplayName() != null ? baseProperty.getDisplayName().get(langName) : "id".equals(baseProperty.getName()) ? "ID" : "";
                }
            } else if (property != null) {
                name = property.getDisplayName() != null ? property.getDisplayName().get(langName) : "id".equals(property.getName()) ? "ID" : "";
            }
            builder.append(name);
        }

        return builder.toString();
    }

    /**
     * 获取并检查F7字段值，用于获取依赖的F7字段并检查是否存在及录入
     *
     * @param view
     * @param colName
     * @return
     */
    public static DynamicObject getAndCheckF7Value(IFormView view, String colName) {
        IDataModel model = view.getModel();
        DynamicObject value = model.getDataEntity().getDynamicObject(colName);
        if (value == null) {
            MainEntityType type = model.getDataEntityType();
            DynamicProperty pro = type.getProperty(colName);
            String msg = pro == null ? String.format("字段【%s】不存在。", new Object[]{colName}) : String.format("请先选择【%s】。", new Object[]{pro.getDisplayName()});
            view.showTipNotification(msg);
        }

        return value;
    }

    /**
     * 获取并检查F7字段值，用于获取依赖的F7字段并检查是否存在及录入
     *
     * @param view
     * @param colName
     * @return
     */
    public static DynamicObject getAndCheckF7Value(IFormView view, String entryKey, String colName) {
        IDataModel model = view.getModel();
        int index = model.getEntryCurrentRowIndex(entryKey);
        DynamicObject value = (DynamicObject) model.getValue(colName, index);
        if (value == null) {
            MainEntityType type = model.getDataEntityType();
            DynamicProperty pro = type.getProperty(colName);
            String msg = pro == null ? String.format("字段【%s】不存在。", new Object[]{colName}) : String.format("请先选择【%s】。", new Object[]{pro.getDisplayName()});
            view.showTipNotification(msg);
        }

        return value;
    }

}