import { defineStore } from 'pinia'
import { login, loginOut, getCurrentUserDetail, getBtnAuth,loginByPwd } from '@/api/system/user'
import { initWebSocket, destroyWebSocket } from '@/requset/websocket'
import { getToken, setToken, removeToken } from '@/utils/cookie'

export const useUserStore = defineStore('user', {
    state: () => ({
        loginStatus: false,
        userInfo: null,
        userDetail: null,
        websocketEnabled: false, // 是否启用WebSocket连接
        btnAuth: {
            allMethod: [],
            curUserMethod: []
        }
    }),
    getters: {
        getToken: () => getToken(),
        isLogin: (state) => !!state.loginStatus,
        getUserInfo: (state) => state.userInfo,
        getUserDetail: (state) => state.userDetail,
        getBtnAuth: (state) => state.btnAuth
    },
    actions: {
        async userLogin(loginInfo: { username: string; password: string }) {
            try {
                const response = (await login(loginInfo)) as any

                if (response.loginStatus) {
                    // 添加状态码判断
                    const { loginStatus, token } = response
                    setToken(token)
                    this.userInfo = response as any
                    this.loginStatus = loginStatus

                    // 异步加载用户详情和按钮权限，不阻塞登录流程
                    this.loadUserDetailAsync(response.account)
                    this.loadBtnAuthAsync()

                    // 登录成功后初始化WebSocket连接
                    this.initWebSocketConnection()

                    return response // 返回成功响应
                }
                return Promise.reject(response.loginStatus) // 返回失败信息
            } catch (error) {
                return Promise.reject(error)
            }
        },
        // 免密登录
        async noPwdLogin(loginInfo: { username: string; password: string;token:string }) {
            try {
                const response = (await loginByPwd(loginInfo)) as any

                if (response.loginStatus) {
                    // 添加状态码判断
                    const { loginStatus, token } = response
                    setToken(token)
                    this.userInfo = response as any
                    this.loginStatus = loginStatus

                    // 异步加载用户详情和按钮权限，不阻塞登录流程
                    this.loadUserDetailAsync(response.account)
                    this.loadBtnAuthAsync()

                    // 登录成功后初始化WebSocket连接
                    this.initWebSocketConnection()

                    return response // 返回成功响应
                }
                return Promise.reject(response.loginStatus) // 返回失败信息
            } catch (error) {
                return Promise.reject(error)
            }
        },
        // 异步加载用户详情
        async loadUserDetailAsync(account: string) {
            try {
                const detailResponse = await getCurrentUserDetail(account)
                this.userDetail = detailResponse as any
            } catch (error) {
                console.warn('获取用户详情失败:', error)
            }
        },
        // 异步加载按钮权限
        async loadBtnAuthAsync() {
            try {
                const authResponse = await getBtnAuth()
                this.btnAuth = authResponse as any
            } catch (error) {
                console.warn('获取按钮权限失败:', error)
            }
        },
        async userLogout() {
            try {
                const response = await loginOut()
                // 退出登录时断开WebSocket连接
                this.destroyWebSocketConnection()
                this.clearUser()
                return response
            } catch (error) {
                return Promise.reject(error)
            }
        },
        setToken(token: string) {
            setToken(token)
        },
        setUserInfo(info: any) {
            this.userInfo = info
        },
        async setUserDetail(account: string) {
            const detailResponse = await getCurrentUserDetail(account)
            this.userDetail = detailResponse as any
        },
        clearUser() {
            // 清除cookie中的token
            removeToken()

            // 清除store状态
            this.loginStatus = false
            this.userInfo = null
            this.userDetail = null
            this.btnAuth = {
                allMethod: [],
                curUserMethod: []
            }

            // 延迟清除localStorage，确保在persist插件处理后执行
            setTimeout(() => {
                localStorage.removeItem('user')
                localStorage.removeItem('menu')
                localStorage.removeItem('dict')
            }, 0)

            // 清除sessionStorage中的数据（如果有）
            localStorage.clear()
        },
        // WebSocket连接管理
        initWebSocketConnection() {
            if (!this.websocketEnabled) {
                console.log('WebSocket连接已禁用')
                return
            }
            const websocketURL = window.config?.WEB_SOCKET_URL
            if (websocketURL) {
                console.log('WebSocket URL:', websocketURL)
                initWebSocket(websocketURL)
            } else {
                console.warn('WebSocket URL 未配置')
            }
        },
        setWebSocketEnabled(enabled: boolean) {
            this.websocketEnabled = enabled
        },
        destroyWebSocketConnection() {
            destroyWebSocket()
        }
    },

    persist: {
        storage: localStorage, // 改为sessionStorage
        key: 'user',
        pick: ['loginStatus', 'userInfo', 'userDetail', 'websocketEnabled', 'btnAuth']
    }
})
