/**
 * 预扣积分相关接口
 */

import { Toast } from "@grace/ui";
import API from '../api/index';
import { runInAction } from "mobx";
import store from "../store/store.ts";

/** 设置积分门票 */
export const setTicketNum = (ticketNum) => {
  runInAction(() => {
    store.ticketNum = ticketNum;
  });
};

let pollNum = 0;
/** 清除次数 */
export const clearPollNum = () => {
  pollNum = 0;
};

export const setPollNum = () => {
  pollNum++;
};

/** 预扣积分 */
export const pre_reduce_score = async (params, sucCb, failCb) => {
  // showLoading();
  const { toPlaywayId, toActionId, desc, credits, scoreFrom, type } = params
  // 预扣积分
  const res = await API.creditsCost({
    toPlaywayId,
    toActionId,
    desc,
    credits: credits,
    scoreFrom
  });
  if (res?.success) {
    setTicketNum(res?.data);
    // 轮询查积分状态
    pollCheck_change(sucCb, failCb);
  } else {
    // hideLoading();
    failCb?.();

  }
};
/**
 * 轮询查积分扣除状态
 * 0:处理中
 * 1:成功
 * 2:失败
 */
export const pollCheck_change = async (sucCb, failCb) => {
  // 查询扣积分状态
  const res = await API.queryStatus({
    ticketNum: store.ticketNum,
  }).catch((e) => {
    // hideLoading();
    failCb?.();
  });
  // 处理中
  if (res?.success && res?.data == 0) {
    if (pollNum > 9) {
      Toast.show("网络异常，扣积分失败~");
      clearPollNum();
      // hideLoading();
      failCb?.();
      return;
    }
    setPollNum();
    // 延时1s递归
    setTimeout(() => {
      pollCheck_change(sucCb, failCb);
    }, 1000);
  }
  // 成功
  if (res?.success && res?.data == 1) {
    sucCb?.();
    clearPollNum();
    // hideLoading();
  }
  // 失败
  if (res?.success && res?.data == 2) {
    Toast.show(res?.message || "网络异常，积分稍后退回");
    // hideLoading();
    failCb?.();
  }
  // 接口报错
  if (!res?.success) {
    // hideLoading();
    failCb?.();
  }
};
