import { reactive, toRefs } from 'vue'
import { v4 } from 'uuid'
import { encryptAES, decryptAES } from '@/utils/crypto'
import { defineStore } from '../store'
import { localData, sessionData } from '../storage'
import service from '@/services'

/**
 * 登录存储对象
 */
export const useLoginStore = defineStore(() => {
    const localToken = localData.getValue('accessToken')
    const sessionToken = sessionData.getValue('accessToken')

    // 创建当前会话唯一ID
    const uuid = sessionStorage.getItem('uuid') || v4()
    sessionStorage.setItem('uuid', uuid)

    const state = reactive({
        isLoggedIn: false,
        rsakey: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC+vKmZCnIVaI7KI1SqY2LhFXqwG9r+F135M4/EaCLKztZWokzl67SjCjmCgsk5ampDa/hPxugaAJo0KZPRaDGqVq54cLm3+dot8a1HU9rHqPCS5MvQRS7gk8ce/t8uHY40/KxLokOpXKmzM1rc3BNoh7elAnRIMCM3W8vhXZkhdwIDAQAB',
        token: localToken || sessionToken,
        signId: uuid,
        sign: ''
    })

    // 设置登录状态
    const setIsLoggedIn = (status: boolean) => {
        state.isLoggedIn = status
    }

    // 更新令牌信息
    const setToken = (value: string) => {
        const tokenStore = service.getConfig('tokenStore')
        state.token = value
        if (tokenStore === 'local') {
            localData.setValue('accessToken', value) // 缓存登录状态到本地
            sessionData.reset('accessToken')
        } else {
            sessionData.setValue('accessToken', value) // 缓存登录状态到会话
            localData.reset('accessToken')
        }
    }

    // 更新密钥
    const setSecretkey = (value: string) => {
        const values = [...value]
        const str = values.sort().join('')
        state.sign = str
    }

    // 获取自动登录信息
    const getAutoLoginData = () => {
        try {
            const encryptedData = localData.getValue('autoLoginEncryptedData')
            const decryptedString = decryptAES(encryptedData)
            return JSON.parse(decryptedString) as Model.LoginReq
        } catch (err) {
            clearAutoLoginData()
            return undefined
        }
    }

    // 更新自动登录信息
    const setAutoLoginData = (data: Model.LoginReq) => {
        const encryptedString = encryptAES(JSON.stringify(data)) // 数据加密
        localData.setValue('autoLoginEncryptedData', encryptedString)
    }

    // 清除自动登录信息
    const clearAutoLoginData = () => {
        localData.reset('autoLoginEncryptedData')
    }

    // 清除登录信息
    const clearLoginInfo = () => {
        state.token = ''
        state.isLoggedIn = false
        localData.reset('accessToken')
        sessionData.reset('accessToken')
    }

    return {
        ...toRefs(state),
        setToken,
        setSecretkey,
        setIsLoggedIn,
        getAutoLoginData,
        setAutoLoginData,
        clearAutoLoginData,
        clearLoginInfo,
    }
})