import axios from 'axios'
import { ElMessage, ElLoading } from 'element-plus'
import router from '@/router'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 初始化时设置token
const token = localStorage.getItem('token')
if (token) {
  api.defaults.headers.common['Authorization'] = `Bearer ${token}`
}

// 请求拦截器
let loadingInstance = null
api.interceptors.request.use(
  (config) => {
    // 从localStorage获取token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    
    // 显示加载动画（可选）
    if (config.showLoading !== false) {
      loadingInstance = ElLoading.service({
        text: '加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
    }
    
    return config
  },
  (error) => {
    if (loadingInstance) {
      loadingInstance.close()
    }
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    if (loadingInstance) {
      loadingInstance.close()
    }
    return response
  },
  (error) => {
    if (loadingInstance) {
      loadingInstance.close()
    }
    
    // 处理不同的错误状态码
    if (error.response) {
      const { status, data } = error.response
      
      switch (status) {
        case 401:
          // 未授权，清除token并根据当前路由跳转到相应的登录页
          localStorage.removeItem('token')
          localStorage.removeItem('agentInfo') // 清除代理信息
          delete api.defaults.headers.common['Authorization']
          
          // 判断当前是否在代理相关页面
          const currentPath = router.currentRoute.value.path
          if (currentPath.startsWith('/agent')) {
            router.push('/agent/mylogin')
            ElMessage.error('代理登录已过期，请重新登录')
          } else {
            router.push({ name: 'MyLogin' })
            ElMessage.error('登录已过期，请重新登录')
          }
          break
          
        case 403:
          // 检查是否是用户被拉黑
          if (data.code === 'USER_BLACKLISTED') {
            // 清除token并跳转到登录页
            localStorage.removeItem('token')
            delete api.defaults.headers.common['Authorization']
            router.push({ name: 'MyLogin' })
            ElMessage.error(data.message || '账户已被拉黑，请联系管理员')
          } else if (data.code === 'PAYMENT_REQUIRED') {
            // 需要支付，跳转到支付页面
            // 只在不是支付页面时才跳转和显示消息，避免重复通知
            if (router.currentRoute.value.name !== 'Payment') {
              router.push({ name: 'Payment' })
              ElMessage.warning(data.message || '您的账户尚未激活，请完成支付后再使用')
            }
          } else {
            ElMessage.error(data.message || '权限不足')
          }
          break
          
        case 404:
          ElMessage.error(data.message || '请求的资源不存在')
          break
          
        case 422:
          ElMessage.error(data.message || '请求参数错误')
          break
          
        case 429:
          ElMessage.error('请求过于频繁，请稍后再试')
          break
          
        case 500:
          ElMessage.error('服务器内部错误')
          break
          
        case 400:
          // 处理业务逻辑错误（如坏账等）
          ElMessage.error(data.error?.message || data.message || '请求失败')
          break
          
        default:
          ElMessage.error(data.error?.message || data.message || '请求失败')
      }
    } else if (error.request) {
      // 网络错误
      ElMessage.error('网络连接失败，请检查网络设置')
    } else {
      // 其他错误
      ElMessage.error('请求配置错误')
    }
    
    return Promise.reject(error)
  }
)

// 封装常用的请求方法
export const request = {
  get: (url, config = {}) => api.get(url, config),
  post: (url, data = {}, config = {}) => api.post(url, data, config),
  put: (url, data = {}, config = {}) => api.put(url, data, config),
  delete: (url, config = {}) => api.delete(url, config),
  patch: (url, data = {}, config = {}) => api.patch(url, data, config)
}



// 用户相关API
export const userAPI = {
  // 获取用户列表
  getList: (params = {}) => request.get('/users', { params }),
  
  // 获取用户详情
  getDetail: (id) => request.get(`/users/${id}`),
  
  // 更新用户信息
  update: (id, data) => request.put(`/users/${id}`, data),
  
  // 删除用户
  delete: (id) => request.delete(`/users/${id}`),
  
  // 获取用户统计
  getStats: () => request.get('/users/stats/overview')
}

// 认证相关API
export const authAPI = {
  // 登录
  login: (data) => request.post('/auth/login', data),
  
  // 注册
  register: (data) => request.post('/auth/register', data),
  
  // 获取当前用户信息
  me: () => request.get('/auth/me'),
  
  // 修改密码
  changePassword: (data) => request.put('/auth/change-password', data)
}

// 验证码相关API
export const captchaAPI = {
  // 生成验证码
  generate: () => request.get('/captcha/generate'),
  
  // 验证验证码
  verify: (data) => request.post('/captcha/verify', data)
}

// 文件上传API
export const uploadAPI = {
  // 上传图片
  uploadImage: (file) => {
    const formData = new FormData()
    formData.append('image', file)
    return request.post('/upload/image', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 上传文件
  uploadFile: (file) => {
    const formData = new FormData()
    formData.append('file', file)
    return request.post('/upload/file', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  }
}

// 支付相关API
export const paymentAPI = {
  // 获取支付方式
  getMethods: () => request.get('/payment/methods'),
  
  // 创建支付订单
  createOrder: (data) => request.post('/payment/create-order', data),
  
  // 查询支付状态
  queryStatus: (outTradeNo) => request.get(`/payment/query-status/${outTradeNo}`),
  
  // 获取支付记录
  getOrders: (params = {}) => request.get('/payment/orders', { params })
}

// 转账相关API
export const transferAPI = {
  // 获取公户信息
  getPublicAccount: () => request.get('/transfers/public-account'),
  
  // 创建转账记录
  create: (data) => {
    const formData = new FormData()
    Object.keys(data).forEach(key => {
      formData.append(key, data[key])
    })
    return request.post('/transfers', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 确认转账
  confirm: (id) => request.put(`/transfers/${id}/confirm`),
  
  // 拒绝转账
  reject: (id) => request.put(`/transfers/${id}/reject`),
  
  // 确认收款
  confirmReceived: (id) => request.post('/transfers/confirm-received', { transfer_id: id }),
  
  // 确认未收到款
  confirmNotReceived: (id) => request.post('/transfers/confirm-not-received', { transfer_id: id }),
  
  // 获取用户转账记录
  getUserTransfers: (params = {}) => request.get('/transfers/user', { params }),
  
  // 获取指定用户的转账记录
  getUserTransfersByUserId: (userId, params = {}) => request.get(`/transfers/user/${userId}`, { params }),
  
  // 获取待确认转账
  getPendingTransfers: (params = {}) => request.get('/transfers/pending', { params }),
  
  // 获取用户账户信息
  getUserAccount: () => request.get('/transfers/account'),
  
  // 获取转账列表（管理员）
  getList: (params = {}) => request.get('/transfers', { params }),
  
  // 获取转账统计
  getStats: () => request.get('/transfers/stats')
}

export default api