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

interface StoreState {
    loading: boolean;
    errorInfos: ShallowRef<Ermcp.ErrorInfosRsp[]>;
}

/**
 * 错误信息存储类
 */
const store = new (class extends VueStore<StoreState>{
    constructor() {
        const storage = new WebStorage<Ermcp.ErrorInfosRsp[]>(sessionStorage, 'errorInfos', [])
        const state: StoreState = {
            loading: false,
            errorInfos: storage.getRef(),
        }
        super(state)
    }

    actions = {
        /** 获取系统错误信息 */
        getErrorInfoList: () => {
            if (this.state.errorInfos.length) {
                return Promise.resolve()
            }
            this.state.loading = true
            return queryErrorInfos({
                success: (res) => {
                    this.state.errorInfos = res.data
                },
                complete: () => {
                    this.state.loading = false
                }
            })
        },
        /** 根据 code 获取错误信息 */
        getErrorInfoByCode: (code: number) => {
            const errorInfos = this.state.errorInfos
            const error = errorInfos.find((e) => e.errorid === code)
            return error?.description
        }
    }
})

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