import { queryLoginData } from '@/services/api/account'
import { loginStore } from './login'
import { createStore } from '../base'
import eventBus from '@/services/bus'

/**
 * 用户存储对象
 */
export const userStore = createStore({
    state() {
        return {
            loading: false,
            userData: <Model.LoginQueryRsp>{
                arearole: [],
                externalExchanges: [],
                goodsgroups: [],
                markets: [],
                systemParams: []
            },
        }
    },
    getters: {
        // 用户信息
        userInfo() {
            const { userInfo } = this.state.userData
            return userInfo
        },
        // 登录机构名称
        accountName() {
            const { userAccount } = this.state.userData
            return userAccount?.accountname
        },
        // 是否已实名认证
        hasAuth() {
            const { userAccount } = this.state.userData
            return userAccount?.hasauth === 1
        }
    },
    actions: {
        // 获取用户数据
        getUserData() {
            this.state.loading = true
            return queryLoginData({
                loginID: loginStore.getters.loginId
            }).then((res) => {
                this.state.userData = res.data
            }).finally(() => {
                this.state.loading = false
            })
        },
        // 获取用户数据
        getUserDataInfo<K extends keyof Model.LoginQueryRsp>(key: K) {
            return this.state.userData[key]!
        },
        // 获取对应系统参数的对应值
        getSystemParamValue(paramcode: string) {
            const { systemParams } = this.state.userData
            return systemParams.find(obj => {
                return obj.paramcode === paramcode
            })?.paramvalue
        }
    }
})

// 接收账户变更通知
export const userChangeNtf = eventBus.$on('UserChangeNtf', () => {
    userStore.actions.getUserData()
})