import { toRefs, shallowReadonly } from 'vue'
import { queryLoginData } from '@/services/api/account'
import { useLoginStore } from './login'
import { VueStore } from '../base'

interface StoreState {
    loading: boolean;
    userData: Ermcp.LoginQueryRsp;
}

/**
 * 用户存储类
 */
const store = new (class extends VueStore<StoreState>{
    constructor() {
        const state: StoreState = {
            loading: false,
            userData: {
                arearole: [],
                externalExchanges: [],
                goodsgroups: [],
                markets: [],
                systemParams: []
            },
        }
        super(state)
    }

    actions = {
        /** 获取用户数据 */
        getUserData: () => {
            const { getLoginId } = useLoginStore()
            this.state.loading = true
            return queryLoginData({
                data: {
                    loginID: getLoginId()
                },
                success: (res) => {
                    this.state.userData = res.data
                },
                complete: () => {
                    this.state.loading = false
                }
            })
        },
        /** 获取用户数据 */
        getUserDataInfo: <K extends keyof Ermcp.LoginQueryRsp>(key: K) => {
            return this.state.userData[key]!
        },
        /** 获取登录机构名称 */
        getAccountName: () => {
            const { userAccount } = this.state.userData
            return userAccount?.accountname
        }
    }
})

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