import { toRefs, shallowReadonly, ShallowRef } from 'vue'
import { queryAllEnums } from '@/services/api/common'
import { VueStore } from '../base'
import WebStorage from '@/utils/storage/base'

/**
 * 枚举类型
 */
export interface EnumType {
    label: string;
    value: number;
    disabled?: boolean;
}

interface StoreState {
    loading: boolean;
    allEnums: ShallowRef<Ermcp.EnumRsp[]>;
}

/**
 * 枚举存储类
 */
const store = new (class extends VueStore<StoreState>{
    constructor() {
        const storage = new WebStorage<Ermcp.EnumRsp[]>(sessionStorage, 'allEnums', [])
        const state: StoreState = {
            loading: false,
            allEnums: storage.getRef(),
        }
        super(state)
    }

    actions = {
        /** 获取所有枚举列表 */
        getAllEnumList: () => {
            if (this.state.allEnums.length) {
                return Promise.resolve()
            }
            this.state.loading = true
            return queryAllEnums({
                success: (res) => {
                    this.state.allEnums = res.data
                },
                complete: () => {
                    this.state.loading = false
                }
            })
        },
        /** 获取枚举类型 */
        getEnumTypes: <T extends string[]>(...args: T) => {
            const enumMap = new Map<typeof args[number], Ermcp.EnumRsp[]>()
            this.state.allEnums.forEach((e) => {
                if (args.some((code) => code.toLowerCase() === e.enumdiccode.toLowerCase())) {
                    const enums = enumMap.get(e.enumdiccode)
                    if (enums) {
                        enums.push(e)
                    } else {
                        enumMap.set(e.enumdiccode, [e])
                    }
                }
            })
            return enumMap
        },
        /** 获取枚举信息 */
        getEnumTypeInfo: (enums: Ermcp.EnumRsp[], value: number) => {
            return enums.find((e) => e.enumitemstatus === 1 && e.enumitemname === value)
        },
        /** 获取枚举列表 */
        getEnumTypeList: (enums?: Ermcp.EnumRsp[]) => {
            return enums?.map((e) => ({
                label: e.enumdicname,
                value: e.enumitemname,
            })) ?? []
        },
        /** 根据枚举值获取枚举名称 */
        getEnumTypeName: (enums: EnumType[], value?: number) => {
            const item = enums.find((e) => e.value === value)
            return item?.label ?? value
        }
    }
})

export function useEnumStore() {
    return shallowReadonly({
        ...toRefs(store.state),
        ...store.actions,
        ...store.methods,
    })
}