import {get, post} from '../utils/http.js'

/**
 * 获取团队成员列表
 * @param {string} teamId - 团队ID
 * @param {object} params - 可选参数，包含lastId等分页参数
 * @returns {Promise}
 */
export const getTeamMembers = async (teamId, params = {}) => {
  try {
    // 构建查询参数
    const queryParams = new URLSearchParams({ id: teamId })
    console.log('params', queryParams)
    // 添加分页参数
    if (params.lastId) {
      queryParams.append('lastId', params.lastId)
    }

    const response = await get(`/team/members?${queryParams.toString()}`)
    return response
  } catch (error) {
    console.error('Failed to fetch team members:', error)
    throw error
  }
}

/**
 * 获取BD代理商列表
 * @param {object} params - 可选参数，包含lastId等分页参数
 * @returns {Promise}
 */
export const getBdAgentList = async (params = {}) => {
  try {
    // 构建查询参数
    const queryParams = new URLSearchParams()
    
    // 添加分页参数
    if (params.lastId) {
      queryParams.append('lastId', params.lastId)
    }
    
    const url = queryParams.toString() 
      ? `/team/bd/bd-agent/list?${queryParams.toString()}`
      : '/team/bd/bd-agent/list'
      
    const response = await get(url)
    return response
  } catch (error) {
    console.error('Failed to fetch BD agent list:', error)
    throw error
  }
}

/**
 * 删除团队成员
 * @param {string} memberId - 成员ID
 * @returns {Promise}
 */
export const deleteMember = async (ids) => {
  try {
    const response = await post('/team-member/client/removeMemberTeam', {
      ids: ids
    })
    return response
  } catch (error) {
    console.error('Failed to delete member:', error)
    throw error
  }
}

/**
 * 获取团队发布的政策
 * @param {string} teamId - 团队ID
 * @returns {Promise}
 */
export const getTeamReleasePolicy = async (teamId) => {
  try {
    const response = await get(`/team/release/policy?id=${teamId}`)
    return response
  } catch (error) {
    console.error('Failed to fetch team release policy:', error)
    throw error
  }
}

/**
 * 获取用户等待申请的团队信息
 * @returns {Promise}
 */
export const getUserSendJoinWaitApplyTeamProfile = async () => {
  try {
    const response = await get('/team/wait-apply/profile')
    return response
  } catch (error) {
    console.error('Failed to get user wait apply team profile:', error)
    throw error
  }
}

/**
 * 搜索团队信息
 * @param {string} account - 团队账户
 * @returns {Promise}
 */
export const searchTeamByAccount = async (account) => {
  try {
    const response = await get(`/team/search-account?account=${account}`)
    return response
  } catch (error) {
    console.error('Failed to search team by account:', error)
    throw error
  }
}

/**
 * 提交团队申请
 * @param {string} teamId - 团队ID
 * @returns {Promise}
 */
export const sendTeamApplyJoin = async (teamId) => {
  try {
    const response = await post('/team/user/apply', {
      teamId,
      reason: 'JOIN'
    })
    return response
  } catch (error) {
    console.error('Failed to send team apply join:', error)
    throw error
  }
}

/**
 * 取消加入申请
 * @param {string} messageId - 申请消息ID
 * @returns {Promise}
 */
export const cancelJoinApplyById = async (messageId) => {
  try {
    const response = await post('/team/user/join-apply-cancel', {
      id: messageId
    })
    return response
  } catch (error) {
    console.error('Failed to cancel join apply:', error)
    throw error
  }
}

/**
 * 获取邀请消息列表
 * @returns {Promise}
 */
export const getInviteMessageList = async () => {
  try {
    const response = await get('/anchor-agent/invite/message')
    return response
  } catch (error) {
    console.error('Failed to get invite message list:', error)
    throw error
  }
}

/**
 * 处理邀请消息
 * @param {object} data - 处理数据 {id, status, contact}
 * @returns {Promise}
 */
export const processInviteMessage = async (data) => {
  try {
    const response = await post('/anchor-agent/invite/process', data)
    return response
  } catch (error) {
    console.error('Failed to process invite message:', error)
    throw error
  }
}

/**
 * 获取团队账单列表
 * @param {string} teamId - 团队ID
 * @returns {Promise}
 */
export const getTeamBill = async (teamId) => {
  try {
    const response = await get(`/team/bill?id=${teamId}`)
    return response
  } catch (error) {
    console.error('Failed to fetch team bill:', error)
    throw error
  }
}

/**
 * 获取团队账单的工资成员信息
 * @param {string} billId - 账单ID
 * @returns {Promise}
 */
export const getTeamBillWorkMembers = async (billId) => {
  try {
    const response = await get(`/team/bill/work-members?id=${billId}`)
    return response
  } catch (error) {
    console.error('Failed to fetch team bill work members:', error)
    throw error
  }
}

/**
 * 获取团队成员工作报告
 * @param {string} userId - 用户ID
 * @returns {Promise}
 */
export const getTeamMemberWork = async (userId) => {
  try {
    return await get(`/team/member-work?userId=${userId}`)
  } catch (error) {
    console.error('Failed to fetch team member work:', error)
    throw error
  }
}

/**
 * 用户申请记录查询
 */
export function getApplyRecord(userId, status) {
  return get(`/team/user/apply/record?teamId=${userId}&status=${status}`)
}

/**
 * BD团队当月总目标
 */
export function getAgentMonthTarget() {
  return get(`/team/bd/agent-count`)
}

/**
 * BD团队上个月总目标
 */
export function getAgentMonthLastTarget() {
  return get(`/team/bd/agent-count-last`)
}

/**
 * 获取团队的成员数量
 * @param teamId
 * @returns {Promise}
 */
export function getTeamMemberCount(teamId) {
  return get(`/team/members/count?id=${teamId}`)
}

/**
 * 格式化显示状态
 * @param {string} status - 状态值
 * @returns {object} 包含显示文本和样式类的对象
 */
export const formatBillStatus = (status) => {
  const statusMap = {
    'UNPAID': {
      text: 'In Progress',
      class: 'in-progress',
      color: '#3B82F6'
    },
    'HANG_UP': {
      text: 'Pending',
      class: 'pending',
      color: '#EF4444'
    },
    'PAY_OUT': {
      text: 'Completed',
      class: 'completed',
      color: '#10B981'
    },
    'PAID': {
      text: 'Completed',
      class: 'completed',
      color: '#10B981'
    },
    'SETTLED': {
      text: 'Settled',
      class: 'settled',
      color: '#059669'
    }
  }

  return statusMap[status] || {
    text: status,
    class: 'unknown',
    color: '#666'
  }
}

/**
 * 格式化时间显示
 * @param {number|string} minutes - 分钟数
 * @returns {string} 格式化的时间字符串
 */
export const formatOnlineTime = (minutes) => {
  if (!minutes || minutes === '0') return '0h'
  const numMinutes = parseInt(minutes)
  const hours = Math.floor(numMinutes / 60)
  const mins = numMinutes % 60
  if (hours > 0) {
    return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`
  }
  return `${mins}m`
}

/**
 * 格式化礼物价值显示
 * @param {string|number} value - 礼物价值
 * @returns {string} 格式化的价值字符串
 */
export const formatGiftValue = (value) => {
  if (!value || value === '0') return '$0'

  // 如果已经是格式化的字符串，直接返回
  if (typeof value === 'string' && value.includes('K')) {
    return `$${value}`
  }

  const numValue = parseFloat(value)
  if (isNaN(numValue)) return '$0'

  if (numValue >= 1000000) {
    return `$${(numValue / 1000000).toFixed(1)}M`
  } else if (numValue >= 1000) {
    return `$${(numValue / 1000).toFixed(1)}K`
  }
  return `$${numValue.toFixed(0)}`
}

/**
 * 格式化钻石价值显示
 * @param {string|number} value - 钻石价值
 * @returns {string} 格式化的钻石价值字符串
 */
export const formatDiamondValue = (value) => {
  if (!value || value === '0') return '0'
  const numValue = parseInt(value)
  if (isNaN(numValue)) return '0'

  if (numValue >= 1000000) {
    return `${(numValue / 1000000).toFixed(1)}M`
  } else if (numValue >= 1000) {
    return `${(numValue / 1000).toFixed(1)}K`
  }
  return numValue.toLocaleString()
}

/**
 * 格式化日期显示
 * @param {number} dateNumber - 日期数字格式 (如: 20250808)
 * @returns {string} 格式化的日期字符串
 */
export const formatDateDisplay = (dateNumber) => {
  if (!dateNumber) return ''
  const dateStr = dateNumber.toString()
  if (dateStr.length !== 8) return dateStr

  const year = dateStr.substring(0, 4)
  const month = dateStr.substring(4, 6)
  const day = dateStr.substring(6, 8)
  return `${month}/${day}/${year}`
}

/**
 * 格式化账户显示
 * @param {object} memberProfile - 成员资料对象
 * @returns {string} 格式化的账户字符串
 */
export const formatAccount = (memberProfile) => {
  if (!memberProfile) return ''

  // 如果有特殊ID，优先显示特殊ID
  if (memberProfile.ownSpecialId && memberProfile.ownSpecialId.account) {
    return memberProfile.ownSpecialId.account
  }

  // 否则显示普通账户
  return memberProfile.account || ''
}

/**
 * 检查是否可以领取道具奖励
 * @param {object} item - 账单项目
 * @returns {boolean} 是否可以领取奖励
 */
export const canReceivePropsReward = (item) => {
  if (item.status !== 'SETTLED') {
    return false
  }

  if (!item.target || !item.target.settlementResult) {
    return false
  }

  const propsRewards = item.target.settlementResult.propsRewards
  if (!propsRewards || propsRewards.length <= 0) {
    return false
  }

  return true
}

/**
 * 领取政策道具奖励
 * @param {string} targetId - 目标ID
 * @returns {Promise}
 */
export const receivePolicyPropsReward = async (targetId) => {
  try {
    const response = await post('/team/policy-props-reward', {
      id: targetId
    })
    return response
  } catch (error) {
    console.error('Failed to receive policy props reward:', error)
    throw error
  }
}
