import { defineStore } from 'pinia'
import pinia from '~src/store/init'
import appConfig from '~src/config/app'
import { clearStoreAll, getStoreValue, setStoreValue } from '~src/utils/storage'
import { removeRefreshToken, removeToken, setRefreshToken, setToken } from '~src/api/util/auth'

export const useAppStore = defineStore('main', {
    state: () => ({
        //系统信息
        title: getStoreValue('title') || appConfig.title,
        //用户信息
        token: getStoreValue('token') || '',
        refreshToken: getStoreValue('refreshToken') || '',
        tenantId: getStoreValue('tenantId') || '',
        userInfo: getStoreValue('userInfo') || {},
    }),
    getters: {
        //系统信息
        getTitle: state => state.title,
        //用户信息
        getToken: state => state.token,
        getRefreshToken: state => state.refreshToken,
        getTenantId: state => state.tenantId,
        getUserInfo: state => state.userInfo,
    },
    actions: {
        //系统信息
        setTitle(value) {
            this.title = value
            setStoreValue('title', value)
        },
        //用户信息
        setTokenVal(value) {
            this.token = value
            setToken(value)
            setStoreValue('token', value)
        },
        setRefreshTokenVal(value) {
            this.refreshToken = value
            setRefreshToken(value)
            setStoreValue('refreshToken', value)
        },
        setTenantId(value) {
            this.tenantId = value
            setStoreValue('tenantId', value)
        },
        setUserInfo(value) {
            this.userInfo = value
            setStoreValue('userInfo', value)
        },
        //清除缓存和token
        clearStoreData() {
            //清除状态
            this.title = null
            this.token = null
            this.refreshToken = null
            this.tenantId = null
            this.userInfo = null
            //清除缓存
            clearStoreAll()
            removeToken()
            removeRefreshToken()
        },
    },
})

export default function useUserStoreWidthOut() {
    return useAppStore(pinia)
}
