package com.yem.em.utils;


import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.db.DB;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.MainEntityType;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

/**
 * @author 夜子
 * @ClassName BaseDataFilterUtils
 * @description: 基础资料列表分组帮助类
 * @date 2023年07月11日
 * @version: 1.0
 */
public class BaseDataFilterUtils {

    public static QFilter getBaseDataFilter(String entityID, Long orgID) {
        QFilter baseDataIdsFilter;
        if (!checkBaseDataCtrl(entityID)) {
            return null;
        } else {
            MainEntityType dt = EntityMetadataCache.getDataEntityType(entityID);
            String baseDataTableName = dt.getAlias();
            String bsaeDataUseRangeTableName = baseDataTableName + "_U";
            String useRangeAliasName1 = "ur" + DB.genLongId("ur");
            baseDataIdsFilter = QFilter.joinSQL(entityID,
                    "inner join " + bsaeDataUseRangeTableName + " " + useRangeAliasName1 + " on " + useRangeAliasName1
                            + ".fdataid = " + entityID + ".fid and " + useRangeAliasName1 + ".fuseorgid=" + orgID,
                    new Object[0]);
            return baseDataIdsFilter;
        }
    }

    public static Boolean checkBaseDataCtrl(String entityID) {
        Boolean isCtrl;
        DynamicObject defaultCtrlStrtgy = getDefaultCtrlStrtgy(entityID);
        if (defaultCtrlStrtgy == null) {
            isCtrl = Boolean.FALSE;
        } else {
            MainEntityType dt = EntityMetadataCache.getDataEntityType(entityID);
            if (dt.getProperty("ctrlstrategy") != null) {
                isCtrl = Boolean.TRUE;
            } else {
                isCtrl = Boolean.FALSE;
            }

        }
        return isCtrl;
    }

    public static DynamicObject getDefaultCtrlStrtgy(String entityID) {
        DynamicObject defaultCtrlStrtgy;
        String selectFields = "id,defaultctrlstrategy";
        QFilter basedataFilter = new QFilter("basedataid", "=", entityID);
        QFilter[] filters = new QFilter[] { basedataFilter };
        defaultCtrlStrtgy = BusinessDataServiceHelper.loadSingleFromCache("bd_bddefctrlstrtgy", selectFields, filters);
        return defaultCtrlStrtgy;
    }



}
