// API 请求相关 mixin
import $http from '@/utils/https'

export default {
  data() {
    return {
      requestLoading: false,
      requestError: null
    }
  },
  
  methods: {
    // 通用 API 请求方法
    async apiRequest(config) {
      this.requestLoading = true
      this.requestError = null
      
      try {
        const response = await $http(config)
        return response
      } catch (error) {
        this.requestError = error
        this.handleApiError(error)
        throw error
      } finally {
        this.requestLoading = false
      }
    },
    
    // GET 请求
    async apiGet(url, params = {}) {
      return this.apiRequest({
        url,
        method: 'GET',
        data: params
      })
    },
    
    // POST 请求
    async apiPost(url, data = {}) {
      return this.apiRequest({
        url,
        method: 'POST',
        data
      })
    },
    
    // PUT 请求
    async apiPut(url, data = {}) {
      return this.apiRequest({
        url,
        method: 'PUT',
        data
      })
    },
    
    // DELETE 请求
    async apiDelete(url, params = {}) {
      return this.apiRequest({
        url,
        method: 'DELETE',
        data: params
      })
    },
    
    // 处理 API 错误
    handleApiError(error) {
      console.error('API Error:', error)
      
      let message = '请求失败'
      
      if (error.response) {
        // 服务器响应错误
        const { status, data } = error.response
        switch (status) {
          case 400:
            message = data.message || '请求参数错误'
            break
          case 401:
            message = '未授权，请重新登录'
            this.handleUnauthorized()
            break
          case 403:
            message = '权限不足'
            break
          case 404:
            message = '请求的资源不存在'
            break
          case 500:
            message = '服务器内部错误'
            break
          default:
            message = data.message || `请求失败 (${status})`
        }
      } else if (error.request) {
        // 网络错误
        message = '网络连接失败，请检查网络'
      }
      
      uni.showToast({
        title: message,
        icon: 'none',
        duration: 2000
      })
    },
    
    // 处理未授权情况
    handleUnauthorized() {
      // 清除用户信息
      uni.removeStorageSync('userData')
      uni.removeStorageSync('token')
      
      // 跳转到登录页
      uni.reLaunch({
        url: '/pages/login/login'
      })
    },
    
    // 上传文件
    async uploadFile(filePath, name = 'file', formData = {}) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: 'your-upload-url', // 替换为实际的上传地址
          filePath,
          name,
          formData,
          success: (res) => {
            try {
              const data = JSON.parse(res.data)
              resolve(data)
            } catch (error) {
              reject(new Error('上传响应解析失败'))
            }
          },
          fail: (error) => {
            reject(error)
          }
        })
      })
    }
  }
}
