// 认证工具类
import { API_ENDPOINTS, buildURL } from '@/common/config/api'
import request from './request'
import storage from './storage'

class Auth {
  constructor() {
    this.token = storage.get('token') || ''
    this.userInfo = storage.get('userInfo') || null
    this.refreshPromise = null
  }

  // 设置token
  setToken(token) {
    this.token = token
    storage.set('token', token)
    
    // 设置全局数据
    const app = getApp()
    if (app) {
      app.globalData.token = token
    }
  }

  // 获取token
  getToken() {
    return this.token
  }

  // 设置用户信息
  setUserInfo(userInfo) {
    this.userInfo = userInfo
    storage.set('userInfo', userInfo)
    
    // 设置全局数据
    const app = getApp()
    if (app) {
      app.globalData.userInfo = userInfo
    }
  }

  // 获取用户信息
  getUserInfo() {
    return this.userInfo
  }

  // 检查是否已登录
  isLoggedIn() {
    return !!this.token && !!this.userInfo
  }

  // 登录
  async login(credentials) {
    try {
      const res = await request({
        url: API_ENDPOINTS.AUTH.LOGIN,
        method: 'POST',
        data: credentials
      })

      if (res.code === 200) {
        this.setToken(res.data.token)
        this.setUserInfo(res.data.userInfo)
        return res.data
      } else {
        throw new Error(res.message || '登录失败')
      }
    } catch (error) {
      console.error('登录失败：', error)
      throw error
    }
  }

  // 微信登录
  async wechatLogin(code) {
    try {
      const res = await request({
        url: API_ENDPOINTS.AUTH.WECHAT_LOGIN,
        method: 'POST',
        data: { code }
      })

      if (res.code === 200) {
        this.setToken(res.data.token)
        this.setUserInfo(res.data.userInfo)
        return res.data
      } else {
        throw new Error(res.message || '微信登录失败')
      }
    } catch (error) {
      console.error('微信登录失败：', error)
      throw error
    }
  }

  // 退出登录
  async logout() {
    try {
      // 调用退出登录接口
      if (this.token) {
        await request({
          url: API_ENDPOINTS.AUTH.LOGOUT,
          method: 'POST'
        })
      }
    } catch (error) {
      console.error('退出登录接口调用失败：', error)
    } finally {
      // 清除本地数据
      this.clearAuth()
    }
  }

  // 清除认证信息
  clearAuth() {
    this.token = ''
    this.userInfo = null
    storage.remove('token')
    storage.remove('userInfo')
    
    // 清除全局数据
    const app = getApp()
    if (app) {
      app.globalData.token = ''
      app.globalData.userInfo = null
    }
  }

  // 刷新token
  async refreshToken() {
    // 防止重复刷新
    if (this.refreshPromise) {
      return this.refreshPromise
    }

    this.refreshPromise = this._doRefreshToken()
    
    try {
      const result = await this.refreshPromise
      return result
    } finally {
      this.refreshPromise = null
    }
  }

  // 执行token刷新
  async _doRefreshToken() {
    try {
      const res = await request({
        url: API_ENDPOINTS.AUTH.REFRESH_TOKEN,
        method: 'POST',
        skipAuth: true // 跳过认证拦截
      })

      if (res.code === 200) {
        this.setToken(res.data.token)
        if (res.data.userInfo) {
          this.setUserInfo(res.data.userInfo)
        }
        return res.data
      } else {
        throw new Error(res.message || 'Token刷新失败')
      }
    } catch (error) {
      console.error('Token刷新失败：', error)
      // 刷新失败，清除认证信息
      this.clearAuth()
      throw error
    }
  }

  // 验证token有效性
  async validateToken() {
    if (!this.token) {
      return false
    }

    try {
      const res = await request({
        url: API_ENDPOINTS.AUTH.VALIDATE_TOKEN,
        method: 'POST'
      })

      return res.code === 200
    } catch (error) {
      console.error('Token验证失败：', error)
      return false
    }
  }

  // 检查登录状态并跳转
  checkLoginAndRedirect(redirectUrl = '/pages/auth/login') {
    if (!this.isLoggedIn()) {
      uni.navigateTo({
        url: redirectUrl
      })
      return false
    }
    return true
  }

  // 获取用户权限
  getUserPermissions() {
    if (!this.userInfo || !this.userInfo.permissions) {
      return []
    }
    return this.userInfo.permissions
  }

  // 检查用户权限
  hasPermission(permission) {
    const permissions = this.getUserPermissions()
    return permissions.includes(permission)
  }

  // 检查用户角色
  hasRole(role) {
    if (!this.userInfo || !this.userInfo.roles) {
      return false
    }
    return this.userInfo.roles.includes(role)
  }

  // 获取用户头像
  getUserAvatar() {
    if (!this.userInfo) {
      return '/static/images/default-avatar.png'
    }
    return this.userInfo.avatar || '/static/images/default-avatar.png'
  }

  // 获取用户昵称
  getUserNickname() {
    if (!this.userInfo) {
      return '未登录'
    }
    return this.userInfo.nickname || this.userInfo.phone || '用户'
  }

  // 更新用户信息
  async updateUserInfo(userInfo) {
    try {
      const res = await request({
        url: API_ENDPOINTS.USER.UPDATE_PROFILE,
        method: 'PUT',
        data: userInfo
      })

      if (res.code === 200) {
        this.setUserInfo(res.data)
        return res.data
      } else {
        throw new Error(res.message || '更新用户信息失败')
      }
    } catch (error) {
      console.error('更新用户信息失败：', error)
      throw error
    }
  }

  // 修改密码
  async changePassword(oldPassword, newPassword) {
    try {
      const res = await request({
        url: API_ENDPOINTS.AUTH.CHANGE_PASSWORD,
        method: 'POST',
        data: {
          oldPassword,
          newPassword
        }
      })

      if (res.code === 200) {
        return true
      } else {
        throw new Error(res.message || '修改密码失败')
      }
    } catch (error) {
      console.error('修改密码失败：', error)
      throw error
    }
  }

  // 重置密码
  async resetPassword(phone, code, newPassword) {
    try {
      const res = await request({
        url: API_ENDPOINTS.AUTH.RESET_PASSWORD,
        method: 'POST',
        data: {
          phone,
          code,
          newPassword
        }
      })

      if (res.code === 200) {
        return true
      } else {
        throw new Error(res.message || '重置密码失败')
      }
    } catch (error) {
      console.error('重置密码失败：', error)
      throw error
    }
  }

  // 发送验证码
  async sendVerificationCode(phone, type = 'login') {
    try {
      const res = await request({
        url: API_ENDPOINTS.AUTH.SEND_CODE,
        method: 'POST',
        data: {
          phone,
          type
        }
      })

      if (res.code === 200) {
        return true
      } else {
        throw new Error(res.message || '发送验证码失败')
      }
    } catch (error) {
      console.error('发送验证码失败：', error)
      throw error
    }
  }

  // 绑定手机号
  async bindPhone(phone, code) {
    try {
      const res = await request({
        url: API_ENDPOINTS.USER.BIND_PHONE,
        method: 'POST',
        data: {
          phone,
          code
        }
      })

      if (res.code === 200) {
        this.setUserInfo(res.data)
        return res.data
      } else {
        throw new Error(res.message || '绑定手机号失败')
      }
    } catch (error) {
      console.error('绑定手机号失败：', error)
      throw error
    }
  }

  // 上传头像
  async uploadAvatar(filePath) {
    try {
      const res = await uni.uploadFile({
        url: API_ENDPOINTS.USER.AVATAR_UPLOAD,
        filePath: filePath,
        name: 'avatar',
        header: {
          'Authorization': `Bearer ${this.token}`
        }
      })

      const data = JSON.parse(res.data)
      if (data.code === 200) {
        // 更新用户信息中的头像
        const updatedUserInfo = {
          ...this.userInfo,
          avatar: data.data.url
        }
        this.setUserInfo(updatedUserInfo)
        return data.data.url
      } else {
        throw new Error(data.message || '上传头像失败')
      }
    } catch (error) {
      console.error('上传头像失败：', error)
      throw error
    }
  }
}

// 创建认证实例
const auth = new Auth()

export default auth