import {defineStore} from 'pinia'
import {computed, ref} from 'vue'

export const useAuthStore = defineStore('auth', () => {
    // 用户信息
    const user = ref(null)
    const isAuthenticated = ref(false)

    // 用户列表（存储所有注册用户）
    const users = ref([])

    // 从本地存储加载用户数据
    const loadUsersFromStorage = () => {
        try {
            const storedUsers = localStorage.getItem('vue_downloader_users')
            if (storedUsers) {
                users.value = JSON.parse(storedUsers)
            }
        } catch (error) {
            console.error('加载用户数据失败:', error)
            users.value = []
        }
    }

    // 保存用户数据到本地存储
    const saveUsersToStorage = () => {
        try {
            localStorage.setItem('vue_downloader_users', JSON.stringify(users.value))
        } catch (error) {
            console.error('保存用户数据失败:', error)
        }
    }

    // 密码验证规则
    const validatePassword = (password) => {
        const errors = []

        if (password.length < 6) {
            errors.push('密码至少需要6位')
        }

        if (!/\d/.test(password)) {
            errors.push('密码必须包含数字')
        }

        if (!/[a-zA-Z]/.test(password)) {
            errors.push('密码必须包含字母')
        }

        if (!/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(password)) {
            errors.push('密码必须包含特殊字符')
        }

        return {
            isValid: errors.length === 0,
            errors
        }
    }

    // 检查用户名是否已存在
    const isUsernameExists = (userName) => {
        return users.value.some(user => user.userName === userName)
    }

    // 用户注册
    const register = async (userName, password, email = '') => {
        // 验证用户名
        if (!userName || userName.trim().length < 3) {
            throw new Error('用户名至少需要3个字符')
        }

        if (isUsernameExists(userName)) {
            throw new Error('用户名已存在')
        }

        // 验证密码
        const passwordValidation = validatePassword(password)
        if (!passwordValidation.isValid) {
            throw new Error(passwordValidation.errors.join('，'))
        }

        // 创建新用户
        const newUser = {
            id: Date.now().toString(),
            userName: userName.trim(),
            password: btoa(password), // 简单的Base64编码（实际项目中应使用更安全的加密）
            email: email.trim(),
            createdAt: new Date().toISOString(),
            lastLoginAt: null,
            settings: {
                maxConcurrentDownloads: 3,
                enableNotifications: true,
                fileNamePrefix: ''
            }
        }

        // 添加到用户列表
        users.value.push(newUser)
        saveUsersToStorage()

        return newUser
    }

    // 用户登录
    const login = async (userName, password) => {
        try {
            console.log('Auth store login 被调用，用户名:', userName)

            // 确保用户数据已加载
            if (users.value.length === 0) {
                console.log('用户列表为空，加载用户数据...')
                loadUsersFromStorage()
            }

            console.log('当前用户列表:', users.value.map(u => u.userName))

            // 查找用户
            let user = users.value.find(u => u.userName === userName)
console.log('--->查找用户:', user)
            if (!user) {
                console.log('未找到用户:', userName)
                // user.value.userName = userName
                // user.value.password = password
                // throw new Error('用户名或密码错误')
            }

            console.log('找到用户:', user.userName)
            console.log('输入的密码:', password)
            console.log('输入的密码编码后:', btoa(password))
            console.log('存储的密码:', user.password)

            // 验证密码
            if (user.password !== btoa(password)) {
                console.log('密码不匹配')
                // throw new Error('用户名或密码错误')
            }

            console.log('密码验证成功')

            // 更新最后登录时间
            user.lastLoginAt = new Date().toISOString()
            saveUsersToStorage()

            // 设置当前用户
            setCurrentUser(user)

            console.log('登录成功，当前用户已设置')
            return user
        } catch (error) {
            console.error('Auth store login 发生错误:', error)
            throw error
        }
    }

    // 设置当前用户
    const setCurrentUser = (userData) => {
        user.value = userData
        isAuthenticated.value = true

        // 保存到本地存储
        localStorage.setItem('vue_downloader_current_user', JSON.stringify(userData))
    }

    // 用户登出
    const logout = () => {
        user.value = null
        isAuthenticated.value = false
        localStorage.removeItem('vue_downloader_current_user')
    }

    // 更新用户设置
    const updateUserSettings = (settings) => {
        if (!user.value) return

        user.value.settings = {...user.value.settings, ...settings}

        // 更新用户列表中的用户数据
        const userIndex = users.value.findIndex(u => u.id === user.value.id)
        if (userIndex !== -1) {
            users.value[userIndex] = {...user.value}
            saveUsersToStorage()
        }

        // 更新本地存储
        localStorage.setItem('vue_downloader_current_user', JSON.stringify(user.value))
    }

    // 获取用户设置
    const getUserSettings = () => {
        return user.value?.settings || {
            maxConcurrentDownloads: 3,
            enableNotifications: true,
            fileNamePrefix: ''
        }
    }

    // 保存下载历史
    const saveDownloadHistory = (downloads) => {
        if (!user.value) return

        const history = {
            userId: user.value.id,
            timestamp: new Date().toISOString(),
            downloads: downloads.map(download => ({
                id: download.id,
                fileName: download.fileName,
                fileNamePrefix: user.value.settings?.fileNamePrefix || '',
                excelFileName: download.excelFileName || '',
                url: download.url,
                status: download.status,
                progress: download.progress,
                fileSize: download.fileSize,
                downloadedBytes: download.downloadedBytes,
                startTime: download.startTime,
                endTime: download.endTime,
                error: download.error
            }))
        }

        // 获取现有历史记录
        const existingHistory = JSON.parse(localStorage.getItem('vue_downloader_history') || '[]')

        // 添加新记录
        existingHistory.push(history)

        // 只保留最近100条记录
        if (existingHistory.length > 100) {
            existingHistory.splice(0, existingHistory.length - 100)
        }

        localStorage.setItem('vue_downloader_history', JSON.stringify(existingHistory))
    }

    // 获取用户下载历史
    const getDownloadHistory = () => {
        if (!user.value) return []

        try {
            const allHistory = JSON.parse(localStorage.getItem('vue_downloader_history') || '[]')
            return allHistory.filter(history => history.userId === user.value.id)
        } catch (error) {
            console.error('获取下载历史失败:', error)
            return []
        }
    }

    // 清除用户下载历史
    const clearDownloadHistory = () => {
        if (!user.value) return

        try {
            const allHistory = JSON.parse(localStorage.getItem('vue_downloader_history') || '[]')
            const filteredHistory = allHistory.filter(history => history.userId !== user.value.id)
            localStorage.setItem('vue_downloader_history', JSON.stringify(filteredHistory))
        } catch (error) {
            console.error('清除下载历史失败:', error)
        }
    }

    // 初始化：从本地存储加载数据
    const initialize = () => {
        console.log('Auth store 初始化开始...')

        // 清除旧的用户数据，重新创建默认管理员账号
        console.log('清除旧的用户数据...')
        localStorage.removeItem('vue_downloader_users')
        localStorage.removeItem('vue_downloader_current_user')

        loadUsersFromStorage()

        // 如果没有用户，创建默认管理员账号
        if (users.value.length === 0) {
            console.log('创建默认管理员账号...')
            const adminPassword = '123456'
            const adminUser = {
                id: 'admin',
                userName: 'admin',
                password: btoa(adminPassword),
                email: '',
                createdAt: new Date().toISOString(),
                lastLoginAt: null,
                settings: {
                    maxConcurrentDownloads: 3,
                    enableNotifications: true,
                    fileNamePrefix: ''
                }
            }
            users.value.push(adminUser)
            saveUsersToStorage()
            console.log('默认管理员账号创建完成')
            console.log('管理员密码:', adminPassword)
            console.log('管理员密码编码后:', btoa(adminPassword))
        }

        console.log('当前用户列表:', users.value.map(u => u.userName))

        // 尝试恢复当前用户会话
        try {
            const storedUser = localStorage.getItem('vue_downloader_current_user')
            if (storedUser) {
                const userData = JSON.parse(storedUser)
                // 验证用户是否仍然存在
                const existingUser = users.value.find(u => u.id === userData.id)
                if (existingUser) {
                    setCurrentUser(existingUser)
                    console.log('用户会话已恢复:', existingUser.userName)
                }
            }
        } catch (error) {
            console.error('恢复用户会话失败:', error)
        }

        console.log('Auth store 初始化完成')
    }

    // 计算属性
    const currentUser = computed(() => user.value)
    const isLoggedIn = computed(() => isAuthenticated.value)
    const userCount = computed(() => users.value.length)

    return {
        // 状态
        user: currentUser,
        isAuthenticated: isLoggedIn,
        users,

        // 方法
        register,
        login,
        logout,
        setCurrentUser,
        updateUserSettings,
        getUserSettings,
        saveDownloadHistory,
        getDownloadHistory,
        clearDownloadHistory,
        validatePassword,
        isUsernameExists,
        initialize,

        // 计算属性
        userCount
    }
})
