import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { isHttp, isEmpty } from "@/utils/validate"
import { resetRoutesAdded } from '@/permission'
import defAva from '@/assets/images/profile.jpg'

const user = {
  state: {
    token: getToken(),
    id: '',
    name: '',
    avatar: '',
    roles: [],
    permissions: []
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_ID: (state, id) => {
      state.id = id
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_PERMISSIONS: (state, permissions) => {
      state.permissions = permissions
    }
  },

  actions: {
    // 登录
    Login({ commit, dispatch }, userInfo) {
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      return new Promise((resolve, reject) => {
        console.log('开始登录请求，用户名:', username)
        login(username, password, code, uuid).then(res => {
          console.log('登录API响应:', res)
          if (res && res.status) {
            console.log('登录成功，token:', res.token)
            setToken(res.token)
            commit('SET_TOKEN', res.token)
            // 设置用户基本信息
            commit('SET_NAME', username)
            commit('SET_ID', username)
            commit('SET_ROLES', ['admin'])
            commit('SET_PERMISSIONS', ['*:*:*'])
            
            // 登录成功，让路由守卫来处理路由生成
            console.log('登录成功，等待路由守卫处理路由')
            resolve()
          } else {
            console.error('登录失败，响应状态:', res ? res.status : '无响应')
            reject(new Error('登录失败'))
          }
        }).catch(error => {
          console.error('登录请求错误:', error)
          // 如果API调用失败，尝试使用mock登录（仅用于测试）
          if (username === 'admin' && password === 'admin123') {
            console.log('使用mock登录')
            const mockToken = 'mock-token-' + Date.now()
            setToken(mockToken)
            commit('SET_TOKEN', mockToken)
            commit('SET_NAME', username)
            commit('SET_ID', username)
            commit('SET_ROLES', ['admin'])
            commit('SET_PERMISSIONS', ['*:*:*'])
            
            // Mock登录成功，让路由守卫来处理路由生成
            console.log('Mock登录成功，等待路由守卫处理路由')
            resolve()
          } else {
            reject(error)
          }
        })
      })
    },

    // 获取用户信息
    GetInfo({ commit, state }) {
      return new Promise((resolve, reject) => {
        // 使用静态用户信息，不再从后端获取
        const userInfo = {
          user: {
            userId: state.id || 'admin',
            userName: state.name || 'admin',
            avatar: defAva
          },
          roles: state.roles.length > 0 ? state.roles : ['admin'],
          permissions: state.permissions.length > 0 ? state.permissions : ['*:*:*']
        }
        
        commit('SET_ROLES', userInfo.roles)
        commit('SET_PERMISSIONS', userInfo.permissions)
        commit('SET_AVATAR', userInfo.user.avatar)
        
        if (!state.name) {
          commit('SET_NAME', userInfo.user.userName)
        }
        if (!state.id) {
          commit('SET_ID', userInfo.user.userId)
        }
        
        resolve(userInfo)
      })
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise(resolve => {
        // 直接前端退出，不调用后端接口
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONS', [])
        commit('SET_NAME', '')
        commit('SET_ID', '')
        commit('SET_AVATAR', '')
        // 清除路由状态
        commit('permission/CLEAR_ROUTES', null, { root: true })
        removeToken()
        // 重置路由添加标记
        resetRoutesAdded()
        resolve()
      })
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit('SET_TOKEN', '')
        // 清除路由状态
        commit('permission/CLEAR_ROUTES', null, { root: true })
        removeToken()
        // 重置路由添加标记
        resetRoutesAdded()
        resolve()
      })
    }
  }
}

export default user
