import api from './index.js'

/**
 * 用户相关API接口
 */

// 获取当前用户信息
export const getCurrentUser = () => {
  return api.get('/auth/me').catch(error => {
    // 记录详细的错误信息用于调试
    console.error('getCurrentUser API 错误:', error)
    
    // 检查是否是500错误且是/me接口
    if (error.response && error.response.status === 500) {
      console.error('/me接口返回500错误，错误详情:', error.response.data)
      // 注意：这里不需要再次处理，因为在api/index.js的响应拦截器中已经处理了
    }
    
    // 继续抛出错误，让调用者能够捕获和处理
    throw error
  })
}

// 更新用户信息（包括头像）
export const updateUserProfile = (data) => {
  return api.put('/auth/profile', data)
}

// 修改用户名
export const updateUsername = (data) => {
  return api.put('name', data)
}

// 修改密码
export const updatePassword = (data) => {
  return api.put('/password', data)
}

// 发起实名认证
export const initiateVerification = () => {
  return api.post('/verify/initiate')
}

// 查询实名认证状态
export const getVerificationStatus = () => {
  return api.get('/verify/status')
}

// 获取用户实名认证信息
export const getRealIdentity = () => {
  return api.get('/auth/real-identity')
}

// 更新用户实名认证信息 - 接入阿里云身份认证服务
export const updateRealIdentity = (data) => {
  // 参数映射：将realUsername映射为realName以匹配新接口要求
  const requestData = {
    realName: data.realUsername || data.realName,
    idNumber: data.idNumber
  }
  
  // 调用新的身份认证接口
  return api.post('/identity/verify', requestData)
}

// 验证密码
export const verifyPassword = (data) => {
  return api.post('/auth/verify-password', data)
}

// 修改密码
export const changePassword = (data) => {
  return api.put('/auth/password', data)
}

// 获取我的内容收益列表
export const getMyContentRevenue = (params = {}) => {
  return api.get('/content-revenue/my', { params })
}

// 获取我的推广提成列表
export const getMyPromotionCommission = (params = {}) => {
  return api.get('/promotion-commission/my', { params })
}

/**
 * API密钥管理相关接口
 */

// 生成API密钥
export const generateApiKey = () => {
  return api.post('/v1/api-key/generate')
}

// 刷新API密钥
export const refreshApiKey = () => {
  return api.post('/v1/api-key/refresh')
}

// 删除API密钥
export const deleteApiKey = () => {
  return api.delete('/v1/api-key/delete')
}

// 获取API密钥信息
export const getApiKeyInfo = () => {
  return api.get('/v1/api-key/info')
}

// 验证API密钥
export const validateApiKey = (keyValue) => {
  return api.post('/v1/api-key/validate', { keyValue })
}

/**
 * 礼品码兑换相关接口
 */

// 兑换礼品码
export const redeemGiftCode = (code) => {
  return api.post('/gift/redeem', { code })
}

/**
 * 收藏相关接口
 */

// 获取用户收藏统计信息
export const getUserFavoritesStats = () => {
  return api.get('/video-likes/stats')
}

// 获取用户收藏的工作流列表
export const getUserFavoriteWorkflows = (params = {}) => {
  return api.get('/v1/workflow-likes/user', { params })
}

// 获取用户收藏的视频列表
export const getUserFavoriteVideos = (params = {}) => {
  return api.get('/course/favorited', { params })
}

// 切换工作流收藏状态
export const toggleWorkflowFavorite = (workflowId) => {
  return api.post('/v1/workflow-likes/toggle', { workflowId })
}

// 切换视频收藏状态
export const toggleVideoFavorite = (videoId) => {
  return api.post('/v1/video-likes/toggle', { videoId })
}

// 切换课程收藏状态
export const toggleCourseFavorite = (courseId) => {
  return api.post(`/course/${courseId}/favorite`)
} 

/**
 * 订单相关接口
 */

// 获取用户订单列表
export const getUserOrders = (params = {}) => {
  return api.get('/v1/orders', { params })
} 

/**
 * 推广相关接口
 */

// 获取我的粉丝列表
export const getMyFans = (params = {}) => {
  return api.get('/promotion/fans', { params })
}

// 生成邀请码
export const generateInviteCode = () => {
  return api.post('/promotion/generate-invite-code')
}

// 获取我的推广信息
export const getMyPromotionInfo = () => {
  return api.get('/promotion/my')
}

// 获取推广规则
export const getPromotionRules = () => {
  return api.get('/v1/promotion-rules')
} 

/**
 * 积分相关接口
 */

// 获取用户积分和消费余额
export const getUserPointsBalance = () => {
  return api.get('/points/consumption/balance')
}

/**
 * 余额相关接口
 */

// 获取用户余额信息
export const getUserBalance = () => {
  return api.get('/balance')
}

// 获取余额增加明细
export const getBalanceIncomeDetail = () => {
  return api.get('/balance/income-detail')
}

// 获取余额变动记录
export const getBalanceLogs = (params = {}) => {
  return api.get('/balance/logs', { params })
}

// 获取余额统计信息
export const getBalanceStats = () => {
  return api.get('/balance/stats')
}

/**
 * 提现相关接口
 */

// 获取用户收益信息（旧接口，保持兼容性）
export const getUserRevenue = () => {
  return api.get('/withdraw/revenue')
}

// 获取基础收益信息
export const getBasicRevenue = () => {
  return api.get('/withdraw/revenue/basic')
}

// 获取工作流收益详情
export const getWorkflowRevenue = (params = {}) => {
  return api.get('/withdraw/revenue/workflows', { params })
}

// 获取视频收益详情
export const getVideoRevenue = (params = {}) => {
  return api.get('/withdraw/revenue/videos', { params })
}

// 获取推广收益信息
export const getPromotionRevenue = () => {
  return api.get('/withdraw/revenue/promotion')
}

// 获取提现任务列表
export const getWithdrawList = (params = {}) => {
  return api.get('/withdraw/list', { params })
}

// 提交提现申请
export const submitWithdraw = (data) => {
  return api.post('/withdraw/submit', data)
}

/**
 * 会员套餐相关接口
 */

// 获取会员套餐详情列表
export const getMembershipPlans = () => {
  return api.get('/membership/plans')
}

// 创建会员购买订单
export const createMembershipOrder = (data) => {
  return api.post('/membership/purchase', data)
}

// 生成微信支付二维码
export const createWechatPayment = (data) => {
  return api.post('/pay/placeOrder', data)
}

// 查询支付状态
export const queryPaymentStatus = (data) => {
  return api.post('/pay/orderQuery', data)
}

// 激活免费套餐
export const activateFreePlan = (planId) => {
  return api.post('/membership/activate-free', { planId })
}

// 关闭订单
export const closeOrder = (orderNo) => {
  return api.post('/pay/closeOrder', { orderNo })
}

/**
 * 微信绑定相关接口
 */

// 获取微信绑定二维码
export const getWechatBindQR = () => {
  return api.post('/wechat/qr/bind')
}

// 检查微信绑定状态
export const checkWechatBindStatus = (sceneStr) => {
  return api.post(`/wechat/bind/check?sceneStr=${sceneStr}`)
}

// 获取用户课程分类
export const getUserCourseCategories = () => {
  return api.get('/categories/course')
}

// 获取用户工作流分类
export const getUserWorkflowCategories = () => {
  return api.get('/categories/workflow')
}

/**
 * 企业微信二维码相关接口
 */

// 获取企业微信二维码列表
export const getWechatQRList = () => {
  return api.get('/wechat-qr/list')
}

/**
 * 推广海报相关接口
 */

// 获取所有启用的推广海报
export const getPromotionPosters = () => {
  return api.get('/promotion-poster/list')
}

/**
 * UV统计相关接口
 */

// 记录UV数据
export const recordUVData = (pageData = {}) => {
  const data = {
    page: pageData.page || window.location.pathname,
    referrer: pageData.referrer || document.referrer,
    ...pageData
  }
  
  return api.post('/uv/record', data, {
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    // 将数据转换为URLSearchParams格式
    transformRequest: [function (data) {
      return new URLSearchParams(data).toString()
    }]
  })
}