import { shallowRef } from 'vue'
import { queryErrorInfos } from '@/services/api/common'
import { defineStore } from '../store'
import { sessionData } from '../storage'

/**
 * 错误信息存储对象
 */
export const useErrorInfoStore = defineStore(() => {
    const loading = shallowRef(false)
    const errorInfos = sessionData.getRef('errorInfos')

    // 获取系统错误信息
    const getErrorInfoList = async () => {
        try {
            if (errorInfos.value.length) {
                return Promise.resolve()
            }
            loading.value = true
            const res = await queryErrorInfos()
            errorInfos.value = res.data
        } finally {
            loading.value = false
        }
    }

    // 根据 code 获取错误信息
    const getErrorInfoByCode = (code: number) => {
        const error = errorInfos.value.find((e) => e.errorid === code)
        return error?.description
    }

    return {
        loading,
        errorInfos,
        getErrorInfoList,
        getErrorInfoByCode,
    }
})