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 _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; }
/* eslint-disable react/jsx-no-useless-fragment */
/* eslint-disable no-nested-ternary */
/* eslint-disable @typescript-eslint/no-use-before-define */
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable consistent-return */
/* eslint-disable react/no-array-index-key */
/* eslint-disable array-callback-return */
import { locales } from '@pisell/utils';
import React, { useEffect, useMemo, useRef, useState } from 'react';
import Step from "../component/step/step";
import { ModeEnum, StatusEnum } from "../const";
import { getPayParams, getUuid } from "../helper";
import { useStoreRef } from "../hooks";
import { updateCustom, updateState, useContextData, useDispatch } from "../store";
import { StemTypeEnum, StepStatusEnum, getStepMapping } from "./const";
import { useFail, useValidate } from "./helper";
import payLog from "../utils/payLog";
import Action, { ReceiptAction } from "./receiptAction";
var Minute = 1000 * 60;

// 注意断网与卸载未完成的回调将终止处理
export default (function (_ref) {
  var api = _ref.api,
    onChange = _ref.onChange,
    _ref$formatAmount = _ref.formatAmount,
    formatAmount = _ref$formatAmount === void 0 ? function (number, precision, symbol) {
      return "".concat(symbol).concat(number);
    } : _ref$formatAmount;
  var _useContextData = useContextData(),
    custom = _useContextData.custom,
    status = _useContextData.status;
  var _useStoreRef = useStoreRef(),
    deviceRef = _useStoreRef.deviceRef,
    payRef = _useStoreRef.payRef,
    numRef = _useStoreRef.numRef,
    orderIdRef = _useStoreRef.orderIdRef,
    modeRef = _useStoreRef.modeRef,
    statusRef = _useStoreRef.statusRef,
    netRef = _useStoreRef.netRef,
    symbolRef = _useStoreRef.symbolRef,
    amountRef = _useStoreRef.amountRef,
    eftposRef = _useStoreRef.eftposRef,
    dataRef = _useStoreRef.dataRef;
  var dispatch = useDispatch();
  var fail = useFail();
  var failRef = useRef(fail);
  var unloadRef = useRef(false);
  var stepRef = useRef(custom === null || custom === void 0 ? void 0 : custom.step);
  var listRef = useRef(custom === null || custom === void 0 ? void 0 : custom.list);
  var initRef = useRef(false);
  var clearRef = useRef(null);

  /** 是否是签名页面 */
  var isReceiptPage = useMemo(function () {
    return (custom === null || custom === void 0 ? void 0 : custom.step) === StepStatusEnum.Receipt;
  }, [custom === null || custom === void 0 ? void 0 : custom.step]);
  /** 签名页面状态 */
  var receiptPage = useMemo(function () {
    return (custom === null || custom === void 0 ? void 0 : custom.step) !== StepStatusEnum.Receipt ? '' : (custom === null || custom === void 0 ? void 0 : custom.receiptPage) || 'receipt';
  }, [custom === null || custom === void 0 ? void 0 : custom.step, custom === null || custom === void 0 ? void 0 : custom.receiptPage]);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    disabled = _useState2[0],
    setDisabled = _useState2[1];
  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]);
  useEffect(function () {
    failRef.current = fail;
  }, [fail]);

  /**
   * @title:  查询支付状态
   * @description: 轮询 api.check 检查支付状态, 中间状态转换在 useValidate 中进行,结束在当前回调中完成
   * @param {*} useValidate
   * @return {*}
   * @Author: hongbing.wang
   * @Date: 2024-08-12 11:02
   */
  var _useValidate = useValidate(api.check, Minute, function (res) {
      var receipt = Array.isArray(res === null || res === void 0 ? void 0 : res.receipt) ? res.receipt : [res.receipt];
      receipt = receipt.filter(function (item) {
        return typeof item === 'string';
      }).filter(Boolean);
      // 将所有步骤状态设为完成 resolve
      dispatch(updateCustom({
        list: listRef.current.map(function (item) {
          return _objectSpread(_objectSpread({}, item), {}, {
            status: 'resolve'
          });
        }),
        card_reader_surcharge: (res === null || res === void 0 ? void 0 : res.card_reader_surcharge) || 0,
        receipt: receipt
      }));

      // 更新支付状态与文案
      dispatch(updateState({
        status: 'success',
        title: locales.getText('page.eftpos-pay.text.successful')(modeRef.current)
      }));
      clearRef.current = setTimeout(function () {
        var _deviceRef$current;
        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: (res === null || res === void 0 ? void 0 : res.card_reader_surcharge) || 0,
            receipt: receipt
          }
        }, 'success');
        onChange('success', _objectSpread(_objectSpread({}, params), {}, {
          receipt: (_deviceRef$current = deviceRef.current) !== null && _deviceRef$current !== void 0 && (_deviceRef$current = _deviceRef$current.setting) !== null && _deviceRef$current !== void 0 && _deviceRef$current.receipts ? [] : receipt
        }));
      }, 1000);
    }),
    _useValidate2 = _slicedToArray(_useValidate, 2),
    run = _useValidate2[0],
    validateRef = _useValidate2[1];
  var controllerRef = useRef();
  useEffect(function () {
    if (statusRef.current === StatusEnum.Success || statusRef.current === StatusEnum.Fail) {
      return;
    }
    if (initRef.current) {
      return;
    }
    initRef.current = true;
    // 是否在签名步骤
    if (stepRef.current === StepStatusEnum.Receipt) {
      if (StatusEnum.Loading === statusRef.current) {
        payLog.log('Windcave：签名页面处于运行中(已发送签名,或取消签名接口),进行计时查询');
        // 签名页面处于运行中(已发送签名,或取消签名接口),则进行计时查询
        run();
      } else {
        payLog.log('Windcave：签名页面处于未加载中,进行无限查询');
        // 签名页面处于未加载中,则进行无限查询
        run(-1);
      }
      return;
    }
    controllerRef.current = new AbortController();

    // 存在支付流水号
    if (numRef.current) {
      // 计时查询
      run();
      return;
    }
    numRef.current = getUuid();
    dispatch(updateState({
      number: numRef.current
    }));
    var isPay = modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay;
    var _params = {};
    if (isPay) {
      var _deviceRef$current2;
      _params = _objectSpread(_objectSpread({}, custom !== null && custom !== void 0 && custom.platform ? {
        operator_id: custom.operator_id,
        operator_type: custom.operator_type,
        platform: custom.platform,
        custom_payment_id: custom.custom_payment_id
      } : {}), {}, {
        service_charge: {
          amount: payRef.current.surMoney,
          percentage: payRef.current.surPercentRate
        },
        original_amount: payRef.current.amount,
        order_id: orderIdRef.current,
        amount: payRef.current.total,
        card_reader_type: eftposRef.current,
        card_reader_id: (_deviceRef$current2 = deviceRef.current) === null || _deviceRef$current2 === void 0 ? void 0 : _deviceRef$current2.id,
        number: numRef.current,
        pay_param_base64: encodeURIComponent(btoa(encodeURIComponent(JSON.stringify(_objectSpread(_objectSpread({}, dataRef.current), {}, {
          number: numRef.current
        })))))
      });
    } else {
      var _deviceRef$current3;
      _params = {
        order_id: orderIdRef.current,
        amount: amountRef.current,
        card_reader_type: eftposRef.current,
        card_reader_id: (_deviceRef$current3 = deviceRef.current) === null || _deviceRef$current3 === void 0 ? void 0 : _deviceRef$current3.id,
        number: numRef.current,
        pay_param_base64: encodeURIComponent(btoa(encodeURIComponent(JSON.stringify(_objectSpread(_objectSpread({}, dataRef.current), {}, {
          number: numRef.current
        })))))
      };
    }
    payLog.setContext({
      transactionNumber: numRef.current
    });
    if (isPay) {
      payLog.log('Windcave：发起支付', {
        number: numRef.current
      });
    } else {
      payLog.log('Windcave：发起退款', {
        number: numRef.current
      });
    }
    var resultPromise = isPay ? api.pay(_params, {
      signal: controllerRef.current.signal
    }) : api.refund(_params, {
      signal: controllerRef.current.signal
    });
    resultPromise.then(function (res) {
      var _failRef$current;
      // 无网 或 已卸载 则不进行处理
      if (unloadRef.current || !netRef.current) {
        return;
      }
      if (res && "".concat(res.code) === '200' && res.data && res.data.txn_status_id) {
        var _res$data, _validateRef$current;
        payLog.log('Windcave：接口成功，进入轮询', {
          txn_status_id: res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.txn_status_id
        });
        (_validateRef$current = validateRef.current) === null || _validateRef$current === void 0 || _validateRef$current.call(validateRef, res, true);
        return;
      }
      payLog.log('Windcave：支付接口返回失败', {
        code: res === null || res === void 0 ? void 0 : res.code
      });
      (_failRef$current = failRef.current) === null || _failRef$current === void 0 || _failRef$current.call(failRef, res, stepRef.current >= StepStatusEnum.Account);
    }).catch(function (res) {
      var _failRef$current2;
      var isNoNet = unloadRef.current || !netRef.current;
      payLog.log('Windcave：支付接口异常', {
        error: res === null || res === void 0 ? void 0 : res.message,
        isNoNet: isNoNet
      });
      if (isNoNet) {
        return;
      }
      (_failRef$current2 = failRef.current) === null || _failRef$current2 === void 0 || _failRef$current2.call(failRef, res, stepRef.current >= StepStatusEnum.Account);
    });
    return;
  }, [api, run, dispatch]);

  /**
   * @title: 取消支付
   * @Author: hongbing.wang
   * @Date: 2024-08-20 12:51
   */
  var onCancel = function onCancel() {
    payLog.log('Windcave：点击取消支付');
    setDisabled(true);
    api.update({
      type: 'CANCEL',
      number: numRef.current
    });
  };
  useEffect(function () {
    return function () {
      var _controllerRef$curren, _controllerRef$curren2;
      unloadRef.current = true;
      (_controllerRef$curren = controllerRef.current) === null || _controllerRef$curren === void 0 || (_controllerRef$curren2 = _controllerRef$curren.abort) === null || _controllerRef$curren2 === void 0 || _controllerRef$curren2.call(_controllerRef$curren);
      if (clearRef.current) {
        clearTimeout(clearRef.current);
      }
    };
  }, []);

  /**
   * @title:  签名状态
   * @param {boolean} status 签名状态
   * @Author: hongbing.wang
   * @Date: 2024-08-20 12:54
   */
  var onChangeReceipt = function onChangeReceipt(status) {
    if (status) {
      payLog.log('Windcave：签名状态');
      // 签名,取消签名接口执行成功, 进行计时查询
      run();
    }
  };
  useEffect(function () {
    if (listRef.current.length === 0) {
      // 总金额(+ 单位)
      var totalUnit = '';
      if (modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay) {
        var _payRef$current;
        // 支付状态,前往pay中获取
        totalUnit = (_payRef$current = payRef.current) === null || _payRef$current === void 0 ? void 0 : _payRef$current.totalUnit;
      } else if (modeRef.current === ModeEnum.Refund) {
        // 退款状态,直接使用总额(退款状态不存在金额编辑)
        if (payRef.current) {
          totalUnit = payRef.current.totalUnit;
        } else {
          totalUnit = formatAmount(amountRef.current, 2, symbolRef.current);
          dispatch(updateState({
            pay: {
              total: amountRef.current,
              totalUnit: totalUnit
            }
          }));
        }
      }
      var nextStep = getStepMapping(StepStatusEnum.Free, {
        money: totalUnit,
        mode: modeRef.current
      });
      dispatch(updateCustom({
        list: [nextStep],
        step: StepStatusEnum.Free
      }));
    }
  }, [dispatch]);
  return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__eft-pay-body"
  }, receiptPage !== 'again' ? (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,
      className: item.type === StemTypeEnum.Passive && item.status === 'pedding' ? 'pisell-lowcode__eft-pay-step-item-warn' : ''
    });
  }) : null, receiptPage === 'again' ? /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__eft-pay-warn-text pisell-lowcode__eft-pay-body"
  }, locales.getText('page.eftpos-pay.text.signature.text')(modeRef.current)) : null, status === StatusEnum.Loading ? /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip"
  }, locales.getText('page.eftpos-pay.text.processing')) : null, status === StatusEnum.Success ? /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip"
  }, locales.getText('page.eftpos-pay.text.transaction.end')) : null), !isReceiptPage && status !== StatusEnum.Success ? /*#__PURE__*/React.createElement(Action, {
    index: custom === null || custom === void 0 ? void 0 : custom.step,
    onCancel: onCancel,
    disabled: disabled
  }) : null, isReceiptPage ? /*#__PURE__*/React.createElement(ReceiptAction, {
    api: api,
    onChange: onChangeReceipt
  }) : null);
});