import { queryErrorInfos } from '@/services/api/common'
import { createStore } from '../base'
import { sessionData } from '../storage'

/**
 * 错误信息存储对象
 */
export const errorInfoStore = createStore({
    state() {
        return {
            loading: false,
            errorInfos: sessionData.getRef('errorInfos'),
        }
    },
    actions: {
        // 获取系统错误信息
        getErrorInfoList() {
            if (this.state.errorInfos.length) {
                return Promise.resolve()
            }
            this.state.loading = true
            return queryErrorInfos().then((res) => {
                this.state.errorInfos = res.data
            }).finally(() => {
                this.state.loading = false
            })
        },
        // 根据 code 获取错误信息
        getErrorInfoByCode(code: number) {
            const errorInfos = this.state.errorInfos
            const error = errorInfos.find((e) => e.errorid === code)
            return error?.description
        }
    }
})