function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
/* eslint-disable @typescript-eslint/no-unused-expressions */
import { locales } from '@pisell/utils';
import { useCallback, useEffect, useRef } from 'react';
import { StatusEnum, PayStatus, ClientEnum } from "../const";
import { useContextData, useDispatch, updateComponent, updateState, updateStatus, updateCustom, updateKey } from "../store";
import { StepStatusEnum, getStepMapping, StemTypeEnum } from "./const";
import { useStoreRef } from "../hooks";
import XhrTimer from "./timer";
var Max4004 = 1;

/**
 * @title: windcave 支付,退款,查询 错误逻辑处理
 * @description: 动态步骤页 异常前往 FailCustom 页面
 * @return null
 * @Author: hongbing.wang
 * @Date: 2024-08-12 10:29
 */
export var useFail = function useFail() {
  var dispatch = useDispatch();
  var _useContextData = useContextData(),
    custom = _useContextData.custom;
  var _useStoreRef = useStoreRef(),
    modeRef = _useStoreRef.modeRef,
    clientRef = _useStoreRef.clientRef;
  var ref = useRef((custom === null || custom === void 0 ? void 0 : custom.retry) || 0);
  useEffect(function () {
    ref.current = (custom === null || custom === void 0 ? void 0 : custom.retry) || 0;
  }, [custom === null || custom === void 0 ? void 0 : custom.retry]);
  return useCallback(function (res) {
    var isMark = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false;
    if (!res || !res.code) {
      // 去往未知处理页面
      dispatch(updateCustom({
        errorStatus: 'unknow' // unknow know
      }));
      dispatch(updateComponent('UnknowFail'));
      return;
    }
    var code = "".concat(res.code);
    if ("".concat(res.code) === PayStatus.Unknown) {
      // 前往报错页 不可标记
      dispatch(updateCustom({
        failCustom: {
          isPosNetworkError: false,
          status: 'fail',
          fail: locales.getText('page.eftpos-pay.text.transaction.fail'),
          warn: null,
          title: locales.getText('page.eftpos-pay.text.failed')(modeRef.current)
        }
      }));
      dispatch(updateComponent('FailCustom'));
      return;
    }
    console.log(code, ref.current, Max4004);
    if (code === PayStatus.NoPay) {
      // 如果未查询到支付状态,则重新发起支付
      if (ref.current > Max4004) {
        // 前往错误页  不可标记状态
        dispatch(updateCustom({
          retry: 0,
          failCustom: {
            isPosNetworkError: false,
            status: 'fail',
            fail: locales.getText('page.eftpos-pay.text.transaction.fail'),
            warn: null,
            titl: locales.getText('page.eftpos-pay.text.failed')(modeRef.current)
          }
        }));
        dispatch(updateComponent('FailCustom'));
        return;
      }
      // 重新支付 最多到重新发起2次
      ref.current += 1;
      // 清掉 支付流水号
      dispatch(updateState({
        number: ''
      }));
      dispatch(updateCustom({
        retry: ref.current,
        list: []
      }));
      dispatch(updateKey(Date.now()));
      return;
    }
    if (code === PayStatus.PayTimeout) {
      dispatch(updateCustom({
        failCustom: {
          isPosNetworkError: false,
          status: 'fail',
          fail: locales.getText('page.eftpos-pay.text.transaction.fail.timeout'),
          title: locales.getText('page.eftpos-pay.text.failed')(modeRef.current),
          warn: null
        }
      }));
      dispatch(updateComponent('FailCustom'));
      return;
    }
    if (code === PayStatus.Timeout) {
      if (isMark) {
        if (clientRef.current === ClientEnum.User) {
          dispatch(updateCustom({
            failCustom: {
              isPosNetworkError: true,
              status: 'warn',
              fail: null,
              title: locales.getText('page.eftpos-pay.text.timedout.title'),
              warn: locales.getText('page.eftpos-pay.text.transaction.eftpos.fail.other')
            }
          }));
          dispatch(updateComponent('FailCustom'));
          return;
        }
        // 超时 前往标记页
        dispatch(updateState({
          manual: {
            title: locales.getText('page.eftpos-pay.text.timedout.title'),
            text: locales.getText('page.eftpos-pay.text.timedout.text')(modeRef.current)
          }
        }));
        dispatch(updateComponent('Manual'));
        return;
      }
      // 前往错误页  不可标记状态
      dispatch(updateCustom({
        failCustom: {
          isPosNetworkError: false,
          status: 'fail',
          fail: locales.getText('page.eftpos-pay.text.transaction.fail.timeout'),
          title: locales.getText('page.eftpos-pay.text.failed')(modeRef.current),
          warn: null
        }
      }));
      dispatch(updateComponent('FailCustom'));
      return;
    }
    if (code === PayStatus.PayOtherEftposFailed) {
      // 前往错误页 不可标记状态
      dispatch(updateCustom({
        failCustom: {
          isPosNetworkError: false,
          status: 'fail',
          fail: locales.getText('page.eftpos-pay.text.transaction.fail.terminal'),
          title: locales.getText('page.eftpos-pay.text.transaction.fail.terminal.title'),
          warn: null
        }
      }));
      dispatch(updateComponent('FailCustom'));
      return;
    }
    if (code === PayStatus.PayCardErrorFailed) {
      // 前往错误页 不可标记状态
      dispatch(updateCustom({
        failCustom: {
          status: 'fail',
          fail: locales.getText('page.eftpos-pay.text.transaction.fail.cancel'),
          title: locales.getText('page.eftpos-pay.text.transaction.fail.cancel.title'),
          warn: null
        }
      }));
      dispatch(updateComponent('FailCustom'));
      return;
    }
    if (code === PayStatus.NoNetWork || code === PayStatus.SocketError) {
      // 前往错误页 可标记状态
      dispatch(updateCustom({
        failCustom: {
          isPosNetworkError: true,
          status: 'warn',
          fail: null,
          title: locales.getText('page.eftpos-pay.text.interrupted'),
          warn: clientRef.current === ClientEnum.Merchant ? "".concat(locales.getText('page.eftpos-pay.text.transaction.eftpos.fail.title'), "\n").concat(locales.getText('page.eftpos-pay.text.transaction.eftpos.fail.power'), "\n ").concat(locales.getText('page.eftpos-pay.text.transaction.eftpos.fail.device'), "\n").concat(locales.getText('page.eftpos-pay.text.transaction.eftpos.fail.network'), "\n").concat(locales.getText('page.eftpos-pay.text.transaction.eftpos.fail.if')(modeRef.current)) : locales.getText('page.eftpos-pay.text.transaction.eftpos.fail.other')
        }
      }));
      dispatch(updateComponent('FailCustom'));
      return;
    }
    if (code === PayStatus.PayBankRefuses) {
      //
      dispatch(updateCustom({
        failCustom: {
          isPosNetworkError: false,
          status: 'fail',
          fail: locales.getText('page.eftpos-pay.text.transaction.back.declined.text'),
          title: locales.getText('page.eftpos-pay.text.transaction.back.declined.title'),
          warn: null
        }
      }));
      dispatch(updateComponent('FailCustom'));
      return;
    }
    if (code === PayStatus.SignatureDeclined) {
      dispatch(updateCustom({
        failCustom: {
          isPosNetworkError: false,
          status: 'fail',
          fail: locales.getText('page.eftpos-pay.text.transaction.user.declined.text'),
          title: locales.getText('page.eftpos-pay.text.transaction.user.declined.title'),
          warn: null
        }
      }));
      dispatch(updateComponent('FailCustom'));
      return;
    }
    if (code === PayStatus.UserConfigError) {
      dispatch(updateCustom({
        failCustom: {
          isPosNetworkError: false,
          status: 'fail',
          fail: locales.getText('page.eftpos-pay.text.transaction.user.config.text'),
          title: locales.getText('page.eftpos-pay.text.transaction.user.config.title'),
          warn: null
        }
      }));
      dispatch(updateComponent('FailCustom'));
      return;
    }

    // 其他场景前往未知错误页
    dispatch(updateCustom({
      errorStatus: 'unknow' // unknow know
    }));
    dispatch(updateComponent('UnknowFail'));
  }, [dispatch]);
};

/**
 * @title: 轮询 check 接口
 * @description: 轮询 终止条件 1.超时 , 2. 返回非200状态码 , 3. 外部关闭
 * @return [run, XhrTimer] run: 启动函数 , XhrTimer 轮询类
 * @Author: hongbing.wang
 * @Date: 2024-08-12 10:30
 */
export var useValidate = function useValidate(check, num, onChange) {
  var unloadRef = useRef(false);
  var dispatch = useDispatch();
  var fail = useFail();
  var failRef = useRef(fail);
  var ref = useRef();
  var _useContextData2 = useContextData(),
    custom = _useContextData2.custom;
  var _useStoreRef2 = useStoreRef(),
    netRef = _useStoreRef2.netRef,
    payRef = _useStoreRef2.payRef,
    numRef = _useStoreRef2.numRef,
    modeRef = _useStoreRef2.modeRef,
    clientRef = _useStoreRef2.clientRef;
  var stepRef = useRef(custom === null || custom === void 0 ? void 0 : custom.step);
  var listRef = useRef(custom === null || custom === void 0 ? void 0 : custom.list);
  useEffect(function () {
    listRef.current = custom === null || custom === void 0 ? void 0 : custom.list;
  }, [custom === null || custom === void 0 ? void 0 : custom.list]);
  useEffect(function () {
    stepRef.current = custom === null || custom === void 0 ? void 0 : custom.step;
  }, [custom === null || custom === void 0 ? void 0 : custom.step]);
  var watchRef = useRef();
  var run = useCallback(function (timeout) {
    var _ref$current2, _ref$current3;
    if (timeout === -1) {
      console.log('无限加载');
    } else {
      console.log('计时加载 ', typeof timeout === 'number' ? timeout : num);
    }
    if (unloadRef.current) {
      var _ref$current;
      (_ref$current = ref.current) === null || _ref$current === void 0 || _ref$current.close();
      return;
    }
    if (!watchRef.current || !netRef.current) {
      return;
    }
    // 关闭上一轮 查询
    (_ref$current2 = ref.current) === null || _ref$current2 === void 0 || _ref$current2.close();
    // 开启新一轮查询
    ref.current = new XhrTimer({
      xhr: check,
      timeout: typeof timeout === 'number' ? timeout : num,
      callback: watchRef.current
    });
    (_ref$current3 = ref.current) === null || _ref$current3 === void 0 || _ref$current3.run({
      number: numRef.current
    })
    // eslint-disable-next-line consistent-return
    .then(function (res) {
      if (unloadRef.current) {
        return;
      }
      if (!netRef.current) {
        return;
      }
      if (!res || Number(res.code) !== 200) {
        // eslint-disable-next-line consistent-return
        return Promise.reject(res);
      }
    }).catch(function (res) {
      var _failRef$current;
      if (unloadRef.current) {
        return;
      }
      if (!netRef.current) {
        return;
      }
      if (res && res.code === -1) {
        return;
      }
      (_failRef$current = failRef.current) === null || _failRef$current === void 0 || _failRef$current.call(failRef, res, stepRef.current >= StepStatusEnum.Account);
    });
  }, [check, num]);
  useEffect(function () {
    /**
     * @title: 轮询结果处理
     * @description: 将轮询结果进行处理,根据不同的轮询结果进行不同的业务逻辑处理
     * @param {any} res 轮询接口范湖遗址
     * @return null
     * @Author: hongbing.wang
     * @Date: 2024-08-12 12:42
     */
    watchRef.current = function (res, isRun) {
      if (unloadRef.current) {
        var _ref$current4;
        (_ref$current4 = ref.current) === null || _ref$current4 === void 0 || _ref$current4.close();
        return;
      }
      if (!res || !res.data || !res.data.txn_status_id) {
        var _ref$current5;
        (_ref$current5 = ref.current) === null || _ref$current5 === void 0 || _ref$current5.close();
      }
      var _ref = [Number(res.data.txn_status_id), Number(res.data.status_id), Number(res.data.complete)],
        txn_status_id = _ref[0],
        status_id = _ref[1],
        complete = _ref[2];

      // 支付成功状态
      if (txn_status_id === StepStatusEnum.Wait && status_id === 6 && complete === 1) {
        var _ref$current6;
        (_ref$current6 = ref.current) === null || _ref$current6 === void 0 || _ref$current6.close();

        // 步骤列表中不存在当前步骤
        if (stepRef.current !== txn_status_id && listRef.current.every(function (_ref2) {
          var index = _ref2.index;
          return txn_status_id !== index;
        })) {
          var _payRef$current;
          // 将所有步骤状态设为完成 resolve
          var current = listRef.current.map(function (item) {
            if (Number(item === null || item === void 0 ? void 0 : item.index) < Number(stepRef.current)) {
              return _objectSpread(_objectSpread({}, item), {}, {
                status: 'resolve'
              });
            }
            return item;
          });
          // 创建下一步骤信息
          var nextStep = getStepMapping(txn_status_id, {
            money: (_payRef$current = payRef.current) === null || _payRef$current === void 0 ? void 0 : _payRef$current.totalUnit,
            mode: modeRef.current
          });
          if (nextStep) {
            current.push(nextStep);
          }
          // 更新步骤
          dispatch(updateCustom({
            list: current,
            step: txn_status_id
          }));
        }
        onChange(res.data);
        return;
      }

      // 普通状态
      if (stepRef.current !== txn_status_id && listRef.current.every(function (_ref3) {
        var index = _ref3.index;
        return txn_status_id !== index;
      })) {
        var _ref$current7, _payRef$current2;
        // 查询到不存在的状态,则新增步骤状态
        console.log('self.flag  stepRef.current, txn_status_id ', stepRef.current, txn_status_id);
        stepRef.current = txn_status_id;
        // 构建新状态时,将之前的查询关闭
        (_ref$current7 = ref.current) === null || _ref$current7 === void 0 || _ref$current7.close();

        // 将当前步骤列表数据翻转成完成 - resolve
        var _current = listRef.current.map(function (item) {
          if (Number(item === null || item === void 0 ? void 0 : item.index) < Number(stepRef.current)) {
            return _objectSpread(_objectSpread({}, item), {}, {
              status: 'resolve'
            });
          }
          return item;
        });
        // 获取下一步配置
        var _nextStep = getStepMapping(txn_status_id, {
          money: (_payRef$current2 = payRef.current) === null || _payRef$current2 === void 0 ? void 0 : _payRef$current2.totalUnit,
          mode: modeRef.current
        });
        if (_nextStep) {
          _current.push(_nextStep);
          // 如果是被动提交等待用户行为则给出 Question 提示 用户操作
          if (_nextStep.type === StemTypeEnum.Passive) {
            dispatch(updateStatus(StatusEnum.Question));
          }
          if (_nextStep.index === StepStatusEnum.Receipt) {
            // 签名步骤定制签名步骤签名
            dispatch(updateState({
              title: locales.getText('page.eftpos-pay.text.waiting.signature')
            }));
          }
        }
        dispatch(updateCustom({
          list: _current,
          step: txn_status_id
        }));
        // 如果是签名页 则开启无限查询, 如果不是则开启计时查询
        txn_status_id === StepStatusEnum.Receipt ? run(-1) : run();
        return;
      }
      if (isRun) {
        run();
      }
    };
  }, [dispatch, onChange, run]);
  useEffect(function () {
    return function () {
      var _ref$current8;
      (_ref$current8 = ref.current) === null || _ref$current8 === void 0 || _ref$current8.close();
      unloadRef.current = true;
    };
  }, []);
  return [run, watchRef, ref];
};