import {
    defineStore
} from 'pinia';
import {
    reactive,
    ref,
} from 'vue'
import {
    createRequest
} from "../utils/request";

//  静态树 O(1) 超快查询！！！！！
let IndustryMap = null
//  构建索引
function buildIndex(tree) {
    const map = new Map();

    function traverse(nodes) {
        for (const node of nodes) {
            map.set(node.id, node);
            if (node.children && node.children.length) {
                traverse(node.children);
            }
        }
    }
    traverse(tree);
    return map;
}
const useDictStore = defineStore("dict", () => {
    // 定义状态
    const complete = ref(false)
    const dictLoading = ref(false)
    const state = reactive({
        education: [],
        experience: [],
        area: [],
        scale: [],
        isPublish: [],
        sex: [],
        affiliation: [],
        industry: [],
        nature: [],
        noticeType: []
    })
    // political_affiliation
    const getDictData = async (dictType, dictName) => {
        if (dictType && dictName) {
            return getDictSelectOption(dictType).then((data) => {
                state[dictName] = data
                return data
            })
        }
        if (complete.value) return
        if (dictLoading.value) return
        dictLoading.value = true
        try {
            const [education, experience, area, scale, sex, affiliation, nature, noticeType] = 
            await Promise.all([
                getDictSelectOption('education'),
                getDictSelectOption('experience'),
                getDictSelectOption('area', true),
                getDictSelectOption('scale'),
                getDictSelectOption('app_sex'),
                getDictSelectOption('political_affiliation'),
                getDictSelectOption('company_nature'),
                getDictSelectOption('sys_notice_type'),
            ]);

            state.education = education;
            state.experience = experience;
            state.area = area;
            state.scale = scale;
            state.sex = sex;
            state.affiliation = affiliation;
            state.nature = nature
            state.noticeType = noticeType
            complete.value = true
            getIndustryDict() // 获取行业
        } catch (error) {
            console.error('Error fetching dictionary data:', error);
            // 确保即使出错也能返回空数组
            state.education = [];
            state.experience = [];
            state.area = [];
            state.scale = [];
            state.sex = [];
            state.affiliation = [];
            state.nature = [];
            state.noticeType = [];
        } finally {
            dictLoading.value = false
        }
    };

    async function getIndustryDict() {
        if (state.industry.length) return
        const resp = await createRequest(`/app/common/industry/treeselect`);
        if (resp.code === 200 && resp.data) {
            state.industry = resp.data
            IndustryMap = buildIndex(resp.data);
        }
        return [];
    }

    function industryLabel(dictType, value) {
        switch (dictType) {
            case 'industry':
                if (!IndustryMap) return
                const data = IndustryMap.get(Number(value))?.label || ''
                return data
        }
        return null
    }

    function dictLabel(dictType, value) {
        if (state[dictType] && Array.isArray(state[dictType])) {
            for (let i = 0; i < state[dictType].length; i++) {
                let element = state[dictType][i];
                if (String(element.value) === String(value)) {
                    return element.label
                }
            }
        }
        return ''
    }

    function oneDictData(dictType, value) {
        if (!value) {
            return state[dictType]
        }
        if (state[dictType]) {
            for (let i = 0; i < state[dictType].length; i++) {
                let element = state[dictType][i];
                if (element.value === value) {
                    return element
                }
            }
        }
        return null
    }

    function getTransformChildren(dictType, title = '', key = '') {
        if (dictType) {
            return {
                label: title,
                key: key || dictType,
                options: state[dictType] || [],
            }
        }
        return null
    }


    async function getDictSelectOption(dictType, isDigital) {
        const resp = await createRequest(`/app/common/dict/${dictType}`);
        if (resp.code === 200 && resp.data) {
            const options = resp.data.map((item) => {
                return {
                    text: item.dictLabel,
                    label: item.dictLabel,
                    value: isDigital ? Number(item.dictValue) : item.dictValue,
                    key: item.dictCode,
                    listClass: item.listClass,
                    status: item.listClass,
                };
            });
            return options;
        }
        return [];
    }

    async function getDictValueEnum(dictType, isDigital) {
        const resp = await createRequest(`/app/common/dict/${dictType}`);
        if (resp.code === 200 && resp.data) {
            const opts = {};
            resp.data.forEach((item) => {
                opts[item.dictValue] = {
                    text: item.dictLabel,
                    label: item.dictLabel,
                    value: isDigital ? Number(item.dictValue) : item.dictValue,
                    key: item.dictCode,
                    listClass: item.listClass,
                    status: item.listClass,
                };
            });
            return opts;
        } else {
            return {};
        }
    }

    // 导入
    return {
        state,
        getDictData,
        dictLabel,
        oneDictData,
        complete,
        getDictSelectOption,
        getTransformChildren,
        industryLabel
    }
})

export default useDictStore;