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; }
import React, { useEffect, useRef, useState } from 'react';
import { locales } from '@pisell/utils';
import { Button } from 'antd';
import { PisellModal } from '@pisell/materials';
import "./index.less";
import { useContextData, useDispatch, updateState, updateNextStep, updateCustom } from "../store";
import { useStoreRef, useFail } from "../hooks";
import { ModeEnum, PayStatus, StatusEnum } from "../const";
import { getPayParams } from "../helper";
import { usePayment } from "../aggregatePayment";
import { EPaymentStatus } from "../aggregatePayment/types";
import payLog from "../utils/payLog";

/**
 * Adyen 常规支付组件
 *
 * 流程：
 *   1. Init 状态 → 显示支付操作界面（由业务具体实现）
 *   2. 用户确认后 → 调用 Adyen API 发起支付
 *   3. Processing 普通 → 展示"处理中" + 取消按钮
 *   4. Processing 签名中（signature_required）→ 展示"客户签名中"提示，禁用取消
 *   5. 支付成功（无签名）→ dispatch updateNextStep + 回调 onChange('success')
 *   6. 支付成功（有签名）→ 展示签名核查 UI，员工确认后回调 onChange('success')
 *      - Accept：签名通过，直接走成功流程
 *      - Decline：弹出二次确认，提示员工手动退款，确认后走成功流程
 *   7. 支付失败 → useFail 处理跳转失败页
 */
var AdyenPos = function AdyenPos(_ref) {
  var _data$custom6, _data$custom7, _data$custom8;
  var onChange = _ref.onChange,
    isNativeApp = _ref.isNativeApp;
  var data = useContextData();
  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;
  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),
    showDeclineModal = _useState2[0],
    setShowDeclineModal = _useState2[1];
  var payment = usePayment({
    paymentCode: 'ADYEN_POS',
    paymentNum: numRef.current || '',
    shouldContinue: function shouldContinue() {
      return !(unloadRef.current || !netRef.current);
    },
    callback: function callback(_instance, response) {
      console.log('response =>>>> ', response);
      var _ref2 = response || {},
        status = _ref2.status,
        responseData = _ref2.data;
      if (status === EPaymentStatus.Success) {
        handleSuccess(responseData);
      } else if (status === EPaymentStatus.Failed) {
        handleFail(responseData);
      } else if (status === EPaymentStatus.Processing) {
        handleProcessing(responseData);
      }
    }
  });
  useEffect(function () {
    failRef.current = fail;
  }, [fail]);
  useEffect(function () {
    return function () {
      unloadRef.current = true;
      if (clearRef.current) {
        clearTimeout(clearRef.current);
      }
    };
  }, []);
  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;
    }
    var isPay = modeRef.current === ModeEnum.Pay || modeRef.current === ModeEnum.FullPay;
    if (isPay) {
      payment.run();
    } else {
      var _data$custom;
      payment.run({
        params: {
          adyenpos: {
            order_payment_id: data === null || data === void 0 || (_data$custom = data.custom) === null || _data$custom === void 0 ? void 0 : _data$custom.order_payment_id
          }
        }
      });
    }
  }, []);

  /**
   * 触发支付成功流程
   * - 若响应包含签名步骤（signature_required），暂停 onChange，展示签名核查 UI
   * - 否则直接走成功流程
   */
  var handleSuccess = function handleSuccess(responseData) {
    var _responseData$data, _response$cvm_result;
    var _response = (responseData === null || responseData === void 0 || (_responseData$data = responseData.data) === null || _responseData$data === void 0 ? void 0 : _responseData$data.external_unified_response) || {};
    var signatureRequired = _response === null || _response === void 0 || (_response$cvm_result = _response.cvm_result) === null || _response$cvm_result === void 0 ? void 0 : _response$cvm_result.signature_required;
    dispatch(updateState({
      status: 'success',
      title: locales.getText('page.eftpos-pay.text.successful')(modeRef.current)
    }));
    dispatch(updateNextStep());
    dispatch(updateCustom({
      card_reader_surcharge: 0,
      receipt: []
    }));
    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');
    var onChangeParams = _objectSpread(_objectSpread({}, params), {}, {
      receipt: []
    });
    if (signatureRequired) {
      // 暂存参数，等待员工完成签名核查后再触发
      dispatch(updateCustom({
        successParams: onChangeParams,
        signatureCheck: true
      }));
    } else {
      clearRef.current = setTimeout(function () {
        if (unloadRef.current) return;
        onChange('success', params);
      }, 1000);
    }
  };

  /**
   * 签名核查通过：直接走成功流程
   */
  var handleSignatureAccept = function handleSignatureAccept() {
    var _data$custom2;
    payLog.log('点击签名核查通过');
    if (data !== null && data !== void 0 && (_data$custom2 = data.custom) !== null && _data$custom2 !== void 0 && _data$custom2.successParams) {
      var _data$custom3;
      // 触发成功回调
      onChange('success', data === null || data === void 0 || (_data$custom3 = data.custom) === null || _data$custom3 === void 0 ? void 0 : _data$custom3.successParams);
      // 清空参数，重置状态
      dispatch(updateCustom({
        successParams: null,
        signatureCheck: false
      }));
    }
  };

  /**
   * 拒绝签名：弹出二次确认，提示员工手动退款
   */
  var handleSignatureDecline = function handleSignatureDecline() {
    payLog.log('点击拒绝签名-弹出二次确认弹窗');
    setShowDeclineModal(true);
  };

  /**
   * 拒绝签名二次确认弹窗-点击确认
   */
  var handleDeclineModalConfirm = function handleDeclineModalConfirm() {
    var _data$custom4;
    payLog.log('拒绝签名二次确认弹窗-点击确认');
    setShowDeclineModal(false);
    if (data !== null && data !== void 0 && (_data$custom4 = data.custom) !== null && _data$custom4 !== void 0 && _data$custom4.successParams) {
      var _data$custom5;
      // 触发成功回调
      onChange('success', data === null || data === void 0 || (_data$custom5 = data.custom) === null || _data$custom5 === void 0 ? void 0 : _data$custom5.successParams);
      // 清空参数，重置状态
      dispatch(updateCustom({
        successParams: null,
        signatureCheck: false
      }));
    }
  };

  /**
   * 拒绝签名二次确认弹窗-点击取消
   */
  var handleDeclineModalCancel = function handleDeclineModalCancel() {
    payLog.log('拒绝签名二次确认弹窗-点击取消');
    setShowDeclineModal(false);
  };

  /**
   * 触发支付失败流程：交由 useFail 统一处理失败/重试逻辑
   */
  var handleFail = function handleFail(errorData) {
    var _errorData$data, _failRef$current;
    var _ref3 = (errorData === null || errorData === void 0 || (_errorData$data = errorData.data) === null || _errorData$data === void 0 ? void 0 : _errorData$data.external_unified_response) || {},
      message = _ref3.message,
      response_code = _ref3.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 handleProcessing = function handleProcessing(processingData) {
    var _processingData$data, _response$cvm_result2;
    console.log('handleProcessing =>>>> ', processingData);
    var _response = (processingData === null || processingData === void 0 || (_processingData$data = processingData.data) === null || _processingData$data === void 0 ? void 0 : _processingData$data.external_unified_response) || {};
    if (_response !== null && _response !== void 0 && (_response$cvm_result2 = _response.cvm_result) !== null && _response$cvm_result2 !== void 0 && _response$cvm_result2.signature_required) {
      dispatch(updateCustom({
        buttonDisabled: true,
        signingInProgress: true
      }));
    }
  };

  /**
   * 取消按钮点击逻辑
   */
  var onCancel = function onCancel() {
    payLog.log('点击取消按钮');
    payment.action({
      action: 'abort'
    });
    dispatch(updateCustom({
      buttonDisabled: true
    }));
  };
  return /*#__PURE__*/React.createElement("div", {
    className: "pisell-eftpos-pay-adyen"
  }, (data === null || data === void 0 ? void 0 : data.status) === StatusEnum.Success && (data === null || data === void 0 || (_data$custom6 = data.custom) === null || _data$custom6 === void 0 ? void 0 : _data$custom6.signatureCheck) && /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip"
  }, locales.getText('page.eftpos-pay.adyen.pos.signature.check.title')), /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip"
  }, locales.getText('page.eftpos-pay.adyen.pos.signature.check.text')), /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__eft-pay-step-item-btns"
  }, /*#__PURE__*/React.createElement(Button, {
    block: true,
    className: "pisell-lowcode__eft-pay-step-item-btn",
    onClick: handleSignatureDecline
  }, locales.getText('page.eftpos-pay.adyen.pos.signature.declined')), /*#__PURE__*/React.createElement(Button, {
    block: true,
    type: "primary",
    className: "pisell-lowcode__eft-pay-step-item-btn",
    onClick: handleSignatureAccept
  }, locales.getText('page.eftpos-pay.adyen.pos.signature.approved'))), /*#__PURE__*/React.createElement(PisellModal, {
    open: showDeclineModal,
    title: locales.getText('page.eftpos-pay.adyen.pos.signature.declined.modal.title'),
    okText: locales.getText('page.eftpos-pay.adyen.pos.signature.declined.modal.ok'),
    cancelText: locales.getText('page.eftpos-pay.text.back'),
    onOk: handleDeclineModalConfirm,
    onCancel: handleDeclineModalCancel
  }, /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip",
    style: {
      paddingTop: '24px'
    }
  }, locales.getText('page.eftpos-pay.adyen.pos.signature.declined.modal.content')))), (data === null || data === void 0 ? void 0 : data.status) === StatusEnum.Loading && /*#__PURE__*/React.createElement(React.Fragment, null, data !== null && data !== void 0 && (_data$custom7 = data.custom) !== null && _data$custom7 !== void 0 && _data$custom7.signingInProgress ?
  /*#__PURE__*/
  // 客户正在签名：不可取消，展示等待提示
  React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip"
  }, locales.getText('page.eftpos-pay.adyen.pos.signature.signing')), /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__eft-pay-step-item pisell-lowcode__eft-pay-step-item-tip"
  }, locales.getText('page.eftpos-pay.adyen.pos.signature.signing.tip'))) :
  /*#__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')), /*#__PURE__*/React.createElement("div", {
    className: "pisell-lowcode__eft-pay-step-item-btns"
  }, /*#__PURE__*/React.createElement(Button, {
    block: true,
    className: "pisell-lowcode__eft-pay-step-item-btn",
    onClick: onCancel,
    disabled: !!(data !== null && data !== void 0 && (_data$custom8 = data.custom) !== null && _data$custom8 !== void 0 && _data$custom8.buttonDisabled)
  }, locales.getText('page.eftpos-pay.text.cancel')))));
};
export default AdyenPos;