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

// 初始化登录信息
function initLoginInfo(): Proto.LoginRsp {
    return {
        RetCode: 0,
        RetDesc: '',
        AccountIDs: [],
        LoginCode: '',
        LoginID: 0,
        LoginUserType: 0,
        AccountStatus: 0,
        UserID: 0,
        ClientID: 0,
        MemberUserID: 0,
        Token: '',
    }
}

/**
 * 登录存储对象
 */
export const useLoginStore = defineStore(() => {
    const localLoginInfo = localData.getValue('loginInfo')
    const sessionLoginInfo = sessionData.getValue('loginInfo')

    const state = reactive({
        logining: false,
        loginInfo: localLoginInfo || sessionLoginInfo || initLoginInfo()
    })

    // 登录令牌
    const token = computed(() => state.loginInfo.Token)

    // 用户ID
    const userId = computed(() => state.loginInfo.UserID)

    // 登录ID
    const loginId = computed(() => state.loginInfo.LoginID)

    // 首个资金账户ID
    const firstAccountId = computed(() => {
        const accounts = state.loginInfo.AccountIDs
        return accounts[0] ?? 0
    })

    // 获取用户登录信息
    const getLoginInfo = <K extends keyof Proto.LoginRsp>(key: K) => {
        return state.loginInfo[key]
    }

    // 更新登录信息
    const setLoginInfo = (data: Proto.LoginRsp, persist = false) => {
        state.loginInfo = data
        if (persist) {
            localData.setValue('loginInfo', data) // 缓存登录状态到本地
            sessionData.reset('loginInfo')
        } else {
            sessionData.setValue('loginInfo', data) // 缓存登录状态到会话
            localData.reset('loginInfo')
        }
    }

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

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

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

    // 清除登录信息
    const clearLoginInfo = () => {
        localData.reset('loginInfo')
        sessionData.reset()
        state.loginInfo = initLoginInfo()
    }

    return {
        ...toRefs(state),
        token,
        userId,
        loginId,
        firstAccountId,
        getLoginInfo,
        setLoginInfo,
        getAutoLoginData,
        setAutoLoginData,
        clearAutoLoginData,
        clearLoginInfo,
    }
})