import { reactive, computed, toRefs } from 'vue'
import { queryLoginData } from '@/services/api/account'
import { useLoginStore } from './login'
import { defineStore } from '../store'

/**
 * 用户存储对象
 * @returns 
 */
export const useUserStore = defineStore(() => {
    const loginStore = useLoginStore()

    const state = reactive({
        loading: false,
        userData: <Ermcp.LoginQueryRsp>{
            arearole: [],
            externalExchanges: [],
            goodsgroups: [],
            markets: [],
            systemParams: []
        },
    })

    // 用户信息
    const userInfo = computed(() => state.userData.userInfo)

    // 登录机构名称
    const accountName = computed(() => {
        const { userAccount } = state.userData
        return userAccount?.accountname
    })

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

    // 获取用户数据
    const getUserData = async () => {
        try {
            state.loading = true
            const res = await queryLoginData({
                loginID: loginStore.loginId
            })
            state.userData = res.data
        } finally {
            state.loading = false
        }
    }

    // 获取用户数据
    const getUserDataInfo = <K extends keyof Ermcp.LoginQueryRsp>(key: K) => {
        return state.userData[key]!
    }

    // 获取对应系统参数的对应值
    const getSystemParamValue = (paramcode: string) => {
        const { systemParams } = state.userData
        return systemParams.find(obj => {
            return obj.paramcode === paramcode
        })?.paramvalue
    }

    return {
        ...toRefs(state),
        userInfo,
        accountName,
        hasAuth,
        getUserData,
        getUserDataInfo,
        getSystemParamValue,
    }
})