import { ref } from 'vue'
import { GetProjectInfoList, GetSectionList, GetLaborTeamPageList, GetWorkerGroupPageList } from '@/api/common/index'

const commonParams = {
    Skip: 0,
    Take: 1000,
    RequireTotalCount: true,
    Sort: JSON.stringify([{ Selector: "CreateTime", Desc: true }]),
    Filter: JSON.stringify(["IsDeleted", "=", false])
}

const CACHE_KEYS = {
    PROJECTS: 'cached_projects',
    SECTIONS: 'cached_sections',
    LABOR_TEAMS: 'cached_labor_teams',
    WORKER_GROUPS: 'cached_worker_groups',
    LAST_CACHE_TIME: 'last_cache_time'
}

const CACHE_DURATION = 5 * 60 * 1000

export const useCascadeSelect = (fetchOptions) => {
    const projectState = ref('')
    const projectListAll = ref([])
    const projectList = ref([])

    const sectionListAll = ref([])
    const sectionState = ref('')
    const sectionList = ref([])

    const laborTeamListAll = ref([])
    const laborTeamState = ref('')
    const laborTeamList = ref([])

    const teamsGroupsState = ref('')
    const teamsGroupsList = ref([])
    const teamsGroupsListAll = ref([])

    const isCacheValid = (cacheKey) => {
        const lastCacheTime = sessionStorage.getItem(CACHE_KEYS.LAST_CACHE_TIME)
        if (!lastCacheTime) return false

        const cachedData = sessionStorage.getItem(cacheKey)
        return cachedData &&
            (Date.now() - parseInt(lastCacheTime)) < CACHE_DURATION
    }

    const getFromCache = (cacheKey) => {
        const cachedData = sessionStorage.getItem(cacheKey)
        return cachedData ? JSON.parse(cachedData) : null
    }

    const saveToCache = (cacheKey, data) => {
        sessionStorage.setItem(cacheKey, JSON.stringify(data))
        sessionStorage.setItem(CACHE_KEYS.LAST_CACHE_TIME, Date.now().toString())
    }

    const fetchData = async (apiFunc, refValue, cacheKey) => {
        try {
            if (isCacheValid(cacheKey)) {
                const cachedData = getFromCache(cacheKey)
                if (cachedData) {
                    refValue.value = cachedData
                    return
                }
            }

            const res = await apiFunc(commonParams)
            if (res.StatusCode === 200) {
                const FIELD_FILTERS = {
                    [CACHE_KEYS.PROJECTS]: item => ({
                        Id: item.Id,
                        AC001: item.AC001,
                        AC002: item.AC002
                    }),
                    [CACHE_KEYS.SECTIONS]: item => ({
                        Id: item.Id,
                        AID: item.AID,
                        BC01: item.BC01,
                        BC02: item.BC02
                    }),
                    [CACHE_KEYS.LABOR_TEAMS]: item => ({
                        Id: item.Id,
                        BID: item.BID,
                        DC01: item.DC01
                    }),
                    [CACHE_KEYS.WORKER_GROUPS]: item => ({
                        Id: item.Id,
                        BID: item.BID,
                        DID: item.DID,
                        EC01: item.EC01
                    })
                };

                const filteredData = res.Data.map(FIELD_FILTERS[cacheKey] || (item => ({ Id: item.Id })));
                refValue.value = filteredData;
                saveToCache(cacheKey, filteredData);
            } else {
                refValue.value = []
            }
        } catch {
            refValue.value = []
        }
    }

    const initSelect = () => {
        if (projectListAll.value?.length > 0) {
            projectList.value = projectListAll.value
            projectState.value = projectListAll.value[0]?.Id || ''

            sectionList.value = sectionListAll.value?.filter(item => item.AID === projectState.value) || []
            sectionState.value = sectionList.value[0]?.Id || ''

            laborTeamList.value = laborTeamListAll.value?.filter(item => item.BID === sectionState.value) || []
            laborTeamState.value = laborTeamList.value[0]?.Id || ''

            teamsGroupsList.value = teamsGroupsListAll.value?.filter(item => item.DID === laborTeamState.value) || []
            teamsGroupsState.value = teamsGroupsList.value[0]?.Id || ''
            return
        }

        if (sectionListAll.value?.length > 0) {
            sectionList.value = sectionListAll.value
            sectionState.value = sectionListAll.value[0]?.Id || ''

            laborTeamList.value = laborTeamListAll.value?.filter(item => item.BID === sectionState.value) || []
            laborTeamState.value = laborTeamList.value[0]?.Id || ''

            teamsGroupsList.value = teamsGroupsListAll.value?.filter(item => item.DID === laborTeamState.value) || []
            teamsGroupsState.value = teamsGroupsList.value[0]?.Id || ''
            return
        }

        if (laborTeamListAll.value?.length > 0) {
            laborTeamList.value = laborTeamListAll.value
            laborTeamState.value = laborTeamList.value[0]?.Id || ''

            teamsGroupsList.value = teamsGroupsListAll.value?.filter(item => item.DID === laborTeamState.value) || []
            teamsGroupsState.value = teamsGroupsList.value[0]?.Id || ''
            return
        }

        if (teamsGroupsListAll.value?.length > 0) {
            teamsGroupsList.value = teamsGroupsListAll.value
            teamsGroupsState.value = teamsGroupsList.value[0]?.Id || ''
        }
    }

    const projectChange = () => {
        sectionList.value = sectionListAll.value?.filter(item => item.AID === projectState.value) || []
        sectionState.value = sectionList.value[0]?.Id || ''

        laborTeamList.value = laborTeamListAll.value?.filter(item => item.BID === sectionState.value) || []
        laborTeamState.value = laborTeamList.value[0]?.Id || ''

        teamsGroupsList.value = teamsGroupsListAll.value?.filter(item => item.DID === laborTeamState.value) || []
        teamsGroupsState.value = teamsGroupsList.value[0]?.Id || ''

        fetchOptions.onChange?.()
    }

    const sectionChange = () => {
        laborTeamList.value = laborTeamListAll.value?.filter(item => item.BID === sectionState.value) || []
        laborTeamState.value = laborTeamList.value[0]?.Id || ''

        teamsGroupsList.value = teamsGroupsListAll.value?.filter(item => item.DID === laborTeamState.value) || []
        teamsGroupsState.value = teamsGroupsList.value[0]?.Id || ''

        fetchOptions.onChange?.()
    }
    const laborTeamChange = () => {
        teamsGroupsList.value = teamsGroupsListAll.value?.filter(item => item.DID === laborTeamState.value) || []
        teamsGroupsState.value = teamsGroupsList.value[0]?.Id || ''
        fetchOptions.onChange?.()
    }

    const teamsGroupsChange = () => {
        fetchOptions.onChange?.()
    }

    const initData = async () => {
        await Promise.all([
            fetchData(GetProjectInfoList, projectListAll, CACHE_KEYS.PROJECTS),
            fetchData(GetSectionList, sectionListAll, CACHE_KEYS.SECTIONS),
            fetchData(GetLaborTeamPageList, laborTeamListAll, CACHE_KEYS.LABOR_TEAMS),
            fetchData(GetWorkerGroupPageList, teamsGroupsListAll, CACHE_KEYS.WORKER_GROUPS)
        ])
        initSelect()
    }

    const clearCache = () => {
        Object.values(CACHE_KEYS).forEach(key => {
            sessionStorage.removeItem(key)
        })
    }

    return {
        projectState,
        projectList,
        projectListAll,
        sectionState,
        sectionList,
        sectionListAll,
        laborTeamState,
        laborTeamList,
        laborTeamListAll,
        teamsGroupsState,
        teamsGroupsList,
        teamsGroupsListAll,
        projectChange,
        sectionChange,
        laborTeamChange,
        teamsGroupsChange,
        initData,
        clearCache
    }
}