// 奖池服务 - 对应 supermart-mini/service/award.js
import { get, post, postL } from './http';

const apis = {
  INDEX: '/api/app/index/magicMartIndex',
  IP_LIST: '/api/spu/basic/listWorksLimit',
  MAGIC_INDEX: '/api/app/index/magicBoxIndex',
  LIST: '/api/luckPool/list',
  HORSE: '/api/luckPool/horseRaceLampByIndex',
  DETAIL: '/api/luckPool/detail',
  PRODUCTS: '/api/luckPool/prize',
  HORSE_DETAIL: '/api/luckPool/horseRaceLampByDetail',
  BUY_RECORD: '/api/luckPool/buyRecord',
  VERSION: '/api/luckPool/version',
  PREVIEW: '/api/luckOrder/preSubmit',
  APPLY: '/api/luckOrder/submit',
  APPLY_TRY: '/api/luckOrder/demo',
  APPLY_RESULT: '/api/luckOrder/luckResult',
  ORDERS: '/api/luckOrder/pageMy',
  STORE: '/api/luckInventory',
  STORE_MOVE_SAFE: '/api/luckInventory/addToSafe',
  STORE_OUT_SAFE: '/api/luckInventory/moveFromSafe',
  CONVERT_PREVIEW: '/api/luckExchangeOrder/preSubmit',
  CONVERT_APPLY: '/api/luckExchangeOrder/submit',
  CONVERT_LIST: '/api/luckExchangeOrder/pageMy',
  CONVERT_ALL_PREVIEW: '/api/luckExchangeOrder/preOneKeySubmit',
  CONVERT_ALL: '/api/luckExchangeOrder/oneKeySubmit',
  TAKE_PREVIEW: '/api/luckPickupOrder/preSubmit',
  TAKE_APPLY: '/api/luckPickupOrder/submit',
  TAKE_LIST: '/api/luckPickupOrder/pageMy',
  TAKE_PAY_ORDER: '/api/luckPickupOrder/pay',
  POOL_IN: '/api/luckPool/participate',
  POOL_OUT: '/api/luckPool/unparticipate',
  PACKAGES: '/api/luckPickupOrder/expressInfo',
  EXPRESS: '/api/luckPickupOrder/expressDetail',
  KING: '/api/luckKing/getTheLatestLuckKingRecord',
  KING_USER: '/api/luckKing/listBillboard',
  KING_GOODS: '/api/luckKing/listGoods',
  CHECK_PAYMENT_STATUS: '/api/luckOrder/checkPaymentStatus',
  GENERATE_PAYMENT_LINK: '/api/luckOrder/generatePaymentLink',
  KING_PRE: '/api/luckKing/getThePrev',
  BOX_LIST: '/api/luckBox',
  BOX_DETAIL: '/api/luckBox/detail',
  BOX_PRE: '/api/luckBox/getThePrev',
  BOX_NEXT: '/api/luckBox/getTheNext',
  UNAVAILABLE_SEAT_NUMBERS: '/api/luckBox/getUnavaliableSeatNumbers',
  BOX_LOCK: '/api/luckBox/lock',
  BOX_UN_LOCK: '/api/luckBox/unlock',
  FEEDBACK_LIST: '/api/app/feedback/list',
  FEEDBACK_SUBMIT: '/api/app/feedback/submit',
  MY_BOXES: '/api/luck/treasure-box/my-boxes',
  OPEN_BOX: '/api/luck/treasure-box/open',
  HARRY_EXCHANGE: '/api/redemptionCode/redeem',
  WIN_RECORDS: '/api/luck/treasure-box/win-records',
  COUNT_RECORDS: '/api/luckPool/countRecordsAfterLastLevel',
};

// ... (existing code)

// 获取最后一次出奖后的记录数
export const countRecordsAfterLastLevel = async (params: { levelEnumList: string[], poolId: string }) => {
  const res = await post<number>(apis.COUNT_RECORDS, params);
  return res;
};



export interface IPItem {
  id: string;
  name: string;
  cover?: string;
}

export interface PoolItem {
  id: string;
  name: string;
  cover: string;
  price: number;
  mode?: string;
  type?: number;
  status?: number;
}

// 获取首页数据
export const getIndex = async (type = 0) => {
  const res = await get(apis.INDEX, { type });
  return res.data;
};

// 获取 IP 列表
export const getIPList = async (limit = 200): Promise<IPItem[]> => {
  const res = await get<IPItem[]>(apis.IP_LIST, { limit });
  return res.data || [];
};

// 获取魔盒首页
export const getMagicIndex = async () => {
  const res = await get(apis.MAGIC_INDEX);
  return res.data;
};

// 获取奖池列表
export const getPoolList = async (params: {
  current: number;
  size: number;
  mode?: string;
  type?: number;
  worksId?: string;
  keyword?: string;
  priceMin?: number;
  priceMax?: number;
  priceSort?: number;
}) => {
  // 处理 mode 参数
  let processedMode = params.mode;
  if (processedMode && processedMode.startsWith('UNLIMITED')) {
    processedMode = 'UNLIMITED';
  }
  const res = await post<PoolItem[]>(apis.LIST, { ...params, mode: processedMode });
  return res;
};

// 获取跑马灯数据
export const getHorse = async () => {
  const res = await post(apis.HORSE);
  return res.success ? res.data : null;
};

// 获取奖池详情
export const getPoolDetail = async (poolId: string) => {
  const res = await get(apis.DETAIL, { poolId });
  return res.data;
};

// 获取奖池商品
export const getPoolProducts = async (poolId: string) => {
  const res = await get(apis.PRODUCTS, { poolId });
  return res.data;
};

// 获取详情跑马灯
export const getDetailHorse = async (poolId: string, size = 50) => {
  const res = await post(apis.HORSE_DETAIL, { poolId, size });
  return res.success ? res.data : null;
};

// 获取购买记录
export const getBuyRecord = async (poolId: string, lastId?: string, level?: number, size = 200) => {
  const res = await post(apis.BUY_RECORD, { poolId, lastId, level, size });
  return res.data;
};

// 获取版本信息
export const getVersion = async (poolId: string, size = 20) => {
  const res = await post(apis.VERSION, { poolId, size });
  return res.data;
};

// 试玩
export const tryDemo = async (poolId: string, quantity: number) => {
  const res = await postL(apis.APPLY_TRY, { poolId, quantity });
  return res.data;
};

// 预提交订单
export const previewOrder = async (poolId: string, quantity?: number, boxNumber?: string, seatNumbers?: number[], packFlag?: boolean) => {
  const param: any = { poolId };
  if (quantity) param.quantity = quantity;
  if (boxNumber) param.boxNumber = boxNumber;
  if (seatNumbers && seatNumbers.length > 0) param.seatNumbers = seatNumbers;
  if (packFlag) param.packFlag = packFlag;
  const res = await postL(apis.PREVIEW, param);

  // http.ts 已经统一处理了错误提示，这里只返回数据
  if (!res.success) {
    return null;
  }

  return res.data;
};

// 提交订单
export const applyOrder = async (poolId: string, quantity: number, paymentType: string, boxNumber?: string, seatNumbers?: number[], packFlag?: boolean) => {
  const param: any = { poolId, quantity, paymentType };
  if (boxNumber) param.boxNumber = boxNumber;
  if (seatNumbers && seatNumbers.length > 0) param.seatNumbers = seatNumbers;
  if (packFlag) param.packFlag = packFlag;
  const res = await postL(apis.APPLY, param);

  // http.ts 已经统一处理了错误提示，这里只返回数据
  if (!res.success) {
    return null;
  }

  return res.data;
};

// 获取抽奖结果
export const getApplyResult = async (tradeNo: string) => {
  const res = await get(apis.APPLY_RESULT, { tradeNo });
  return res.data;
};

// 检查支付状态
export const checkPaymentStatus = async (tradeNo: string) => {
  const res = await get(apis.CHECK_PAYMENT_STATUS, { tradeNo });
  return res.data;
};

// 获取盲盒订单列表
export const getAwardOrders = async (current: number, size: number, tab?: string) => {
  const res = await post(apis.ORDERS, { current, size, tab });
  return res.data;
};

// 获取仓库列表
export const getStore = async (current: number, size: number, safeFlag?: number, tab?: string, status: number = 0) => {
  const res = await post(apis.STORE, { current, size, status, tab, safeFlag });
  return res.data;
};

// 移入保险箱
export const moveToSafeStore = async (inventoryIds: string[]) => {
  const res = await postL(apis.STORE_MOVE_SAFE, { inventoryIds });
  return res.success;
};

// 移出保险箱
export const moveOutSafeStore = async (inventoryIds: string[]) => {
  const res = await postL(apis.STORE_OUT_SAFE, { inventoryIds });
  return res.success;
};

// 兑换预览
export const convertPreview = async (inventoryIds: string[]) => {
  const res = await postL(apis.CONVERT_PREVIEW, { inventoryIds });
  return res;
};

// 兑换申请
export const convertApply = async (inventoryIds: string[]) => {
  const res = await postL(apis.CONVERT_APPLY, { inventoryIds });
  return res.success;
};

// 兑换列表
export const getConvertList = async (current: number, size: number) => {
  const res = await post(apis.CONVERT_LIST, { current, size });
  return res.data;
};

// 一键兑换预览
export const convertAllPreview = async () => {
  const res = await postL(apis.CONVERT_ALL_PREVIEW);
  return res.data;
};

// 一键兑换
export const convertAll = async (levels: number[]) => {
  const res = await postL(apis.CONVERT_ALL, { levels });
  return res.success;
};

// 提货预览
export const takePreview = async (inventoryIds: string[], addressBookId: string) => {
  const res = await postL(apis.TAKE_PREVIEW, { inventoryIds, addressBookId });
  return res.data;
};

// 提货申请
export const takeApply = async (inventoryIds: string[], addressBookId: string, paymentType: string) => {
  const res = await postL(apis.TAKE_APPLY, { inventoryIds, addressBookId, paymentType });
  return res.data;
};

// 提货列表
export const getTakeList = async (current: number, size: number) => {
  const res = await post(apis.TAKE_LIST, { current, size });
  return res.data;
};

// 提货支付
export const takePayOrder = async (inventoryIds: string[], addressBookId: string, paymentType: string, tradeNo?: string) => {
  const res = await postL(apis.TAKE_PAY_ORDER, { inventoryIds, addressBookId, paymentType, tradeNo });
  return res.data;
};

// 参与奖池
export const poolIn = async (poolId: string) => {
  const res = await get(apis.POOL_IN, { poolId });
  return res.success;
};

// 退出奖池
export const poolOut = async (poolId?: string) => {
  const param: any = {};
  if (poolId) param.poolId = poolId;
  const res = await get(apis.POOL_OUT, param);
  return res.success;
};

// 获取包裹信息
export const getAwardPackages = async (tradeNo: string) => {
  const res = await get(apis.PACKAGES, { tradeNo });
  return res.data;
};

// 获取物流详情
export const getAwardExpress = async (tradeNo: string, packageId: string) => {
  const res = await get(apis.EXPRESS, { tradeNo, packageId });
  return res.data;
};

// 获取欧皇信息
export const getKing = async (poolId: string) => {
  const res = await get(apis.KING, { poolId });
  return res.success ? res.data : null;
};

// 获取欧皇榜单
export const getKingUser = async (poolId: string) => {
  const res = await get(apis.KING_USER, { poolId });
  return res.data;
};

// 获取欧皇商品
export const getKingGoods = async (poolId: string) => {
  const res = await get(apis.KING_GOODS, { poolId });
  return res.data;
};

// 获取上一期欧皇
export const getPreKing = async (poolId: string) => {
  const res = await get(apis.KING_PRE, { poolId });
  return res.data;
};

// 获取盒子列表
export const getBoxList = async (poolId: string, level?: number, current?: number, size?: number) => {
  const res = await post(apis.BOX_LIST, { poolId, current, size, level });
  return res.data;
};

// 获取盒子详情
export const getBoxDetail = async (poolId: string, boxNumber?: string) => {
  const param: any = { poolId };
  if (boxNumber) param.boxNumber = boxNumber;
  const res = await get(apis.BOX_DETAIL, param);
  return res.data;
};

// 获取上一个盒子
export const getPreBox = async (poolId: string, boxNumber: string) => {
  const res = await get(apis.BOX_PRE, { poolId, boxNumber });
  return res.data;
};

// 获取下一个盒子
export const getNextBox = async (poolId: string, boxNumber: string) => {
  const res = await get(apis.BOX_NEXT, { poolId, boxNumber });
  return res.data;
};

// 锁定盒子
export const lockBox = async (poolId: string, boxNumber: string) => {
  const res = await postL(apis.BOX_LOCK, { poolId, boxNumber });
  return res.success;
};

// 解锁盒子
export const unlockBox = async (poolId: string, boxNumber: string) => {
  const res = await postL(apis.BOX_UN_LOCK, { poolId, boxNumber });
  return res.success;
};

// 获取不可用座位号
export const getUnavailableSeatNumbers = async (poolId: string, boxNumber: string, startSeatNumber?: number, endSeatNumber?: number) => {
  const params: any = { poolId, boxNumber };
  if (startSeatNumber) params.startSeatNumber = startSeatNumber;
  if (endSeatNumber) params.endSeatNumber = endSeatNumber;
  const res = await post(apis.UNAVAILABLE_SEAT_NUMBERS, params);
  return res.data;
};

// 获取弹幕列表
export const getFeedbackList = async () => {
  const res = await get(apis.FEEDBACK_LIST);
  return res;
};

// 发送弹幕
export const submitFeedback = async (content: string) => {
  const res = await postL(apis.FEEDBACK_SUBMIT, { content });
  return res;
};

// 获取我的宝箱列表
export const getMyBoxes = async () => {
  const res = await get(apis.MY_BOXES);
  return res.data;
};

// 开启宝箱
export const openBox = async (params: { boxIds: string }) => {
  // 按照小程序的方式，boxIds 作为 query 参数
  const res = await post(`${apis.OPEN_BOX}?boxIds=${params.boxIds}`, {});
  return res;
};

// 获取仓库商品详情
export const getLuckDetail = async (id: string) => {
  const res = await get('/api/luckInventory/detail', { id });
  return res.data;
};

// 获取仓库商品总数
export const getSumInventory = async () => {
  const res = await get('/api/luckInventory');
  return res.data;
};

// 兑换码兑换
export const harryExchange = async (params: { code: string }) => {
  const res = await post(apis.HARRY_EXCHANGE, params, { silent: true });
  return res;
};

// 获取中奖记录
export const getWinRecords = async (poolId: string, boxNumber: string) => {
  const res = await get(apis.WIN_RECORDS, { poolId, boxNumber });
  return res.data;
};

export default {
  getIndex,
  getIPList,
  getMagicIndex,
  getPoolList,
  getHorse,
  getPoolDetail,
  getPoolProducts,
  getDetailHorse,
  getBuyRecord,
  getVersion,
  tryDemo,
  previewOrder,
  applyOrder,
  getApplyResult,
  checkPaymentStatus,
  getAwardOrders,
  getStore,
  moveToSafeStore,
  moveOutSafeStore,
  convertPreview,
  convertApply,
  getConvertList,
  convertAllPreview,
  convertAll,
  takePreview,
  takeApply,
  getTakeList,
  takePayOrder,
  poolIn,
  poolOut,
  getAwardPackages,
  getAwardExpress,
  getKing,
  getKingUser,
  getKingGoods,
  getPreKing,
  getBoxList,
  getBoxDetail,
  getPreBox,
  getNextBox,
  lockBox,
  unlockBox,
  getUnavailableSeatNumbers,
  getFeedbackList,
  submitFeedback,
  getLuckDetail,
  getSumInventory,
  harryExchange,
  getWinRecords,
  countRecordsAfterLastLevel,
};
