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); }
var _excluded = ["key"];
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; }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
/* eslint-disable no-unused-vars */
/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable consistent-return */
/* eslint-disable @typescript-eslint/no-unused-expressions */
/* eslint-disable @typescript-eslint/naming-convention */
import { locales } from '@pisell/utils';
import { Button } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import Step from "../component/step";
import { PayStatus, StatusEnum, ModeEnum, ClientEnum } from "../const";
import { getUuid, getPayParams } from "../helper";
import { useFail, useStoreRef } from "../hooks";
import { useContextData, useDispatch, updateNextStep, updateComponent, updateState, updateCustom } from "../store";
import { useValidate } from "./hooks";

// 注意断网与卸载未完成的回调将终止处理
export var POS = function POS(_ref) {
  var api = _ref.api,
    onChange = _ref.onChange;
  var _useContextData = useContextData(),
    steps = _useContextData.steps,
    custom = _useContextData.custom;
  var _useStoreRef = useStoreRef(),
    deviceRef = _useStoreRef.deviceRef,
    payRef = _useStoreRef.payRef,
    numRef = _useStoreRef.numRef,
    statusRef = _useStoreRef.statusRef,
    modeRef = _useStoreRef.modeRef,
    netRef = _useStoreRef.netRef,
    orderIdRef = _useStoreRef.orderIdRef,
    amountRef = _useStoreRef.amountRef,
    eftposRef = _useStoreRef.eftposRef,
    dataRef = _useStoreRef.dataRef;
  var dispatch = useDispatch();
  var _steps$ = steps[0],
    key = _steps$.key,
    props = _objectWithoutProperties(_steps$, _excluded);
  var fail = useFail(0);
  var failRef = useRef(fail);
  var controllerRef = useRef();
  var clearRef = useRef();
  var initRef = useRef(false);
  var unloadRef = useRef(false);
  var _useValidate = useValidate(1000 * 60),
    _useValidate2 = _slicedToArray(_useValidate, 1),
    check = _useValidate2[0];
  useEffect(function () {
    failRef.current = fail;
  }, [fail]);

  /**
   * @title: 支付,退款,查询 成功 后续逻辑处理
   * @description:
   * @return {*}
   * @Author: zhiwei.Wang
   * @Date: 2024-01-30 16:34
   */
  var success = function success(res) {
    var _res$data, _res$data2, _res$data3, _res$data4;
    var receipt = Array.isArray(res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.receipt) ? res === null || res === void 0 || (_res$data2 = res.data) === null || _res$data2 === void 0 ? void 0 : _res$data2.receipt : [res === null || res === void 0 || (_res$data3 = res.data) === null || _res$data3 === void 0 ? void 0 : _res$data3.receipt];
    receipt = receipt.filter(function (item) {
      return typeof item === 'string';
    }).filter(Boolean);
    dispatch(updateNextStep());
    dispatch(updateCustom({
      card_reader_surcharge: (res === null || res === void 0 || (_res$data4 = res.data) === null || _res$data4 === void 0 ? void 0 : _res$data4.card_reader_surcharge) || 0,
      receipt: receipt
    }));
    clearRef.current = setTimeout(function () {
      var _res$data5, _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 || (_res$data5 = res.data) === null || _res$data5 === void 0 ? void 0 : _res$data5.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);
  };

  /**
   * @title: 检查支付状态
   * @Author: hongbing.wang
   * @Date: 2024-08-20 11:53
   */
  var checkApi = function checkApi() {
    check(api.check, numRef.current).then(function (res) {
      // 无网 或 已卸载 则不进行处理
      if (unloadRef.current || !netRef.current) {
        return;
      }
      if (res && "".concat(res.code) === '200') {
        success(res);
        return;
      }
      failRef.current(res, true);
    }, function (res) {
      // 无网 或 已卸载 则不进行处理
      if (unloadRef.current || !netRef.current) {
        return;
      }
      failRef.current(res, true);
    });
  };

  /**
   * @title: 支付,退款,查询 初始化逻辑处理
   * @Author: hongbing.wang
   * @Date: 2024-08-12 10:14
   */
  useEffect(function () {
    var _deviceRef$current2, _deviceRef$current3;
    if (statusRef.current === StatusEnum.Success || statusRef.current === StatusEnum.Fail) {
      return;
    }
    if (initRef.current) {
      return;
    }
    initRef.current = true;
    // 存在交易流水进行查询
    if (numRef.current) {
      checkApi();
      return;
    }
    numRef.current = getUuid();
    dispatch(updateState({
      number: numRef.current
    }));
    controllerRef.current = new AbortController();
    // 支付 or 退款
    var resultPromise = modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay ? api.pay(_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
      })))))
    }), {
      signal: controllerRef.current.signal
    }) : api.refund({
      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
      })))))
    }, {
      signal: controllerRef.current.signal
    });
    resultPromise.then(function (res) {
      console.log('netRef.current111 = ', netRef.current);
      if (unloadRef.current || !netRef.current) {
        return;
      }
      if (res && "".concat(res.code) === '200') {
        success(res);
        return;
      }
      return Promise.reject(res);
    }).catch(function (err) {
      console.log('netRef.current222 = ', netRef.current, unloadRef.current, err);
      if (unloadRef.current || !netRef.current) {
        return;
      }
      // 支付接口超时 进行支付状态查询
      if (err && "".concat(err.code) === PayStatus.Timeout) {
        checkApi();
        return;
      }
      failRef.current(err, true);
    });
  }, [api, check, dispatch, onChange]);
  useEffect(function () {
    return function () {
      var _controllerRef$curren;
      (_controllerRef$curren = controllerRef.current) === null || _controllerRef$curren === void 0 || _controllerRef$curren.abort();
      unloadRef.current = true;
      if (clearRef.current) {
        clearTimeout(clearRef.current);
      }
    };
  }, []);
  return /*#__PURE__*/React.createElement(Step, props);
};
export var Action = function Action(_ref2) {
  var onChange = _ref2.onChange;
  var dispatch = useDispatch();
  var _useContextData2 = useContextData(),
    mode = _useContextData2.mode,
    client = _useContextData2.client,
    order_id = _useContextData2.order_id,
    number = _useContextData2.number,
    device = _useContextData2.device;
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isShowCancel = _useState2[0],
    setIsShowCancel = _useState2[1];
  useEffect(function () {
    var timer = setTimeout(function () {
      setIsShowCancel(true);
    }, 30 * 1000);
    return function () {
      clearTimeout(timer);
    };
  }, []);

  /**
   * @title: 前往手动标记页
   * @Author: hongbing.wang
   * @Date: 2024-08-20 12:18
   */
  var onManually = function onManually() {
    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));
  };
  var onCancel = function onCancel() {
    onChange('fail', {
      number: number,
      uniquePaymentNumber: number,
      device: device,
      order_id: order_id
    });
  };
  return /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__eft-pay-step-item-btns"
  }, client !== ClientEnum.Merchant && isShowCancel && /*#__PURE__*/React.createElement(Button, {
    block: true,
    className: "pisell-lowcode__eft-pay-step-item-btn",
    onClick: onCancel
  }, locales.getText('page.eftpos-pay.text.cancel')), 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')) : null);
};