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 _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 _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, useState } from 'react';
import { locales } from '@pisell/utils';
import "./index.less";
import { useContextData, useDispatch, updateState, updateNextStep, updateCustom, updateStatus } from "../store";
import { useStoreRef, useFail } from "../hooks";
import { EftposEnum, ModeEnum, PayStatus, StatusEnum } from "../const";
import { getPayParams } from "../helper";
import { AdyenScanQrcode } from "./Action";
import useEngineContext from "../../../hooks/useEngineContext";
import { usePayment } from "../aggregatePayment";
import { EPaymentStatus } from "../aggregatePayment/types";
var ADYEN_SCAN_PAYMENT_CODE_MAP = _defineProperty(_defineProperty({}, EftposEnum.AdyenAlipay, 'EFTPOS_ADYENALIPAY'), EftposEnum.AdyenWechat, 'EFTPOS_ADYENWECHAT');

// 扫码支付结果回调路径
var ADYEN_SCAN_RETURN_PATH = '/lc/tob_pay_toc-pay-result';

/**
 * 获取扫码支付结果回调 URL
 * @param defaultDomain - 默认域名
 * @param query - 需要拼接到回调地址上的查询参数
 * @returns 扫码支付结果回调 URL
 */
var getAdyenScanReturnUrl = function getAdyenScanReturnUrl(defaultDomain, query) {
  if (!defaultDomain) return '';
  var domain = defaultDomain === null || defaultDomain === void 0 ? void 0 : defaultDomain.trim().replace(/\/+$/, '');
  if (!domain) return '';
  var returnUrl = /^https?:\/\//i.test(domain) ? "".concat(domain).concat(ADYEN_SCAN_RETURN_PATH) : "https://".concat(domain).concat(ADYEN_SCAN_RETURN_PATH);
  var url = new URL(returnUrl);
  Object.entries(query || {}).forEach(function (_ref) {
    var _ref2 = _slicedToArray(_ref, 2),
      key = _ref2[0],
      value = _ref2[1];
    if (value !== undefined && value !== null && value !== '') {
      url.searchParams.set(key, "".concat(value));
    }
  });
  return url.toString();
};

/**
 * Adyen 扫码支付组件（商家被扫模式）
 */
var AdyenScan = function AdyenScan(_ref3) {
  var _context$appHelper;
  var onChange = _ref3.onChange,
    isNativeApp = _ref3.isNativeApp;
  var data = useContextData();
  var context = useEngineContext();
  var _ref4 = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {},
    interaction = _ref4.interaction,
    getApp = _ref4.getApp,
    store = _ref4.store,
    getData = _ref4.getData,
    getStore = _ref4.getStore;
  var dispatch = useDispatch();
  var _useStoreRef = useStoreRef(),
    statusRef = _useStoreRef.statusRef,
    modeRef = _useStoreRef.modeRef,
    amountRef = _useStoreRef.amountRef,
    orderIdRef = _useStoreRef.orderIdRef,
    numRef = _useStoreRef.numRef,
    deviceRef = _useStoreRef.deviceRef,
    payRef = _useStoreRef.payRef,
    netRef = _useStoreRef.netRef,
    eftposRef = _useStoreRef.eftposRef;
  var fail = useFail(0);
  var failRef = useRef(fail);
  var initRef = useRef(false);
  var unloadRef = useRef(false);
  var clearRef = useRef(null);
  var _useState = useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    loading = _useState2[0],
    setLoading = _useState2[1];
  var _useState3 = useState(''),
    _useState4 = _slicedToArray(_useState3, 2),
    qrCode = _useState4[0],
    setQrCode = _useState4[1];
  var qrCodeRef = useRef('');
  /** 支付方式类型 */
  var _useState5 = useState(''),
    _useState6 = _slicedToArray(_useState5, 2),
    payMethodType = _useState6[0],
    setPayMethodType = _useState6[1];
  var payment = usePayment({
    paymentCode: ADYEN_SCAN_PAYMENT_CODE_MAP[eftposRef.current],
    paymentNum: numRef.current || '',
    config: {
      globalQueryTimeout: modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay ? 1000 * 60 * 5 // 支付场景轮询超时时间5分钟
      : 1000 * 60 * 2 // 退款场景轮询超时时间2分钟
    },
    shouldContinue: function shouldContinue() {
      return !(unloadRef.current || !netRef.current);
    },
    callback: function callback(_instance, response) {
      console.log('response =>>>> ', response);
      var _ref5 = response || {},
        status = _ref5.status,
        data = _ref5.data;
      var needHideLoading = true;
      if (status === EPaymentStatus.Processing) {
        var _data$data;
        var _ref6 = (data === null || data === void 0 || (_data$data = data.data) === null || _data$data === void 0 || (_data$data = _data$data.external_unified_response) === null || _data$data === void 0 ? void 0 : _data$data.action) || {},
          url = _ref6.url,
          paymentMethodType = _ref6.paymentMethodType,
          qrCodeData = _ref6.qrCodeData;
        // 不同支付方式返回的二维码字段不同
        var _qrCode = url || qrCodeData;
        if (!_qrCode) {
          needHideLoading = false;
        }
        if (_qrCode && _qrCode !== qrCodeRef.current) {
          qrCodeRef.current = _qrCode;
          setQrCode(_qrCode);
          setPayMethodType(paymentMethodType);
        }
      } else if (status === EPaymentStatus.Success) {
        handleSuccess();
      } else if (status === EPaymentStatus.Failed) {
        handleFail(data);
      }
      if (needHideLoading) {
        setLoading(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;
    }

    // 根据支付/退款场景直接发起当前 Adyen 扫码类型的交易
    var isPay = modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay;
    setLoading(true);
    updateToLoading();
    if (isPay) {
      var _store$getState, _getStore, _getStore$getState, _store$getState2;
      var defaultDomain = store === null || store === void 0 || (_store$getState = store.getState()) === null || _store$getState === void 0 || (_store$getState = _store$getState.global) === null || _store$getState === void 0 || (_store$getState = _store$getState.globalConfig) === null || _store$getState === void 0 ? void 0 : _store$getState.default_domain;
      if (!defaultDomain) {
        var _getApp, _getApp$getStore, _getApp$getStore$getD;
        defaultDomain = getApp === null || getApp === void 0 || (_getApp = getApp()) === null || _getApp === void 0 || (_getApp = _getApp.data) === null || _getApp === void 0 || (_getApp = _getApp.store) === null || _getApp === void 0 || (_getApp$getStore = _getApp.getStore) === null || _getApp$getStore === void 0 || (_getApp$getStore = _getApp$getStore.call(_getApp)) === null || _getApp$getStore === void 0 || (_getApp$getStore$getD = _getApp$getStore.getDataByModel) === null || _getApp$getStore$getD === void 0 || (_getApp$getStore$getD = _getApp$getStore$getD.call(_getApp$getStore, 'core', 'core')) === null || _getApp$getStore$getD === void 0 ? void 0 : _getApp$getStore$getD.default_domain;
      }
      var shopId = (getStore === null || getStore === void 0 || (_getStore = getStore()) === null || _getStore === void 0 || (_getStore$getState = _getStore.getState) === null || _getStore$getState === void 0 || (_getStore$getState = _getStore$getState.call(_getStore)) === null || _getStore$getState === void 0 || (_getStore$getState = _getStore$getState.global) === null || _getStore$getState === void 0 || (_getStore$getState = _getStore$getState.shop) === null || _getStore$getState === void 0 ? void 0 : _getStore$getState.id) || (getData === null || getData === void 0 ? void 0 : getData('shop_id')) || (store === null || store === void 0 || (_store$getState2 = store.getState) === null || _store$getState2 === void 0 || (_store$getState2 = _store$getState2.call(store)) === null || _store$getState2 === void 0 || (_store$getState2 = _store$getState2.global) === null || _store$getState2 === void 0 || (_store$getState2 = _store$getState2.globalConfig) === null || _store$getState2 === void 0 ? void 0 : _store$getState2.id) || undefined;
      payment.run({
        getParams: function getParams(_ref7) {
          var uniquePaymentNumber = _ref7.uniquePaymentNumber;
          return {
            adyenscan: {
              return_url: getAdyenScanReturnUrl(defaultDomain, {
                payment_number: uniquePaymentNumber,
                shop_id: shopId
              }) || ''
            }
          };
        }
      });
    } else {
      var _data$custom;
      payment.run({
        params: {
          adyenscan: {
            order_payment_id: data === null || data === void 0 || (_data$custom = data.custom) === null || _data$custom === void 0 ? void 0 : _data$custom.order_payment_id
          }
        }
      });
    }
  }, []);
  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);
      }
    };
  }, []);

  /**
   * 进入 Loading 态
   * 在该步骤展示QRCode给用户扫码，不能直接关闭支付弹窗
   */
  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)
    }));
  };

  /**
   * 触发支付成功流程：更新 store 状态 → 延迟回调外部 onChange
   */
  var handleSuccess = function handleSuccess() {
    dispatch(updateNextStep());
    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 () {
      if (unloadRef.current) return;
      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);
  };

  /**
   * 触发支付失败流程：交由 useFail 统一处理失败/重试逻辑
   */
  var handleFail = function handleFail(errorData) {
    var _errorData$data, _failRef$current;
    var _ref8 = (errorData === null || errorData === void 0 || (_errorData$data = errorData.data) === null || _errorData$data === void 0 ? void 0 : _errorData$data.external_unified_response) || {},
      message = _ref8.message,
      response_code = _ref8.response_code;
    var _code = "".concat(response_code || '') || PayStatus.PaymentFailed;
    var _message = message || (errorData === null || errorData === void 0 ? void 0 : errorData.message) || '';
    console.log('handleFail =>>>> ', errorData, _code, _message);
    (_failRef$current = failRef.current) === null || _failRef$current === void 0 || _failRef$current.call(failRef, {
      code: _code,
      message: _message
    }, true);
  };

  /**
   * 取消/关闭支付弹窗
   */
  var handleClose = function handleClose() {
    onChange('fail', {
      number: data.number,
      uniquePaymentNumber: data.number,
      order_id: data.order_id
    });
  };

  /**
   * 在二维码展示阶段点击取消：
   * 弹出确认弹窗，防止顾客已扫码支付后商家误操作导致重复收款。
   * 确认后：停止轮询、销毁支付实例，并通知外层关闭当前支付流。
   */
  var handleCancelModalOk = function handleCancelModalOk() {
    // 停止轮询并销毁当前支付实例
    payment.reset();
    handleClose();
  };
  return /*#__PURE__*/React.createElement("div", {
    className: "pisell-eftpos-pay-adyen-scan"
  }, (data === null || data === void 0 ? void 0 : data.status) === StatusEnum.Loading ? /*#__PURE__*/React.createElement(AdyenScanQrcode, {
    loading: loading,
    qrCode: qrCode,
    payMethodType: payMethodType,
    onCancelPay: handleCancelModalOk,
    isPay: modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay,
    message: locales.getText('page.eftpos-pay.text.processing')
  }) : null);
};
export default AdyenScan;