// store/user.js - 基于Pinia的用户状态管理
import { defineStore } from 'pinia'
import { authAPI } from '@/utils/api'
import { STORAGE_KEYS } from '@/utils/constants'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    userInfo: null,
    isLoggedIn: false,
    loginTime: null
  }),
  
  getters: {
    // 是否已认证
    isAuthenticated: (state) => !!state.token && !!state.userInfo,
    
    // 用户昵称
    nickname: (state) => state.userInfo?.nickname || '未登录',
    
    // 用户头像
    avatar: (state) => state.userInfo?.avatar || '/static/images/default-avatar.png',
    
    // 用户角色
    roleId: (state) => state.userInfo?.role_id || null,
    
    // 是否为管理员
    isAdmin: (state) => {
      const roleId = state.userInfo?.role_id
      return roleId === 1 || roleId === 2
    },
    
    // 是否为普通用户
    isUser: (state) => state.userInfo?.role_id === 3
  },
  
  actions: {
    // 微信登录（动态调用保险端后端认证接口）
    async wxLogin() {
      try {
        console.log('开始微信登录...')
        
        // 1. 获取微信登录码
        const loginRes = await uni.login({
          provider: 'weixin'
        })
        
        if (!loginRes[1]?.code) {
          throw new Error('获取登录码失败')
        }
        
        console.log('获取到微信登录码:', loginRes[1].code)
        
        // 2. 获取用户信息（微信小程序需要用户授权）
        const userInfoRes = await uni.getUserInfo({
          provider: 'weixin'
        })
        
        console.log('获取到用户信息:', userInfoRes[1])
        
        // 3. 发送到保险端后端验证（动态调用）
        const authRes = await authAPI.wxLogin({
          code: loginRes[1].code,
          userInfo: userInfoRes[1].userInfo,
          signature: userInfoRes[1].signature,
          rawData: userInfoRes[1].rawData
        })
        
        console.log('后端认证成功:', authRes)
        
        // 4. 保存 token 和用户信息
        this.token = authRes.data.token
        this.userInfo = authRes.data.userInfo
        this.isLoggedIn = true
        this.loginTime = new Date().toISOString()
        
        // 持久化存储
        uni.setStorageSync(STORAGE_KEYS.TOKEN, this.token)
        uni.setStorageSync(STORAGE_KEYS.USER_INFO, this.userInfo)
        uni.setStorageSync(STORAGE_KEYS.LAST_LOGIN_TIME, this.loginTime)
        
        console.log('登录状态保存成功')
        
        return authRes.data
      } catch (error) {
        console.error('微信登录失败:', error)
        
        // 登录失败时清理状态
        this.clearLoginState()
        
        throw error
      }
    },
    
    // 普通账号密码登录（复用现有接口）
    async login(credentials) {
      try {
        console.log('开始账号密码登录...')
        
        // 动态调用保险端登录接口
        const authRes = await authAPI.login(credentials)
        
        // 保存登录状态
        this.token = authRes.data.token
        this.userInfo = authRes.data.userInfo
        this.isLoggedIn = true
        this.loginTime = new Date().toISOString()
        
        // 持久化存储
        uni.setStorageSync(STORAGE_KEYS.TOKEN, this.token)
        uni.setStorageSync(STORAGE_KEYS.USER_INFO, this.userInfo)
        uni.setStorageSync(STORAGE_KEYS.LAST_LOGIN_TIME, this.loginTime)
        
        return authRes.data
      } catch (error) {
        console.error('登录失败:', error)
        this.clearLoginState()
        throw error
      }
    },
    
    // 检查登录状态
    checkAuth() {
      try {
        const token = uni.getStorageSync(STORAGE_KEYS.TOKEN)
        const userInfo = uni.getStorageSync(STORAGE_KEYS.USER_INFO)
        const loginTime = uni.getStorageSync(STORAGE_KEYS.LAST_LOGIN_TIME)
        
        if (token && userInfo) {
          this.token = token
          this.userInfo = userInfo
          this.isLoggedIn = true
          this.loginTime = loginTime
          
          console.log('恢复登录状态成功:', userInfo)
          return true
        }
        
        return false
      } catch (error) {
        console.error('检查登录状态失败:', error)
        return false
      }
    },
    
    // 获取用户信息（动态调用保险端接口）
    async getUserProfile() {
      try {
        const res = await authAPI.getProfile()
        this.userInfo = res.data
        
        // 更新本地存储
        uni.setStorageSync(STORAGE_KEYS.USER_INFO, this.userInfo)
        
        return res.data
      } catch (error) {
        console.error('获取用户信息失败:', error)
        throw error
      }
    },
    
    // 更新用户信息（动态调用保险端接口）
    async updateProfile(data) {
      try {
        const res = await authAPI.updateProfile(data)
        this.userInfo = { ...this.userInfo, ...res.data }
        
        // 更新本地存储
        uni.setStorageSync(STORAGE_KEYS.USER_INFO, this.userInfo)
        
        return res.data
      } catch (error) {
        console.error('更新用户信息失败:', error)
        throw error
      }
    },
    
    // 退出登录
    async logout() {
      try {
        // 调用后端退出接口
        await authAPI.logout()
      } catch (error) {
        console.warn('后端退出接口调用失败:', error)
      } finally {
        // 无论后端接口是否成功，都清理本地状态
        this.clearLoginState()
        
        // 跳转到登录页
        uni.reLaunch({
          url: '/pages/login/login'
        })
      }
    },
    
    // 清理登录状态
    clearLoginState() {
      this.token = ''
      this.userInfo = null
      this.isLoggedIn = false
      this.loginTime = null
      
      // 清理本地存储
      uni.removeStorageSync(STORAGE_KEYS.TOKEN)
      uni.removeStorageSync(STORAGE_KEYS.USER_INFO)
      uni.removeStorageSync(STORAGE_KEYS.LAST_LOGIN_TIME)
      
      console.log('登录状态已清理')
    },
    
    // 刷新token
    async refreshToken() {
      try {
        // 如果后端支持token刷新
        const res = await authAPI.refreshToken()
        this.token = res.data.token
        uni.setStorageSync(STORAGE_KEYS.TOKEN, this.token)
        return res.data.token
      } catch (error) {
        console.error('刷新token失败:', error)
        // token刷新失败，需要重新登录
        this.logout()
        throw error
      }
    }
  }
})