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 _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
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/destructuring-assignment */
import { locales } from '@pisell/utils';
import React, { useEffect, useState, useMemo, useRef, useCallback } from 'react';
import useEngineContext from "../../hooks/useEngineContext";
import App from "./app";
import Tip from "./tip";
import { RouteEnum, ModeEnum, RestoreEumn, OrderEumn, EftposEnum } from "./const";
import localeTexts from "./locales";
import { getInitState } from "./manufacturer";
import { Provider } from "./store";
import "./index.less";
import { getLocale } from "../../utils/locales";
locales.init(localeTexts, getLocale());
export default (function (props) {
  var _context$appHelper, _store$getState, _props$params, _props$params2;
  var _useState = useState(props.type === EftposEnum.Tyro ? OrderEumn.Null : props.source === RestoreEumn.Restore ? OrderEumn.Restore : OrderEumn.Normal),
    _useState2 = _slicedToArray(_useState, 2),
    check = _useState2[0],
    setCheckStatus = _useState2[1];
  var context = useEngineContext();
  var _useState3 = useState(0),
    _useState4 = _slicedToArray(_useState3, 2),
    cardSurcharge = _useState4[0],
    setCardSurcharge = _useState4[1];
  var _useState5 = useState([]),
    _useState6 = _slicedToArray(_useState5, 2),
    receipt = _useState6[0],
    setReceipt = _useState6[1];
  var _useState7 = useState(''),
    _useState8 = _slicedToArray(_useState7, 2),
    updateTime = _useState8[0],
    setTime = _useState8[1];
  console.log('context = ', context);
  var _useState9 = useState(),
    _useState10 = _slicedToArray(_useState9, 2),
    historyData = _useState10[0],
    setHistory = _useState10[1];
  var _ref = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {
      store: {},
      formatAmount: function formatAmount(number, precision, symbol) {
        return "".concat(symbol).concat(number);
      },
      storage: function storage() {
        return {
          get: function get() {
            return '';
          }
        };
      }
    },
    formatAmount = _ref.formatAmount,
    storage = _ref.storage,
    store = _ref.store;

  /**
   * terminal : terminal 内嵌
   * android_kiosk     : kiosk 内嵌
   */
  var channel = useMemo(function () {
    var _storage$get;
    var channel = (storage === null || storage === void 0 || (_storage$get = storage.get) === null || _storage$get === void 0 ? void 0 : _storage$get.call(storage, 'channel')) || '';
    if (channel === 'terminal') {
      return 'terminal';
    }
    if (channel === 'android_kiosk') {
      return 'kiosk';
    }
    return '';
  }, []);
  var isMobile = useMemo(function () {
    return Boolean(channel);
  }, [channel]);
  var symbol = (store === null || store === void 0 || (_store$getState = store.getState) === null || _store$getState === void 0 || (_store$getState = _store$getState.call(store)) === null || _store$getState === void 0 || (_store$getState = _store$getState.global) === null || _store$getState === void 0 ? void 0 : _store$getState.symbol) || '$';
  var mode = useMemo(function () {
    if (props.source === RestoreEumn.Restore) {
      if (props.params) {
        if (props.params.mode) {
          return props.params.mode;
        }
      }
      return ModeEnum.Pay;
    }
    if (props.mode) {
      return props.mode;
    }
    return ModeEnum.Pay;
  }, [props.mode, props.source, props.params]);

  /**
   * @title: 构建全局状态
   * @description: 1. 初始化, 2. 恢复
   * @Author: hongbing.wang
   * @Date: 2024-08-20 13:11
   */
  var state = useMemo(function () {
    var current = props.params && props.params.symbol ? props.params.symbol : symbol;
    // console.log('current 单位 = ', props.params.symbol, symbol);
    if (props.source === RestoreEumn.Restore) {
      return props.params;
    }
    return getInitState(props.type, props.params ? _objectSpread(_objectSpread({
      mode: mode
    }, props.params), {}, {
      symbol: current
    }) : {
      mode: mode,
      symbol: current
    });
  }, [mode, props.params, props.type, symbol]);
  var stateRef = useRef(state);
  useEffect(function () {
    stateRef.current = state;
  }, [state]);
  var onChangeStatus = useCallback(function (status, params, other) {
    props.onChangeStatus(status, params, other);
  }, []);
  var action = useMemo(function () {
    var act = function () {
      if (state.action) {
        return state.action;
      }
      if (mode === ModeEnum.Pay || mode === ModeEnum.FullPay) {
        if (state.device && state.pay) {
          return RouteEnum.Pay;
        }
        if (state.device) {
          return RouteEnum.Amount;
        }
        return RouteEnum.DeviceList;
      }
      if (mode === ModeEnum.Refund) {
        if (state.device) {
          return RouteEnum.Pay;
        }
        return RouteEnum.DeviceList;
      }
      if (mode === ModeEnum.Query) {
        return RouteEnum.Pay;
      }
      throw Error('未知模式');
    }();

    // if(props.source === 'restore'){
    onChangeStatus('page', act);
    // }
    return act;
  }, [mode, state]);
  useEffect(function () {
    document.body.id = 'body';
    console.log('初始化 ........112218017777');
  }, []);

  // console.log('action = ', action);
  console.log('props?.params?.device_number = ', props === null || props === void 0 || (_props$params = props.params) === null || _props$params === void 0 ? void 0 : _props$params.device_number);

  /**
   * @title: api 接口 数据
   * @Author: hongbing.wang
   * @Date: 2024-08-20 13:10
   */
  var api = useMemo(function () {
    if (typeof props.getApi === 'function') {
      return props.getApi();
    }
    return {};
  }, [props.getApi]);
  useEffect(function () {
    if (props.source === RestoreEumn.Restore || props.type === EftposEnum.Tyro) {
      return;
    }
    api.getTransaction({
      order_id: stateRef.current.order_id,
      card_reader_type: stateRef.current.eftpos,
      receive_status: 'unprocessed'
    }).then(function (res) {
      if (!Array.isArray(res.data) || res.data.length === 0) {
        setCheckStatus(OrderEumn.Null);
        return;
      }
      var currentMode = stateRef.current.mode === ModeEnum.FullPay ? ModeEnum.Pay : stateRef.current.mode;
      var list = res.data.filter(function (item) {
        return item.action === currentMode;
      });
      if (list.length === 0) {
        setCheckStatus(OrderEumn.Null);
        return;
      }
      var latest = list.pop();
      var numberList = list.map(function (item) {
        return item.number;
      });
      if (latest.status === OrderEumn.Failed) {
        setCheckStatus(latest.status);
        onChangeStatus('mark_tx_processed', [].concat(_toConsumableArray(numberList), [latest.number]));
        return;
      }
      if (list.length > 0) {
        onChangeStatus('mark_tx_processed', numberList);
      }
      var _ref2 = (latest === null || latest === void 0 ? void 0 : latest.metadata) || {},
        pay_param_base64 = _ref2.pay_param_base64,
        card_reader_surcharge = _ref2.card_reader_surcharge,
        receipt = _ref2.receipt;
      setTime(latest.updated_at);
      setCardSurcharge(card_reader_surcharge || 0);
      setReceipt(receipt || []);
      if (!pay_param_base64) {
        setCheckStatus(OrderEumn.Failed);
        return;
      }
      try {
        var data = JSON.parse(decodeURIComponent(atob(decodeURIComponent(pay_param_base64))));
        setHistory(data);
        setCheckStatus(latest.status);
      } catch (e) {
        setCheckStatus(OrderEumn.Failed);
        return;
      }
    });
  }, []);
  if (check === OrderEumn.Normal) {
    return null;
  }
  if (check === OrderEumn.Succeed) {
    return /*#__PURE__*/React.createElement(Provider, {
      state: historyData
    }, /*#__PURE__*/React.createElement(Tip, {
      cardSurcharge: cardSurcharge,
      receipts: receipt,
      onChangeStatus: onChangeStatus,
      onChangeParams: props.onChangeParams,
      formatAmount: formatAmount,
      successTime: updateTime,
      className: isMobile ? 'pisell-lowcode__eft-pay-terminal' : ''
    }));
  }
  return /*#__PURE__*/React.createElement(Provider, {
    state: check === OrderEumn.Pending ? historyData : state
  }, /*#__PURE__*/React.createElement(App, {
    api: api,
    channel: channel,
    params: props.params,
    onChangeStatus: onChangeStatus,
    terminal: props.terminal,
    onChangeParams: props.onChangeParams,
    action: check === OrderEumn.Pending ? ModeEnum.Pay : action,
    source: props.source,
    tyroUrl: props.tyroUrl,
    tyroVersion: props.tyroVersion,
    device_number: props === null || props === void 0 || (_props$params2 = props.params) === null || _props$params2 === void 0 ? void 0 : _props$params2.device_number,
    isMobile: isMobile,
    formatAmount: formatAmount
  }));
});