import api from './index'

/**
 * 获取积分套餐列表
 * @returns {Promise<any>}
 */
export const getPointsPackages = () => {
  return api.get('/points/packages')
}

/**
 * 创建积分充值订单
 * @param {Object} data 充值订单数据
 * @param {number} data.packageId 套餐ID
 * @param {number} data.paymentMethod 支付方式 (1: 支付宝, 2: 微信)
 * @param {boolean} data.useBalance 是否使用余额
 * @param {string} data.openid 微信openid (微信支付时必填)
 * @param {string} data.tradeType 交易类型 ( APP: APP支付, NATIVE: 扫码支付)
 * @returns {Promise<any>}
 */
export const createRechargeOrder = (data) => {
  return api.post('/points/recharge', data)
}

/**
 * 获取用户积分充值记录
 * @param {Object} params 查询参数
 * @param {number} params.page 页码
 * @param {number} params.size 每页数量
 * @returns {Promise<any>}
 */
export const getRechargeRecords = async (params) => {
  try {
    const response = await api.get('/points/recharge/records', { params })
    
    if (response.code === 200 && response.data) {
      // 处理状态映射：将"待支付"改为"已关闭"
      const processedData = response.data.map(record => ({
        ...record,
        statusName: record.statusName === '待支付' ? '已关闭' : record.statusName
      }))
      
      return {
        ...response,
        data: processedData
      }
    }
    
    return response
  } catch (error) {
    throw error
  }
}

/**
 * 获取用户积分消耗记录
 * @param {Object} params 查询参数
 * @param {number} params.page 页码
 * @param {number} params.size 每页数量
 * @param {string} params.changeType 变化类型 (consume: 消费)
 * @returns {Promise<any>}
 */
export const getConsumptionLogs = async (params) => {
  try {
    const response = await api.get('/points/consumption/logs', { params })
    
    if (response.code === 200 && response.data) {
      // 处理积分变化显示：负数显示为消费
      const processedData = {
        ...response.data,
        records: response.data.records.map(record => ({
          ...record,
          // 确保changeAmount为负数时显示为消费
          changeAmount: Math.abs(record.changeAmount),
          changeTypeName: record.changeAmount < 0 ? '消费' : record.changeTypeName
        }))
      }
      
      return {
        ...response,
        data: processedData
      }
    }
    
    return response
  } catch (error) {
    throw error
  }
}

