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

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

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

        eventBus.$on('UserChangeNtf',()=>{
            this.actions.getUserData()
        })
    }

    /** 是否已实名认证 */
    private hasAuth = computed(() => {
        const { userAccount } = this.state.userData
        return userAccount?.hasauth === 1
    })

    getters = {
        hasAuth: this.hasAuth
    }

    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 Model.LoginQueryRsp>(key: K) => {
            return this.state.userData[key]!
        },
        /** 获取登录机构名称 */
        getAccountName: () => {
            const { userAccount } = this.state.userData
            return userAccount?.accountname
        },
        /** 获取登录用户信息 */
        getUserInfo: () => {
            const { userInfo } = this.state.userData
            return userInfo
        },
        /** 获取对应系统参数的对应值 */
        getSystemParamValue: (paramcode: string) => {
            const {systemParams} = this.state.userData
            return systemParams.find(obj => {
                return obj.paramcode === paramcode
            })?.paramvalue
        }
    }
})

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