/**
 * 用户状态管理模块
 * 管理用户信息、登录状态、权限等
 */

import { defineStore } from 'pinia'
import { userApi } from '@/common/api/user'
import { storage } from '@/common/utils/storage'
import { APP_CONFIG } from '@/common/config'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户基本信息
    userInfo: null,
    
    // 登录状态
    isLoggedIn: false,
    
    // 访问令牌
    accessToken: null,
    
    // 刷新令牌
    refreshToken: null,
    
    // 用户权限列表
    permissions: [],
    
    // 用户角色
    roles: [],
    
    // 登录时间
    loginTime: null,
    
    // 最后活跃时间
    lastActiveTime: null,
    
    // 用户设置
    settings: {
      theme: 'light',
      language: 'zh-CN',
      notifications: true,
      autoLogin: true
    }
  }),

  getters: {
    // 获取用户ID
    userId: (state) => state.userInfo?.id,
    
    // 获取用户名
    username: (state) => state.userInfo?.username,
    
    // 获取用户昵称
    nickname: (state) => state.userInfo?.nickname || state.userInfo?.username,
    
    // 获取用户头像
    avatar: (state) => state.userInfo?.avatar || '/static/images/default-avatar.png',
    
    // 获取用户手机号
    phone: (state) => state.userInfo?.phone,
    
    // 获取用户邮箱
    email: (state) => state.userInfo?.email,
    
    // 检查是否有特定权限
    hasPermission: (state) => (permission) => {
      return state.permissions.includes(permission)
    },
    
    // 检查是否有特定角色
    hasRole: (state) => (role) => {
      return state.roles.includes(role)
    },
    
    // 检查是否为管理员
    isAdmin: (state) => {
      return state.roles.includes('admin') || state.roles.includes('super_admin')
    },
    
    // 检查登录是否过期
    isTokenExpired: (state) => {
      if (!state.loginTime) return true
      const now = Date.now()
      const expireTime = state.loginTime + (24 * 60 * 60 * 1000) // 24小时
      return now > expireTime
    },
    
    // 获取用户完整信息
    fullUserInfo: (state) => {
      return {
        ...state.userInfo,
        permissions: state.permissions,
        roles: state.roles,
        settings: state.settings
      }
    }
  },

  actions: {
    /**
     * 用户登录
     * @param {Object} credentials 登录凭证
     * @param {string} credentials.username 用户名
     * @param {string} credentials.password 密码
     * @param {string} credentials.code 验证码（可选）
     */
    async login(credentials) {
      try {
        const response = await userApi.login(credentials)
        const { user, token, refreshToken, permissions, roles } = response.data
        
        // 保存用户信息
        this.userInfo = user
        this.accessToken = token
        this.refreshToken = refreshToken
        this.permissions = permissions || []
        this.roles = roles || []
        this.isLoggedIn = true
        this.loginTime = Date.now()
        this.lastActiveTime = Date.now()
        
        // 保存到本地存储
        storage.set(APP_CONFIG.storage.tokenKey, token)
        storage.set(APP_CONFIG.storage.userKey, user)
        
        return response
      } catch (error) {
        console.error('登录失败:', error)
        throw error
      }
    },

    /**
     * 微信登录
     * @param {Object} wxLoginData 微信登录数据
     */
    async wxLogin(wxLoginData) {
      try {
        const response = await userApi.wxLogin(wxLoginData)
        const { user, token, refreshToken, permissions, roles } = response.data
        
        // 保存用户信息
        this.userInfo = user
        this.accessToken = token
        this.refreshToken = refreshToken
        this.permissions = permissions || []
        this.roles = roles || []
        this.isLoggedIn = true
        this.loginTime = Date.now()
        this.lastActiveTime = Date.now()
        
        // 保存到本地存储
        storage.set(APP_CONFIG.storage.tokenKey, token)
        storage.set(APP_CONFIG.storage.userKey, user)
        
        return response
      } catch (error) {
        console.error('微信登录失败:', error)
        throw error
      }
    },

    /**
     * 用户注册
     * @param {Object} userData 注册数据
     */
    async register(userData) {
      try {
        const response = await userApi.register(userData)
        return response
      } catch (error) {
        console.error('注册失败:', error)
        throw error
      }
    },

    /**
     * 用户登出
     */
    async logout() {
      try {
        if (this.accessToken) {
          await userApi.logout()
        }
      } catch (error) {
        console.error('登出请求失败:', error)
      } finally {
        // 清除用户信息
        this.userInfo = null
        this.accessToken = null
        this.refreshToken = null
        this.permissions = []
        this.roles = []
        this.isLoggedIn = false
        this.loginTime = null
        this.lastActiveTime = null
        
        // 清除本地存储
        storage.remove(APP_CONFIG.storage.tokenKey)
        storage.remove(APP_CONFIG.storage.userKey)
      }
    },

    /**
     * 刷新访问令牌
     */
    async refreshAccessToken() {
      try {
        if (!this.refreshToken) {
          throw new Error('没有刷新令牌')
        }
        
        const response = await userApi.refreshToken(this.refreshToken)
        const { token, refreshToken } = response.data
        
        this.accessToken = token
        if (refreshToken) {
          this.refreshToken = refreshToken
        }
        
        // 更新本地存储
        storage.set(APP_CONFIG.storage.tokenKey, token)
        
        return response
      } catch (error) {
        console.error('刷新令牌失败:', error)
        // 刷新失败，清除登录状态
        await this.logout()
        throw error
      }
    },

    /**
     * 获取用户信息
     */
    async fetchUserInfo() {
      try {
        const response = await userApi.getUserInfo()
        const { user, permissions, roles } = response.data
        
        this.userInfo = user
        this.permissions = permissions || []
        this.roles = roles || []
        this.lastActiveTime = Date.now()
        
        // 更新本地存储
        storage.set(APP_CONFIG.storage.userKey, user)
        
        return response
      } catch (error) {
        console.error('获取用户信息失败:', error)
        throw error
      }
    },

    /**
     * 更新用户信息
     * @param {Object} userData 用户数据
     */
    async updateUserInfo(userData) {
      try {
        const response = await userApi.updateUserInfo(userData)
        const { user } = response.data
        
        this.userInfo = { ...this.userInfo, ...user }
        this.lastActiveTime = Date.now()
        
        // 更新本地存储
        storage.set(APP_CONFIG.storage.userKey, this.userInfo)
        
        return response
      } catch (error) {
        console.error('更新用户信息失败:', error)
        throw error
      }
    },

    /**
     * 修改密码
     * @param {Object} passwordData 密码数据
     * @param {string} passwordData.oldPassword 旧密码
     * @param {string} passwordData.newPassword 新密码
     */
    async changePassword(passwordData) {
      try {
        const response = await userApi.changePassword(passwordData)
        return response
      } catch (error) {
        console.error('修改密码失败:', error)
        throw error
      }
    },

    /**
     * 绑定手机号
     * @param {Object} phoneData 手机号数据
     * @param {string} phoneData.phone 手机号
     * @param {string} phoneData.code 验证码
     */
    async bindPhone(phoneData) {
      try {
        const response = await userApi.bindPhone(phoneData)
        const { user } = response.data
        
        this.userInfo = { ...this.userInfo, ...user }
        
        // 更新本地存储
        storage.set(APP_CONFIG.storage.userKey, this.userInfo)
        
        return response
      } catch (error) {
        console.error('绑定手机号失败:', error)
        throw error
      }
    },

    /**
     * 更新用户设置
     * @param {Object} settings 设置数据
     */
    updateSettings(settings) {
      this.settings = { ...this.settings, ...settings }
      
      // 保存到本地存储
      storage.set(APP_CONFIG.storage.settingsKey, this.settings)
    },

    /**
     * 更新最后活跃时间
     */
    updateLastActiveTime() {
      this.lastActiveTime = Date.now()
    },

    /**
     * 检查登录状态
     */
    checkLoginStatus() {
      const token = storage.get(APP_CONFIG.storage.tokenKey)
      const user = storage.get(APP_CONFIG.storage.userKey)
      
      if (token && user && !this.isTokenExpired) {
        this.accessToken = token
        this.userInfo = user
        this.isLoggedIn = true
        this.lastActiveTime = Date.now()
        return true
      } else {
        this.logout()
        return false
      }
    },

    /**
     * 清除用户数据
     */
    clearUserData() {
      this.$reset()
      storage.remove(APP_CONFIG.storage.tokenKey)
      storage.remove(APP_CONFIG.storage.userKey)
      storage.remove(APP_CONFIG.storage.settingsKey)
    }
  },

  // 持久化配置
  persist: {
    key: 'user-store',
    storage: {
      getItem: (key) => uni.getStorageSync(key),
      setItem: (key, value) => uni.setStorageSync(key, value),
      removeItem: (key) => uni.removeStorageSync(key)
    },
    paths: ['userInfo', 'isLoggedIn', 'accessToken', 'refreshToken', 'permissions', 'roles', 'loginTime', 'settings']
  }
})