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); }
import React, { useEffect, useRef } from 'react';
import { locales } from '@pisell/utils';
import "./index.less";
import { useContextData, updateStatus, updateState } from "../store";
import { ScanAction } from "./Action";
import { useMicropay } from "../aggregatePayment";
import { EPaymentStatus } from "../aggregatePayment/types";
import { useStoreRef, useFail } from "../hooks";
import { useDispatch, updateNextStep, updateCustom } from "../store";
import { ModeEnum, StatusEnum } from "../const";
import { getPayParams } from "../helper";
import useEngineContext from "../../../hooks/useEngineContext";
var Huifu = function Huifu(_ref) {
  var _context$appHelper, _data$custom;
  var isNativeApp = _ref.isNativeApp,
    onChange = _ref.onChange;
  var data = useContextData();
  var context = useEngineContext();
  var _ref2 = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {},
    interaction = _ref2.interaction;

  // 数据源
  var _useStoreRef = useStoreRef(),
    statusRef = _useStoreRef.statusRef,
    numRef = _useStoreRef.numRef,
    netRef = _useStoreRef.netRef,
    modeRef = _useStoreRef.modeRef,
    amountRef = _useStoreRef.amountRef,
    orderIdRef = _useStoreRef.orderIdRef,
    deviceRef = _useStoreRef.deviceRef,
    payRef = _useStoreRef.payRef;
  var dispatch = useDispatch();
  var fail = useFail(0);
  var failRef = useRef(fail);

  // 当前组件数据
  var initRef = useRef(false);
  var unloadRef = useRef(false);
  var clearRef = useRef(null);
  var payment = useMicropay({
    paymentCode: (data === null || data === void 0 || (_data$custom = data.custom) === null || _data$custom === void 0 ? void 0 : _data$custom.custom_payment_code) || 'EFTPOS_HUIFU',
    paymentNum: numRef.current || '',
    shouldContinue: function shouldContinue() {
      return !(unloadRef.current || !netRef.current);
    },
    callback: function callback(_instance, response) {
      console.log('callback = ', response);
      var _ref3 = response || {},
        status = _ref3.status,
        data = _ref3.data;
      if (status === EPaymentStatus.Success) {
        dispatch(updateNextStep());
        // 将所有步骤状态设为完成 resolve
        dispatch(updateCustom({
          card_reader_surcharge: 0,
          receipt: []
        }));
        // 更新支付状态与文案
        dispatch(updateState({
          status: 'success',
          title: locales.getText('page.eftpos-pay.text.successful')(modeRef.current)
        }));
        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: 0,
              receipt: []
            }
          }, 'success');
          onChange('success', _objectSpread(_objectSpread({}, params), {}, {
            receipt: []
          }));
        }, 1000);
      } else if (status === EPaymentStatus.Failed) {
        var _failRef$current;
        (_failRef$current = failRef.current) === null || _failRef$current === void 0 || _failRef$current.call(failRef, data, false);
      }
    }
  });
  useEffect(function () {
    failRef.current = fail;
  }, [fail]);
  useEffect(function () {
    if (statusRef.current === StatusEnum.Success || statusRef.current === StatusEnum.Fail) {
      return;
    }
    if (initRef.current) {
      return;
    }
    initRef.current = true;

    // 存在支付流水号
    if (numRef.current) {
      console.log('payment.query');
      payment.query();
      return;
    }
    console.log('data?.custom =>>>> ', data === null || data === void 0 ? void 0 : data.custom);
    // 如果是退款场景，直接进入退款流程
    var isPay = modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay;
    if (!isPay) {
      var _data$custom2;
      payment.run({
        orderPaymentId: data === null || data === void 0 || (_data$custom2 = data.custom) === null || _data$custom2 === void 0 ? void 0 : _data$custom2.order_payment_id
      });
      return;
    }
  }, []);
  useEffect(function () {
    if (isNativeApp && (data === null || data === void 0 ? void 0 : data.status) === StatusEnum.Init) {
      var _interaction$utils, _interaction$utils$po;
      // 如果是原生App调用并且是init状态，则显示关闭按钮
      interaction === null || interaction === void 0 || (_interaction$utils = interaction.utils) === null || _interaction$utils === void 0 || (_interaction$utils$po = _interaction$utils.postMessageToApp) === null || _interaction$utils$po === void 0 || _interaction$utils$po.call(_interaction$utils, {
        module: 'pos',
        key: 'other',
        data: {
          key: 'show_close_button'
        }
      });
    }
  }, [isNativeApp, data === null || data === void 0 ? void 0 : data.status]);

  // 页面卸载处理
  useEffect(function () {
    return function () {
      unloadRef.current = true;
      if (clearRef.current) {
        clearTimeout(clearRef.current);
      }
    };
  }, []);

  /**
   * 更新到加载状态
   */
  var updateToLoading = function updateToLoading() {
    // 如果是原生App调用，进入加载状态则隐藏关闭按钮
    if (isNativeApp) {
      var _interaction$utils2, _interaction$utils2$p;
      interaction === null || interaction === void 0 || (_interaction$utils2 = interaction.utils) === null || _interaction$utils2 === void 0 || (_interaction$utils2$p = _interaction$utils2.postMessageToApp) === null || _interaction$utils2$p === void 0 || _interaction$utils2$p.call(_interaction$utils2, {
        module: 'pos',
        key: 'other',
        data: {
          key: 'hide_close_button'
        }
      });
    }
    dispatch(updateStatus(StatusEnum.Loading));
    dispatch(updateState({
      title: locales.getText('page.eftpos-pay.text.loading')(modeRef.current)
    }));
  };
  var onClose = function onClose() {
    onChange('fail', {
      number: data.number,
      uniquePaymentNumber: data.number,
      device: data.device,
      order_id: data.order_id
    });
  };
  var onPayClick = function onPayClick(scanResult) {
    console.log('scanResult = ', scanResult);
    updateToLoading();
    payment.run({
      authCode: scanResult
    });
  };
  var onScanCallback = function onScanCallback(scanResult) {
    console.log('scanResult = ', scanResult);
    updateToLoading();
    payment.run({
      authCode: scanResult
    });
  };
  return /*#__PURE__*/React.createElement(React.Fragment, null, (data === null || data === void 0 ? void 0 : data.status) === StatusEnum.Init && /*#__PURE__*/React.createElement(ScanAction, {
    onClose: onClose,
    onScanCallback: onScanCallback,
    onPayClick: onPayClick,
    isNativeApp: isNativeApp
  }), (data === null || data === void 0 ? void 0 : data.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);
};
export default Huifu;