/**
 * Vuex Auth Module - 用户认证状态管理
 * @module store/modules/auth
 */
import request from '@/utils/request'

// 从本地存储获取初始状态
const getAuthInitialState = () => {
  return {
    userInfo: uni.getStorageSync('userInfo') || null,
    token: uni.getStorageSync('token') || '',
    isLogin: !!uni.getStorageSync('token'),
    openId: uni.getStorageSync('openId') || '',
    userId: uni.getStorageSync('userId') || '',
    phoneNumber: uni.getStorageSync('phoneNumber') || ''
  }
}

const state = getAuthInitialState()

const mutations = {
  /**
   * 设置用户信息
   * @param {Object} userInfo - 用户信息对象
   */
  SET_USER_INFO(state, userInfo) {
    state.userInfo = userInfo
    uni.setStorageSync('userInfo', userInfo)
  },

  /**
   * 设置访问令牌
   * @param {String} token - 访问令牌
   */
  SET_TOKEN(state, token) {
    state.token = token
    uni.setStorageSync('token', token)
  },

  /**
   * 设置登录状态
   * @param {Boolean} status - 登录状态
   */
  SET_LOGIN_STATUS(state, status) {
    state.isLogin = status
  },

  /**
   * 设置 OpenID
   * @param {String} openId - 微信 OpenID
   */
  SET_OPEN_ID(state, openId) {
    state.openId = openId
    uni.setStorageSync('openId', openId)
  },

  /**
   * 设置用户 ID
   * @param {String} userId - 用户 ID
   */
  SET_USER_ID(state, userId) {
    state.userId = userId
    uni.setStorageSync('userId', userId)
  },

  /**
   * 设置手机号
   * @param {String} phoneNumber - 手机号
   */
  SET_PHONE_NUMBER(state, phoneNumber) {
    state.phoneNumber = phoneNumber
    uni.setStorageSync('phoneNumber', phoneNumber)
  },

  /**
   * 清除所有认证信息
   */
  CLEAR_AUTH(state) {
    state.userInfo = null
    state.token = ''
    state.isLogin = false
    state.openId = ''
    state.userId = ''
    state.phoneNumber = ''
    // 清除本地存储
    uni.removeStorageSync('userInfo')
    uni.removeStorageSync('token')
    uni.removeStorageSync('openId')
    uni.removeStorageSync('userId')
    uni.removeStorageSync('phoneNumber')
  }
}

const actions = {
  /**
   * 检查登录状态
   * @returns {Promise<Boolean>} 是否已登录
   */
  checkLogin({ commit, state }) {
    return new Promise((resolve) => {
      const token = uni.getStorageSync('token')
      if (token) {
        commit('SET_TOKEN', token)
        commit('SET_LOGIN_STATUS', true)
        resolve(true)
      } else {
        resolve(false)
      }
    })
  },

  /**
   * 微信登录
   * @param {String} code - 微信登录 code
   * @returns {Promise<Object>} 登录结果
   */
  async wechatLogin({ commit }, code) {
    try {
      const res = await request({
        url: '/api/wechat/login',
        method: 'POST',
        data: { code }
      })

      commit('SET_USER_INFO', res.data.userInfo)
      commit('SET_TOKEN', res.data.token)
      commit('SET_LOGIN_STATUS', true)
      
      return res.data
    } catch (error) {
      console.error('登录失败:', error)
      throw new Error('登录请求失败')
    }
  },

  /**
   * 退出登录
   */
  logout({ commit }) {
    commit('CLEAR_AUTH')
  }
}

const getters = {
  /**
   * 获取用户信息
   */
  userInfo: state => state.userInfo,
  
  /**
   * 获取令牌
   */
  token: state => state.token,
  
  /**
   * 是否已登录
   */
  isLogin: state => state.isLogin,
  
  /**
   * 获取 OpenID
   */
  openId: state => state.openId,
  
  /**
   * 获取用户 ID
   */
  userId: state => state.userId
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}