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); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { useEffect, useRef, useState } from 'react';
import { useTyro } from "./hooks";
import { locales } from '@pisell/utils';
import { Button } from 'antd';
import { useDispatch, useContextData, updateState, updateCustom, updateComponent } from "../store";
import { ModeEnum, ClientEnum } from "../const";
import { Decimal } from 'decimal.js';
import { getUuid, getPayParams, getBrowserVersion } from "../helper";
import Step from "../component/step/step";
import { useStoreRef } from "../hooks";
import payLog from "../utils/payLog";
var Minute = 1000 * 60;
export default (function (_ref) {
  var api = _ref.api,
    onChange = _ref.onChange,
    children = _ref.children,
    url = _ref.url,
    version = _ref.version;
  var _useContextData = useContextData(),
    eftpos = _useContextData.eftpos,
    custom = _useContextData.custom,
    mode = _useContextData.mode,
    payStatus = _useContextData.status,
    client = _useContextData.client;
  var dispatch = useDispatch();
  var _useState = useState(-1),
    _useState2 = _slicedToArray(_useState, 2),
    status = _useState2[0],
    setStatus = _useState2[1];
  var _useState3 = useState(false),
    _useState4 = _slicedToArray(_useState3, 2),
    isManually = _useState4[0],
    setManually = _useState4[1];
  var isCancelRef = useRef(false);
  var _useStoreRef = useStoreRef(),
    deviceRef = _useStoreRef.deviceRef,
    payRef = _useStoreRef.payRef,
    numRef = _useStoreRef.numRef,
    modeRef = _useStoreRef.modeRef,
    orderIdRef = _useStoreRef.orderIdRef,
    amountRef = _useStoreRef.amountRef;
  var merchantReceiptRef = useRef({});
  var _useTyro = useTyro({
      url: url,
      version: version
    }),
    _useTyro2 = _slicedToArray(_useTyro, 2),
    TyroRef = _useTyro2[0],
    load = _useTyro2[1];
  var requestParams = useRef(custom === null || custom === void 0 ? void 0 : custom.requestParams);
  var listRef = useRef((custom === null || custom === void 0 ? void 0 : custom.list) || []);
  var iClientRef = useRef();
  var requestIdRef = useRef((custom === null || custom === void 0 ? void 0 : custom.requestId) || '');
  var unloadRef = useRef(false);
  var clearRef = useRef();
  var isPrint = function isPrint(key) {
    var _deviceRef$current, _deviceRef$current2;
    if ((_deviceRef$current = deviceRef.current) !== null && _deviceRef$current !== void 0 && (_deviceRef$current = _deviceRef$current.setting) !== null && _deviceRef$current !== void 0 && _deviceRef$current.receipts) {
      return false;
    }
    var receiptList = (_deviceRef$current2 = deviceRef.current) === null || _deviceRef$current2 === void 0 || (_deviceRef$current2 = _deviceRef$current2.setting) === null || _deviceRef$current2 === void 0 ? void 0 : _deviceRef$current2.receiptList;
    if (!Array.isArray(receiptList)) {
      return true;
    }
    if (Array.isArray(receiptList) && receiptList.some(function (item) {
      return item === key;
    })) {
      return true;
    }
    return false;
  };
  useEffect(function () {
    listRef.current = (custom === null || custom === void 0 ? void 0 : custom.list) || [];
  }, [custom === null || custom === void 0 ? void 0 : custom.list]);
  useEffect(function () {
    requestIdRef.current = (custom === null || custom === void 0 ? void 0 : custom.requestId) || '';
  }, [custom === null || custom === void 0 ? void 0 : custom.requestId]);
  useEffect(function () {
    requestParams.current = custom === null || custom === void 0 ? void 0 : custom.requestParams;
  }, [custom === null || custom === void 0 ? void 0 : custom.requestParams]);

  /**
   * @title: 获取设备信息
   * @description: 获取设备信息
   * @param {function} cb
   * @Author: hongbing.wang
   * @Date: 2024-08-19 11:32
   */
  var getTerminalInfo = function getTerminalInfo(cb) {
    var iClient = iClientRef.current;
    if (!iClient) {
      return;
    }
    setStatus(0);
    var connection = deviceRef.current.connection;
    var integrationKey = connection.integrationKey,
      tid = connection.tid,
      mid = connection.mid;
    console.log(integrationKey, tid, mid);
    iClient.terminalInfo(function (_ref2) {
      var status = _ref2.status,
        message = _ref2.message,
        terminalInfo = _ref2.terminalInfo;
      payLog.log('Tyro：终端信息回调', {
        status: status,
        terminalInfo: terminalInfo,
        message: message
      });
      if (status === 'success' && terminalInfo !== null && terminalInfo !== void 0 && terminalInfo.available) {
        cb();
      }
    }, {
      mid: mid,
      tid: tid,
      integrationKey: integrationKey
    });
  };

  /**
   * @title: 退款
   * @description: 退款
   * @Author: hongbing.wang
   * @Date: 2024-08-19 11:32
   */
  var refundOrder = function refundOrder() {
    var _deviceRef$current3, _deviceRef$current4, _requestParams$curren;
    var iClient = iClientRef.current;
    if (!iClient) {
      return;
    }
    if (isCancelRef.current) {
      return;
    }
    var connection = deviceRef.current.connection;
    var integrationKey = connection.integrationKey,
      tid = connection.tid,
      mid = connection.mid;
    numRef.current = getUuid();
    dispatch(updateState({
      number: numRef.current
    }));
    requestParams.current = {
      amount: new Decimal(amountRef.current || 0).mul(100).toFixed(0, Decimal.ROUND_HALF_UP),
      // 打印小票 true 打印到Pisell系统上 false 打印到pos机上
      integratedReceipt: !((_deviceRef$current3 = deviceRef.current) !== null && _deviceRef$current3 !== void 0 && (_deviceRef$current3 = _deviceRef$current3.setting) !== null && _deviceRef$current3 !== void 0 && _deviceRef$current3.receipts),
      integrationKey: integrationKey,
      transactionId: numRef.current,
      mid: mid,
      tid: tid,
      device: JSON.stringify(deviceRef.current),
      isPrintMerchant: isPrint('merchant'),
      isPrintCustomer: isPrint('customer'),
      browserVersion: getBrowserVersion()
    };
    dispatch(updateCustom({
      requestParams: requestParams.current
    }));
    setStatus(Date.now());
    merchantReceiptRef.current = {};
    // 退款 记录
    api.addTransaction({
      order_id: orderIdRef.current,
      number: numRef.current,
      card_reader_id: (_deviceRef$current4 = deviceRef.current) === null || _deviceRef$current4 === void 0 ? void 0 : _deviceRef$current4.id,
      card_reader_type: eftpos,
      amount: requestParams.current.amount,
      action: modeRef.current === ModeEnum.FullPay ? ModeEnum.Pay : modeRef.current,
      status: 'pending',
      request: requestParams.current,
      response: {},
      metadata: {
        receipt: []
      },
      _config: {
        retry: {
          count: 10,
          delay: 500
        }
      }
    }).then(function (res) {
      requestIdRef.current = res.data.id;
      dispatch(updateCustom({
        requestId: res.data.id
      }));
    });
    payLog.setContext({
      transactionNumber: numRef.current
    });
    payLog.log('Tyro：发起退款', {
      number: numRef === null || numRef === void 0 ? void 0 : numRef.current,
      amount: (_requestParams$curren = requestParams.current) === null || _requestParams$curren === void 0 ? void 0 : _requestParams$curren.amount
    });
    iClient.initiateRefund(requestParams.current, {
      receiptCallback: receiptCallbackImpl,
      transactionCompleteCallback: transactionCompleteCallbackImpl,
      questionCallback: questionCallbackImpl,
      statusMessageCallback: statusMessageCallbackImpl
    });
  };

  /**
   * @title: 支付
   * @description:
   * @return {*}
   * @Author: hongbing.wang
   * @Date: 2024-08-19 11:33
   */
  var payOrder = function payOrder() {
    var _deviceRef$current5, _payRef$current, _deviceRef$current6, _deviceRef$current7, _deviceRef$current8;
    var iClient = iClientRef.current;
    if (!iClient) {
      return;
    }
    if (isCancelRef.current) {
      return;
    }
    var connection = deviceRef.current.connection;
    var integrationKey = connection.integrationKey,
      tid = connection.tid,
      mid = connection.mid;
    numRef.current = getUuid();
    dispatch(updateState({
      number: numRef.current
    }));
    console.log('deviceRef.current?.settings?.useOriginSurcharge = ', (_deviceRef$current5 = deviceRef.current) === null || _deviceRef$current5 === void 0 || (_deviceRef$current5 = _deviceRef$current5.setting) === null || _deviceRef$current5 === void 0 ? void 0 : _deviceRef$current5.useOriginSurcharge);
    // (deviceRef.current?.setting as { receipts?: boolean })
    requestParams.current = {
      amount: new Decimal((_payRef$current = payRef.current) === null || _payRef$current === void 0 ? void 0 : _payRef$current.total).mul(100).toFixed(0, Decimal.ROUND_HALF_UP),
      // 手续费 true tyro 手续费, false 系统手续费
      enableSurcharge: ((_deviceRef$current6 = deviceRef.current) === null || _deviceRef$current6 === void 0 || (_deviceRef$current6 = _deviceRef$current6.setting) === null || _deviceRef$current6 === void 0 ? void 0 : _deviceRef$current6.useOriginSurcharge) || false,
      // 打印小票 true 打印到系统上 false 打印到pos机上
      integratedReceipt: !((_deviceRef$current7 = deviceRef.current) !== null && _deviceRef$current7 !== void 0 && (_deviceRef$current7 = _deviceRef$current7.setting) !== null && _deviceRef$current7 !== void 0 && _deviceRef$current7.receipts),
      integrationKey: integrationKey,
      transactionId: numRef.current,
      mid: mid,
      tid: tid,
      device: JSON.stringify(deviceRef.current),
      isPrintMerchant: isPrint('merchant'),
      isPrintCustomer: isPrint('customer'),
      browserVersion: getBrowserVersion()
    };
    dispatch(updateCustom({
      requestParams: requestParams.current
    }));
    setStatus(Date.now());
    merchantReceiptRef.current = {};
    // 支付 记录
    api.addTransaction({
      order_id: orderIdRef.current,
      number: numRef.current,
      card_reader_id: (_deviceRef$current8 = deviceRef.current) === null || _deviceRef$current8 === void 0 ? void 0 : _deviceRef$current8.id,
      card_reader_type: eftpos,
      amount: requestParams.current.amount,
      action: modeRef.current === ModeEnum.FullPay ? ModeEnum.Pay : modeRef.current,
      status: 'pending',
      request: requestParams.current,
      response: {},
      metadata: {
        receipt: []
      },
      _config: {
        retry: {
          count: 10,
          delay: 500
        }
      }
    }).then(function (res) {
      requestIdRef.current = res.data.id;
      dispatch(updateCustom({
        requestId: res.data.id
      }));
    });
    payLog.setContext({
      transactionNumber: numRef.current
    });
    payLog.log('Tyro：发起支付', {
      number: numRef.current,
      amount: requestParams.current.amount
    });
    iClient.initiatePurchase(requestParams.current, {
      receiptCallback: receiptCallbackImpl,
      transactionCompleteCallback: transactionCompleteCallbackImpl,
      questionCallback: questionCallbackImpl,
      statusMessageCallback: statusMessageCallbackImpl
    });
  };

  /**
   * @title: 恢复上一次支付
   * @Author: hongbing.wang
   * @Date: 2024-08-19 11:33
   */
  var continueLastOrder = function continueLastOrder() {
    var iClient = iClientRef.current;
    if (!iClient) {
      return;
    }
    if (isCancelRef.current) {
      return;
    }
    setStatus(Date.now());
    merchantReceiptRef.current = {};
    payLog.log('Tyro：恢复上次交易');
    iClient.continueLastTransaction({
      receiptCallback: receiptCallbackImpl,
      transactionCompleteCallback: transactionCompleteCallbackImpl,
      questionCallback: questionCallbackImpl,
      statusMessageCallback: statusMessageCallbackImpl
    });
  };

  /**
   * @title: 获取商家小票回调信息
   * @description: 获取小票回调信息
   * @param {{signatureRequired:boolean,merchantReceipt:string}} signatureRequired: 是否打印小票, merchantReceipt:小票内容
   * @Author: hongbing.wang
   * @Date: 2024-08-19 11:33
   */
  var receiptCallbackImpl = function receiptCallbackImpl(_ref3) {
    var signatureRequired = _ref3.signatureRequired,
      merchantReceipt = _ref3.merchantReceipt;
    payLog.log('Tyro：小票回调', {
      signatureRequired: signatureRequired,
      hasReceipt: !!merchantReceipt
    });
    var receipt = [merchantReceipt].filter(function (item) {
      return typeof item === 'string';
    }).filter(Boolean);
    merchantReceiptRef.current = {
      signatureRequired: signatureRequired,
      merchantReceipt: merchantReceipt
    };
    if (signatureRequired) {
      onChange('print', receipt);
      return;
    }
    if (isPrint('merchant')) {
      onChange('print', receipt);
    }
  };

  /**
   * @title: 支付状态回调函数
   * @description:
   * @param {string} message
   * @return {*}
   * @Author: hongbing.wang
   * @Date: 2024-08-19 11:34
   */
  var statusMessageCallbackImpl = function statusMessageCallbackImpl(message) {
    var _listRef$current;
    payLog.log('Tyro：状态消息', {
      message: message
    });
    var translateMsg = locales.getText('page.eftpos-pay.text.tyro')(message);
    var msg = Array.isArray(translateMsg) ? translateMsg.reduce(function (accumulator, currentValue) {
      return accumulator + ' ' + currentValue;
    }, '') : translateMsg;
    var lastitem = listRef.current[listRef.current.length - 1];
    var key = locales.getText('page.eftpos-pay.text.tyro')('Connection lost. Attempting to recover');
    if (msg === key && lastitem && lastitem.pedding === key) {
      return;
    }
    console.log('message = ', message);
    console.log('msg = ', msg);
    dispatch(updateCustom({
      list: [].concat(_toConsumableArray(listRef.current || []), [{
        status: 'pendding',
        pedding: msg,
        resolve: msg,
        reject: msg,
        index: ((_listRef$current = listRef.current) === null || _listRef$current === void 0 ? void 0 : _listRef$current.length) || 0
      }])
    }));
  };

  /**
   * @title: 支付提示下操作信息
   * @Author: hongbing.wang
   * @Date: 2024-08-19 11:34
   */
  var questionCallbackImpl = function questionCallbackImpl(question, answerCallback) {
    payLog.log('Tyro：交互问题回调', {
      question: question
    });
    setStatus(-1);
    setManually(false);
    var msg = locales.getText('page.eftpos-pay.text.tyro')(question.text);
    dispatch(updateCustom({
      btnList: question.options.map(function (item) {
        return /*#__PURE__*/React.createElement(Button, {
          key: item,
          type: item === 'YES' || item === 'RETRY' ? 'primary' : 'default',
          className: "pisell-lowcode__eft-pay-step-item-btn",
          onClick: function onClick() {
            dispatch(updateCustom({
              btnList: []
            }));
            setManually(false);
            dispatch(updateState({
              status: 'loading',
              title: locales.getText('page.eftpos-pay.text.loading')(modeRef.current),
              subTitle: ''
            }));
            setStatus(Date.now());
            answerCallback(item);
          }
        }, locales.getText('page.eftpos-pay.text.tyro-btn')(item));
      })
    }));
    var status = question.isError ? 'fail' : 'warn';
    dispatch(updateState(Array.isArray(msg) ? {
      status: status,
      title: msg[0],
      subTitle: msg[1]
    } : {
      status: status,
      title: msg
    }));
  };

  /**
   * @title: 支付完成-支付状态回调函数
   * @param {any} response
   * @Author: hongbing.wang
   * @Date: 2024-08-19 11:35
   */
  var transactionCompleteCallbackImpl = function transactionCompleteCallbackImpl(response) {
    var _deviceRef$current9;
    setStatus(-1);
    setManually(false);
    payLog.log('Tyro：交易完成回调', {
      response: response
    });
    var receipt = [// merchantReceiptRef.current?.merchantReceipt,
    response === null || response === void 0 ? void 0 : response.customerReceipt].filter(function (item) {
      return typeof item === 'string';
    }).filter(Boolean);
    api.editTransaction(requestIdRef.current, {
      order_id: orderIdRef.current,
      number: numRef.current,
      card_reader_id: (_deviceRef$current9 = deviceRef.current) === null || _deviceRef$current9 === void 0 ? void 0 : _deviceRef$current9.id,
      card_reader_type: eftpos,
      amount: requestParams.current.amount,
      action: modeRef.current === ModeEnum.FullPay ? ModeEnum.Pay : modeRef.current,
      request: requestParams.current,
      status: response.result === 'APPROVED' ? 'succeed' : 'failed',
      response: _objectSpread(_objectSpread({}, response), {}, {
        merchantReceipt: merchantReceiptRef.current
      }),
      metadata: {
        receipt: receipt
      }
    });
    dispatch(updateCustom({
      btnList: []
    }));
    // 保存入库
    if (response.result === 'APPROVED') {
      // 支付成功
      dispatch(updateState({
        status: 'success',
        title: locales.getText('page.eftpos-pay.text.successful')(mode),
        subTitle: ''
      }));
      dispatch(updateCustom({
        card_reader_surcharge: response.surchargeAmount || 0,
        receipt: receipt
      }));
      clearRef.current = setTimeout(function () {
        var params = getPayParams({
          mode: modeRef.current,
          amount: amountRef.current,
          order_id: orderIdRef.current,
          number: numRef.current,
          device: deviceRef.current,
          pay: payRef.current,
          custom: {
            card_reader_surcharge: response.surchargeAmount || 0,
            receipt: receipt
          }
        }, 'success');
        onChange('success', _objectSpread(_objectSpread({}, params), {}, {
          receipt: isPrint('customer') ? receipt : []
        }));
      }, 1000);
      return;
    } else {
      var _deviceRef$current10;
      var current = (_deviceRef$current10 = deviceRef.current) !== null && _deviceRef$current10 !== void 0 && _deviceRef$current10.setting.receipts ? [] : receipt;
      if (current.length > 0) {
        if (isPrint('customer')) {
          onChange('print', receipt);
        }
      }
    }
    if (response.result === 'UNKNOWN') {
      dispatch(updateCustom({
        errorStatus: 'unknow' // unknow know unknown
      }));
      dispatch(updateComponent('UnknowFail'));
      return;
    }
    // SYSTEM ERROR
    // CANCELLED
    // REVERSED
    // NOT STARTED

    dispatch(updateState({
      status: 'fail'
    }));
    dispatch(updateCustom({
      failCustom: {
        isPosNetworkError: false,
        status: 'fail',
        fail: response.result,
        //locales.getText('page.eftpos-pay.text.transaction.fail'),
        warn: null,
        title: locales.getText('page.eftpos-pay.text.failed')(modeRef.current)
      }
    }));
    dispatch(updateComponent('FailCustom'));
  };
  useEffect(function () {
    var config = deviceRef.current.config;
    var apiKey = config.apiKey,
      posProductData = config.posProductData;
    if (load && TyroRef.current) {
      var _IClient = TyroRef.current.IClient;
      if (_IClient) {
        var iclient = new _IClient(apiKey, posProductData);
        iClientRef.current = iclient;
        payLog.log('Tyro：SDK 初始化完成');
        if (isCancelRef.current) {
          return;
        }
        if (!numRef.current) {
          if (modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay) {
            payLog.log('Tyro：支付交易，查询终端信息');
            getTerminalInfo(payOrder);
          } else if (modeRef.current === ModeEnum.Refund) {
            payLog.log('Tyro：退款交易，查询终端信息');
            getTerminalInfo(refundOrder);
          }
        } else {
          payLog.log('Tyro：恢复上次交易，查询终端信息');
          getTerminalInfo(continueLastOrder);
        }
      }
    }
  }, [load]);
  var onNotin = function onNotin() {
    onChange('print', [], 'print_on_timeout');
  };
  useEffect(function () {
    var clear;
    if (status === -1) {
      return function () {
        if (clear) {
          clearTimeout(clear);
        }
      };
    }
    if (status === 0) {
      clear = setTimeout(function () {
        payLog.log('Tyro：连接超时');
        dispatch(updateState({
          status: 'fail'
        }));
        dispatch(updateCustom({
          failCustom: {
            status: 'fail',
            fail: locales.getText('page.eftpos-pay.text.transaction.pay.fail.timeout'),
            title: locales.getText('page.eftpos-pay.text.transaction.fail.timeout'),
            warn: null
          }
        }));
        dispatch(updateComponent('FailCustom'));
      }, Minute);
      return function () {
        if (clear) {
          clearTimeout(clear);
        }
      };
    }
    clear = setTimeout(function () {
      var iClient = iClientRef.current;
      if (!iClient) {
        return;
      }
      payLog.log('Tyro：交易超时，显示手动标记');
      setManually(true);
    }, Minute);
    return function () {
      if (clear) {
        clearTimeout(clear);
      }
    };
  }, [status]);
  var onManually = function onManually() {
    payLog.log('Tyro：点击手动标记');
    dispatch(updateState({
      manual: {
        title: locales.getText('page.eftpos-pay.text.request.title')(mode),
        text: locales.getText('page.eftpos-pay.text.request.text')(mode)
      }
    }));
    dispatch(updateComponent('Manual', true));
  };

  /**
   * @title: 取消支付
   * @description:
   * @return {*}
   * @Author: hongbing.wang
   * @Date: 2024-09-13 13:42
   */
  var onCancel = function onCancel() {
    var iClient = iClientRef.current;
    if (!iClient) {
      return;
    }
    if (status > 0) {
      payLog.log('Tyro：取消当前交易');
      iClient.cancelCurrentTransaction();
      return;
    }
    if (isCancelRef.current) {
      return;
    }
    payLog.log('Tyro：取消（交易未开始）');
    isCancelRef.current = true;
    dispatch(updateState({
      status: 'fail'
    }));
    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'));

    // iClient.cancelCurrentTransaction();
  };
  useEffect(function () {
    return function () {
      unloadRef.current = true;
      if (clearRef.current) {
        clearTimeout(clearRef.current);
      }
    };
  }, []);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__eft-pay-body"
  }, ((custom === null || custom === void 0 ? void 0 : custom.list) || []).map(function (item) {
    return /*#__PURE__*/React.createElement(Step, {
      key: item.index,
      pedding: item.pedding,
      resolve: item.resolve,
      reject: item.reject,
      status: item.status
    });
  })), isManually ? /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__eft-pay-step-item-btns"
  }, client === ClientEnum.Merchant ? /*#__PURE__*/React.createElement(Button, {
    block: true,
    className: "pisell-lowcode__eft-pay-step-item-btn",
    onClick: onManually
  }, locales.getText('page.eftpos-pay.text.manual.marking')) : /*#__PURE__*/React.createElement(Button, {
    block: true,
    className: "pisell-lowcode__eft-pay-step-item-btn",
    onClick: onNotin
  }, locales.getText('page.eftpos-pay.text.manual.print_receipt'))) : null, /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__eft-pay-step-item-btns",
    style: {
      flexWrap: 'wrap'
    }
  }, Array.isArray(custom === null || custom === void 0 ? void 0 : custom.btnList) && (custom === null || custom === void 0 ? void 0 : custom.btnList).length > 0 ? /*#__PURE__*/React.createElement("div", {
    style: {
      width: '100%',
      display: 'flex',
      gap: '12px'
    }
  }, custom === null || custom === void 0 ? void 0 : custom.btnList) : null, !(payStatus === 'success' || payStatus === 'fail') ? /*#__PURE__*/React.createElement(Button, {
    block: true,
    type: "text",
    disabled: Array.isArray(custom === null || custom === void 0 ? void 0 : custom.btnList) && (custom === null || custom === void 0 ? void 0 : custom.btnList).length > 0,
    className: "pisell-lowcode__eft-pay-step-item-btn",
    onClick: onCancel
  }, locales.getText('page.eftpos-pay.text.manual.cancel')) : null));
});