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

/**
 * 获取钱包流水详情
 * @returns {Promise} 返回流水详情数据
 */
export function getWalletDetails() {
  return get('/wallet/bank/balance/water/details')
}

/**
 * 获取银行余额
 * @returns {Promise} 返回银行余额数据
 */
export function getBankBalance() {
  return get('/wallet/bank/balance')
}

/**
 * 转账角色检查
 * @returns {Promise} 返回用户角色和权限信息
 */
export function userBankCheckTransfer() {
  return get('/wallet/bank/check/transfer')
}

/**
 * 验证兑换金币限制
 * @returns {Promise} 返回用户角色和权限信息
 */
export function userSalaryCheckExchange() {
  return get('/wallet/bank/check/exchange-gold')
}

// 获取用户银行卡余额-兑换金币
export function userBankExchangeGold(data) {
  return post('/wallet/bank/exchange/gold', data)
}

// 用户银行卡余额-转账到金币
export function userBankTransfer(data) {
  return post('/wallet/bank/transferGold', data)
}

/**
 * 搜索用户资料
 * @param {string} type - 用户类型 (AGENT/BD/ANCHOR)
 * @param {string} account - 用户账号/ID
 * @param {string} searchType - 搜索类型
 * @returns {Promise} 返回用户资料
 */
export function userBankSearchUserProfile(account, searchType = '') {
  if (searchType == '') {
    return get(`/wallet/bank/search/user-profile?account=${account}&type=AGENT`)
  } else {
    return get(
      `/wallet/bank/search/user-profile?account=${account}&type=AGENT&searchType=${searchType}`,
    )
  }
}

/**
 * 获取用户身份信息
 * @param {string} userId - 用户ID
 * @returns {Promise} 返回用户身份权限信息
 */
export function getUserIdentity() {
  return get(`/app/h5/identity`)
}

/**
 * 获取团队入口信息
 * @returns {Promise} 返回团队和用户信息
 */
export function getTeamEntry() {
  return get('/team/entry')
}

/**
 * 获取用户信息(仅用户信息)
 */
export function getMemberProfile() {
  return get('/team/member/profile')
}

// 获取用户所在的区域信息
export const getRegionByUserId = async (userId) => {
  try {
    const response = await get(`/region-config/client/getRegionByUserId?userId=${userId}`)
    return response
  } catch (error) {
    console.error('Failed to fetch get region of userId:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

/**
 * 校验金币销售商权限
 * @returns {Promise} 返回是否具有销售商权限
 */
export function checkFreightDealer() {
  return get('/wallet/freight/seller/check/dealer')
}

/**
 * 获取金币销售商余额
 * @returns {Promise} 返回销售商金币余额
 */
export function getFreightBalance() {
  return get('/wallet/freight/balance')
}

/**
 * 搜索用户
 * @param {string} account - 用户账号
 * @returns {Promise} 返回用户信息
 */
export function searchFreightUser(account) {
  return get(`/wallet/freight/search-user?account=${account}`)
}

/**
 * 经销商搜索已有 coin seller
 * @param {string} account - 用户账号
 * @returns {Promise} 返回 coin seller 用户信息
 */
export function searchDealerFreightUser(account) {
  return get(`/wallet/freight/dealer/search-user?account=${account}`)
}

/**
 * 金币充值
 * @param {Object} data - 充值数据
 * @param {number} data.acceptUserId - 接收用户ID
 * @param {number} data.quantity - 充值数量
 * @returns {Promise} 返回剩余可用余额
 */
export function freightRecharge(data) {
  return post('/wallet/freight/ship', data)
}

/**
 * 获取当前超级经销商的子 coin seller 列表
 * @returns {Promise} 返回子 coin seller 列表
 */
export function getFreightSubSellers() {
  return get('/wallet/freight/super/sub-sellers')
}

/**
 * 绑定已有 coin seller 为当前超级经销商的子 coin seller
 * @param {Object} data
 * @param {number|string} data.userId - 子 coin seller 用户ID
 * @returns {Promise}
 */
export function addFreightSubSeller(data) {
  return post('/wallet/freight/super/sub-sellers', data)
}

/**
 * 从当前超级经销商币商钱包转账给子 coin seller 币商钱包
 * @param {Object} data
 * @param {number|string} data.acceptUserId - 子 coin seller 用户ID
 * @param {number|string} data.quantity - 转账金币数量
 * @returns {Promise} 返回当前超级经销商剩余余额
 */
export function transferFreightSubSeller(data) {
  return post('/wallet/freight/super/sub-sellers/transfer', data)
}

/**
 * 获取金币交易流水
 * @param {string} data
 * @returns {Promise} 返回交易流水记录
 */
export const getFreightWaterFlow = async (data) => {
  try {
    const response = await get(
      `/wallet/freight/balance/running/water/client/flowByUserId?userId=${data.userId}&type=${data.type}&searchId=${data.searchId}&lastId=${data.lastId}`,
    )
    return response
  } catch (error) {
    console.error('Failed to fetch bank card list:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

/**
 * 根据账号搜索团队
 * @param {string} account - 代理账号
 * @returns {Promise} 返回团队信息
 */
export function searchTeamByAccount(account) {
  return get(`/team/search-account?account=${account}`)
}

/**
 * 发送加入团队申请
 * @param {Object} data - 申请数据
 * @param {string} data.teamId - 团队ID
 * @param {string} data.reason - 申请原因
 * @returns {Promise} 返回申请结果
 */
export function sendTeamApplyJoin(data) {
  return post('/team/user/apply', data)
}

/**
 * 获取团队申请记录
 * @param {string} teamId - 团队ID
 * @param {string} status - 状态 (WAIT/AGREE/REJECT)
 * @returns {Promise} 返回申请记录列表
 */
export function getTeamApplyRecord(teamId, status) {
  return get(`/team/user/apply/record?teamId=${teamId}&status=${status}`)
}

/**
 * 获取自己的申请记录
 * @returns {Promise} 返回申请记录列表
 */
export function getWaitApplyRecord() {
  return get('/team/wait-apply/profile')
}

/**
 * 撤销申请
 * @param {string} applyId - 申请ID
 * @returns {Promise} 返回撤销结果
 */
export function cancelApply(id) {
  return post('/team/user/join-apply-cancel', { id })
}

/**
 * 处理申请（同意/拒绝）
 * @param {Object} data - 处理数据
 * @param {string} data.id - 申请记录ID
 * @param {string} data.status - 审核状态 (AGREE/REJECT)
 * @returns {Promise} 返回处理结果
 */
export function processUserApply(data) {
  return post('/team/process/user/apply', data)
}

/**
 * 获取团队成员工作统计
 * @returns {Promise} 返回工作统计数据
 */
export function getTeamMemberWorkStatistics(dataType, memberId) {
  return get(`/team/member/work/statistics-now?dataType=${dataType}&memberId=${memberId}`)
}

/**
 * 格式化时间戳为可读格式
 * @param {number} timestamp - 时间戳（毫秒）
 * @returns {string} 格式化后的时间字符串
 */
export function formatDateTime(timestamp) {
  const date = new Date(timestamp)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')

  return `${day}/${month}/${year} ${hours}:${minutes}`
}

/**
 * 格式化事件描述
 * @param {string} eventDescribe - 原始事件描述
 * @returns {string} 格式化后的事件描述
 */
export function formatEventDescribe(eventDescribe) {
  // 移除 [system] 前缀并简化描述
  return eventDescribe
    .replace(/^\[system\]\s*/i, '[System] ')
    .replace(/Settlement Agent Salary/i, 'Create An Account')
    .replace(/Settlement Member salary/i, 'Transfer')
}

// 获取累积充值信息
export const getTotalRecharge = async (userId) => {
  try {
    const response = await get(`/user/count/total-recharge?userId=${userId}`)
    return response
  } catch (error) {
    console.error('Failed to fetch total recharge:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

// 获取提现方式列表
export const getWithdrawalWays = async () => {
  try {
    const response = await get(`/wallet/bank/withdrawal_ways`)
    return response
  } catch (error) {
    console.error('Failed to fetch withdrawal ways:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

// 根据用户ID获取银行卡列表
export const getBankCardList = async () => {
  try {
    const response = await get(`/wallet/bank-card/list`)
    return response
  } catch (error) {
    console.error('Failed to fetch bank card list:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

// 添加用户银行卡
export const addBankCard = async (data) => {
  try {
    const response = await post(`/wallet/bank-card/add`, data)
    return response
  } catch (error) {
    console.error('Failed to add bank card:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

// 根据卡片ID删除银行卡
export const deleteBankCard = async (data) => {
  try {
    const response = await post(`/wallet/bank-card/delete`, data)
    return response
  } catch (error) {
    console.error('Failed to delete bank card:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

// 使用银行卡
export const useBankCard = async (data) => {
  try {
    const response = await post(`/wallet/bank-card/use`, data)
    return response
  } catch (error) {
    console.error('Failed to use bank card:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

// 根据用户ID获取提现信息列表
export const getWithdrawInfoList = async () => {
  try {
    const response = await get(`/wallet/withdraw-info/list`)
    return response
  } catch (error) {
    console.error('Failed to fetch withdraw info list:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

// 添加用户提现信息
export const addWithdrawInfo = async (data) => {
  try {
    const response = await post(`/wallet/withdraw-info/add`, data)
    return response
  } catch (error) {
    console.error('Failed to add withdraw info:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

// 修改用户提现信息
export const updateWithdrawInfo = async (data) => {
  try {
    const response = await post(`/wallet/withdraw-info/update`, data)
    return response
  } catch (error) {
    console.error('Failed to update withdraw info:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

// 提交提现申请
export const withdrawApply = async (data) => {
  try {
    const response = await post('/wallet/bank/withdraw', data)
    return response
  } catch (error) {
    console.error('Failed to fetch withdraw apply:', error)
    throw error
  }
}

// 获取提现记录
export const apiGetWithdrawRecords = async () => {
  try {
    const response = await get(`/team/bd/withdraw/details`)
    return response
  } catch (error) {
    console.error('Failed to fetch get all withdraw records:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

// 获取提现权限
export const apiGetWithdrawEnabled = async () => {
  try {
    const response = await get(`/wallet/bank/host-salary/withdraw/enabled`)
    return response
  } catch (error) {
    console.error('Failed to fetch get all withdraw records:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

// 获取提现美金手续费
export const apiGetUsdWithdrawServiceCharge = async () => {
  try {
    const response = await get(`/wallet/bank/service-charge`)
    return response
  } catch (error) {
    console.error('Failed to fetch withdraw service charge:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

// 获取提现美金门槛
export const apiGetUsdWithdrawalThreshold = async () => {
  try {
    const response = await get(`/wallet/bank/withdrawal-threshold`)
    return response
  } catch (error) {
    console.error('Failed to fetch withdraw threshold:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

/**
 * 获取当前余额
 * @returns {Promise} 返回当前的余额信息
 */
export const apiGetBankBalance = async (salaryType) => {
  try {
    const response = await get(`/wallet/salary-account/balance?salaryType=${salaryType}`)
    return response
  } catch (error) {
    console.error('Failed to fetch get all withdraw records:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

// 转账到金币
export const apiTransfer = async (data) => {
  try {
    const response = await post('/wallet/salary-account/transferGold', data)
    return response
  } catch (error) {
    console.error('Failed to fetch transfer Gold:', error)
    throw error
  }
}

// 兑换金币
export const apiExchange = async (data) => {
  try {
    const response = await post('/wallet/salary-account/exchange/gold', data)
    return response
  } catch (error) {
    console.error('Failed to fetch exchange Gold:', error)
    throw error
  }
}

/**
 * 获取金币代理最小收入金额
 * @returns {Promise} 返回当前的余额信息
 */
export const apiGetFreightThreshold = async (account) => {
  try {
    const response = await get(`/wallet/freight/threshold?account=${account}`)
    return response
  } catch (error) {
    console.error('Failed to fetch get freight threshold:', error)
    console.error('error:' + error.response.errorMsg)
    throw error
  }
}

// 金币代理设置最小收入金额
export const apiSetThreshold = async (data) => {
  try {
    const response = await post('/wallet/freight/threshold', data)
    return response
  } catch (error) {
    console.error('Failed to set threshold:', error)
    throw error
  }
}
