import API from "@src/api";

/**
* 预扣积分
* @param {String} toPlaywayId 门票核销的目标玩法id
* @param {String} toActionId 门票核销的目标actionId
* @param {Number} credits 自定义扣积分值
* @returns 是否扣除成功
*/
export const preDeductPointsfunc = async (toPlaywayId, toActionId, credits) => {
  // [扣积分]查询可复用扣积分票号，核销视情况调用
  // const res = await API.queryUnused({ toPlaywayId: 'gambler', toActionId: 'betting' })
  // if (res?.success && res?.data?.ticketList) {
  //   const ticketList = res?.data?.ticketList
  //   if (Array.isArray(ticketList)) {
  //     if (ticketList.length > 0) {
  //       return ticketList[0]
  //     }
  //   } else {
  //     return ticketList
  //   }
  // }

  const paramDeduct = {
    toPlaywayId,
    toActionId,
    credits,
    desc: "creditsCostDesc"
  }
  // 预扣积分
  const { success, data: ticketTmp } = await API.preDeductPoints(paramDeduct);
  if (!success) return
  let pollingNums = 1
  const queryParams = {
    ticketNum: ticketTmp
  }
  const pollingApi = async () => {
    if (pollingNums > 10) return false
    const { data = 0 } = await API.queryDeductSatus(queryParams);

    if (data == 1) { // data == 1 扣除成功
      return queryParams.ticketNum
    } else if (data == 2) { // data == 2 扣除失败
      return false
    } else { // data == 0 预扣中
      if (pollingNums <= 9) {
        pollingNums++
        return new Promise(resolve => {
          setTimeout(() => {
            resolve(pollingApi())
          }, 1000)
        })
      } else {
        return false
      }
    }
  }
  return pollingApi()
}