import SysDictDataController from '@/services/apis/SysDictDataController';
import { useRequest } from 'ahooks';

type DictTypeCode =
    | 'common_status'
    | 'vis_type'
    | 'menu_type'
    | 'menu_open_type'
    | 'data_scope_type'
    | 'student_status'
    | 'education_stage'
    | 'semester_type'
    | 'exam_status'
    | 'exam_period_type'
    | 'exam_type'
    | 'exam_sample_type'
    | 'publish_status'
    | 'org_type'
    | 'org_fund_source'
    | 'urban_rural_type'
    | 'data_publish_type'
    | 'data_report_type'
    | 'data_report_status'
    | 'gender'
    | 'school_job_title'
    | 'certificate_type'
    | 'data_import_mode'
    | 'audit_status'
    | 'audit_action_type'
    | 'exam_sample_status'
    | 'exam_score_range_type'
    | 'question_catalog'
    | 'cognitive_ability'
    ;

/**
 * 字典
 */
export default () => {
    const { data: list, loading } = useRequest<API.SysDictDataOutput[], any>(async () => {
        try {
            const res = await SysDictDataController.getAllList();
            return res ?? [];
        } catch {
            return [];
        }
    });

    const getDict = (code: DictTypeCode) => list?.filter((t) => t.sysDictType?.code === code)?.sort((a, b) => a.sort - b.sort) ?? [];

    const getDictValueEnum = (code: DictTypeCode, includeStatus: boolean = false, excludeValues?: number[]) => {
        let valueEnum: Record<number, { text: string, status?: string, value?: number }> = {};
        getDict(code)?.filter(t => !excludeValues || !excludeValues.includes(t.value))?.forEach(t => {
            let v: { text: string; status?: string, value?: number } = { text: t.name ?? '' };
            if (includeStatus) {
                v = {
                    ...v,
                    value: t.value,
                    status: t.antStatus || 'default'
                };
            }
            valueEnum[t.value] = v;
        });
        return valueEnum;
    };

    const getDictOptions = (code: DictTypeCode) => {
        return getDict(code)?.sort((a, b) => a.sort - b.sort)?.map((t) => ({
            key: t.id,
            value: t.value,
            label: t.name,
        }));
    };

    const getKeyDict = (code: DictTypeCode) => {
        const ds = getDict(code);
        let dict: Record<number, API.SysDictDataOutput> = {};
        ds.forEach(t => {
            dict[t.value] = t;
        });
        return dict;
    };

    return {
        /** 所有数据字典 */
        list,
        /** 获取单个字典 */
        getDict,
        /** 获取单个字典 ValueEnum 类型数据 */
        getDictValueEnum,
        /** 获取单个字典 Option 类型数据列表 */
        getDictOptions,
        /** 获取单个字典键值数据 */
        getKeyDict,
        /** 加载状态 */
        loading,
    };
};
