package cc.smtweb.system.bpm.web.design.form.define;

import cc.smtweb.framework.core.common.SwEnum;
import cc.smtweb.framework.core.db.cache.ModelTableCache;
import cc.smtweb.framework.core.db.vo.ModelField;
import cc.smtweb.framework.core.db.vo.ModelTable;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * Created by Akmm at 2022/4/18 14:20
 * 数据集定义
 */
public class PageDataset {
    //唯一标识
    public String id;
    //名称
    public String name;
    //中文名
    public String label;
    //类别：list-列表；form-表单；editList-编辑列表;tree
    public String type;
    //主表
    public long masterTable;
    public String masterTable_text;
    //id字段 对应field的name
    public String idField;
    //list的自定义sql，仅列表支持，select fields from tables [condition] group by xxx order by xxx
    public String sql;
    //固定条件，如f1='a' and f2=:p1
    public String fixedCond;
    //是否懒加载
    public boolean lazy;
    //是否可编辑
    public boolean canEdit;
    //是否虚拟数据集
    public boolean virtual;
    //关联大字段信息
    public PageDatasetLinkClob linkClob;
    //select的字段
    public List<PageDatasetField> fields;
    public List<PageDatasetFilter> filters;
    public List<PageDatasetEnumData> data;
    public PageDatasetDynCond dynCond;
    public List<PageDatasetSortField> sortFields;

    //按字段名的缓存
    private Map<String, PageDatasetField> mapFieldName;
    private Map<String, PageDatasetFilter> mapFilterName;
    //按字段Id的缓存
    private Map<String, PageDatasetField> mapFieldId;
    private Map<String, PageDatasetFilter> mapFilterId;

    //依赖的数据集
    private Set<String> linkDs = new HashSet<>();
    private boolean calcField = false;

    public PageDatasetField findFieldByName(String name) {
        if (mapFieldName == null) resetFields();
        return mapFieldName.get(name);
    }

    public PageDatasetFilter findFilterByName(String name) {
        if (mapFilterName == null) resetFields();
        return mapFilterName.get(name);
    }

    public PageDatasetField findFieldById(String id) {
        if (mapFieldId == null) resetFields();
        return mapFieldId.get(id);
    }

    public PageDatasetFilter findFilterById(String id) {
        if (mapFilterId == null) resetFields();
        return mapFilterId.get(id);
    }


    public ModelTable _getModelTable() {
        return ModelTableCache.getInstance().get(masterTable);
    }

    public boolean _isCurDataSet(String dataset) {
        return this.name.equals(dataset);
    }

    /**
     * 重置丰富字段信息
     */
    public void resetFields() {
        mapFieldName = new HashMap<>();
        mapFieldId = new HashMap<>();
        linkDs.clear();
        resetFields(mapFieldName, mapFieldId, fields, false);
        mapFilterName = new HashMap<>();
        mapFilterId = new HashMap<>();
        resetFields(mapFilterName, mapFilterId, filters, true);
    }

    private <T extends BaseDatasetField> void resetFields(Map<String, T> mapName, Map<String, T> mapId, List<T> list, boolean isFilter) {
        ModelTableCache cache = ModelTableCache.getInstance();
        ModelTable table = null;
        for (T field : list) {
            mapName.put(field.name, field);
            mapId.put(field.id, field);
            if (field.table <= 0 || StringUtils.isEmpty(field.field)) continue;
            if (table == null || table.getId() != field.table) {
                table = cache.get(field.table);
            }
            if (table == null) continue;
            ModelField mf = table.findField(field.field);
//            if (mf == null) throw new BizException("未找到表字段的定义信息（" + table.getName() + "." + field.field + "）");
            field.table_text = table.getTitle();
            if (mf != null) {
                field.fieldType = mf.getFieldType();
                field.notNull = mf.getNotNull();
                field.link = mf.getLink();

                if (StringUtils.isEmpty(field.label)) field.label = mf.getTitle();
                if (StringUtils.isEmpty(field.dataType)) field.dataType = mf.getDataType();
                if (StringUtils.isEmpty(field.remark)) field.remark = mf.getRemark();
                if (StringUtils.isEmpty(field.editor)) field.editor = mf.getEditor();
            }
            //过滤条件，需要建立依赖关系
            if (isFilter) {
                PageDatasetFilter filter = (PageDatasetFilter) field;
                if (StringUtils.isNotEmpty(filter.linkDb)) linkDs.add(filter.linkDb);

                if (StringUtils.isEmpty(filter.sqlName)) {
                    filter.sqlName = filter.field;
                }
            } else {
                calcField = calcField || ((PageDatasetField) field).fieldIsCalc();
            }
        }
    }

    public PageDatasetFilter findFilterByDs(String dsName) {
        for (PageDatasetFilter filter : filters) {
            if (SwEnum.FilterType.LINK.value.equals(filter.type) && dsName.equals(filter.linkDb)) {
                return filter;
            }
        }
        return null;
    }

    //是否依赖指定数据集
    public boolean hasDepends(String dsName) {
        return linkDs.contains(dsName);
    }

    //是否有计算字段
    public boolean hasCalcField() {
        return calcField;
    }
}
