var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/components/eftposPay/tyro/index.tsx
var tyro_exports = {};
__export(tyro_exports, {
  default: () => tyro_default
});
module.exports = __toCommonJS(tyro_exports);
var import_react = __toESM(require("react"));
var import_hooks = require("./hooks");
var import_utils = require("@pisell/utils");
var import_antd = require("antd");
var import_store = require("../store");
var import_const = require("../const");
var import_decimal = require("decimal.js");
var import_helper = require("../helper");
var import_step = __toESM(require("../component/step/step"));
var import_hooks2 = require("../hooks");
var import_payLog = __toESM(require("../utils/payLog"));
var Minute = 1e3 * 60;
var tyro_default = ({
  api,
  onChange,
  children,
  url,
  version
}) => {
  const { eftpos, custom, mode, status: payStatus, client } = (0, import_store.useContextData)();
  const dispatch = (0, import_store.useDispatch)();
  const [status, setStatus] = (0, import_react.useState)(-1);
  const [isManually, setManually] = (0, import_react.useState)(false);
  const isCancelRef = (0, import_react.useRef)(false);
  const { deviceRef, payRef, numRef, modeRef, orderIdRef, amountRef } = (0, import_hooks2.useStoreRef)();
  const merchantReceiptRef = (0, import_react.useRef)({});
  const [TyroRef, load] = (0, import_hooks.useTyro)({ url, version });
  const requestParams = (0, import_react.useRef)(custom == null ? void 0 : custom.requestParams);
  const listRef = (0, import_react.useRef)((custom == null ? void 0 : custom.list) || []);
  const iClientRef = (0, import_react.useRef)();
  const requestIdRef = (0, import_react.useRef)((custom == null ? void 0 : custom.requestId) || "");
  const unloadRef = (0, import_react.useRef)(false);
  const clearRef = (0, import_react.useRef)();
  const isPrint = (key) => {
    var _a, _b, _c, _d;
    if ((_b = (_a = deviceRef.current) == null ? void 0 : _a.setting) == null ? void 0 : _b.receipts) {
      return false;
    }
    const receiptList = (_d = (_c = deviceRef.current) == null ? void 0 : _c.setting) == null ? void 0 : _d.receiptList;
    if (!Array.isArray(receiptList)) {
      return true;
    }
    if (Array.isArray(receiptList) && receiptList.some((item) => item === key)) {
      return true;
    }
    return false;
  };
  (0, import_react.useEffect)(() => {
    listRef.current = (custom == null ? void 0 : custom.list) || [];
  }, [custom == null ? void 0 : custom.list]);
  (0, import_react.useEffect)(() => {
    requestIdRef.current = (custom == null ? void 0 : custom.requestId) || "";
  }, [custom == null ? void 0 : custom.requestId]);
  (0, import_react.useEffect)(() => {
    requestParams.current = custom == null ? void 0 : custom.requestParams;
  }, [custom == null ? void 0 : custom.requestParams]);
  const getTerminalInfo = (cb) => {
    const iClient = iClientRef.current;
    if (!iClient) {
      return;
    }
    setStatus(0);
    const { connection } = deviceRef.current;
    const { integrationKey, tid, mid } = connection;
    console.log(integrationKey, tid, mid);
    iClient.terminalInfo(
      ({ status: status2, message, terminalInfo }) => {
        import_payLog.default.log("Tyro：终端信息回调", { status: status2, terminalInfo, message });
        if (status2 === "success" && (terminalInfo == null ? void 0 : terminalInfo.available)) {
          cb();
        }
      },
      {
        mid,
        tid,
        integrationKey
      }
    );
  };
  const refundOrder = () => {
    var _a, _b, _c, _d;
    const iClient = iClientRef.current;
    if (!iClient) {
      return;
    }
    if (isCancelRef.current) {
      return;
    }
    const { connection } = deviceRef.current;
    const { integrationKey, tid, mid } = connection;
    numRef.current = (0, import_helper.getUuid)();
    dispatch(
      (0, import_store.updateState)({
        number: numRef.current
      })
    );
    requestParams.current = {
      amount: new import_decimal.Decimal(amountRef.current || 0).mul(100).toFixed(0, import_decimal.Decimal.ROUND_HALF_UP),
      // 打印小票 true 打印到Pisell系统上 false 打印到pos机上
      integratedReceipt: !((_b = (_a = deviceRef.current) == null ? void 0 : _a.setting) == null ? void 0 : _b.receipts),
      integrationKey,
      transactionId: numRef.current,
      mid,
      tid,
      device: JSON.stringify(deviceRef.current),
      isPrintMerchant: isPrint("merchant"),
      isPrintCustomer: isPrint("customer"),
      browserVersion: (0, import_helper.getBrowserVersion)()
    };
    dispatch(
      (0, import_store.updateCustom)({
        requestParams: requestParams.current
      })
    );
    setStatus(Date.now());
    merchantReceiptRef.current = {};
    api.addTransaction({
      order_id: orderIdRef.current,
      number: numRef.current,
      card_reader_id: (_c = deviceRef.current) == null ? void 0 : _c.id,
      card_reader_type: eftpos,
      amount: requestParams.current.amount,
      action: modeRef.current === import_const.ModeEnum.FullPay ? import_const.ModeEnum.Pay : modeRef.current,
      status: "pending",
      request: requestParams.current,
      response: {},
      metadata: {
        receipt: []
      },
      _config: {
        retry: {
          count: 10,
          delay: 500
        }
      }
    }).then((res) => {
      requestIdRef.current = res.data.id;
      dispatch(
        (0, import_store.updateCustom)({
          requestId: res.data.id
        })
      );
    });
    import_payLog.default.setContext({ transactionNumber: numRef.current });
    import_payLog.default.log("Tyro：发起退款", { number: numRef == null ? void 0 : numRef.current, amount: (_d = requestParams.current) == null ? void 0 : _d.amount });
    iClient.initiateRefund(requestParams.current, {
      receiptCallback: receiptCallbackImpl,
      transactionCompleteCallback: transactionCompleteCallbackImpl,
      questionCallback: questionCallbackImpl,
      statusMessageCallback: statusMessageCallbackImpl
    });
  };
  const payOrder = () => {
    var _a, _b, _c, _d, _e, _f, _g, _h;
    const iClient = iClientRef.current;
    if (!iClient) {
      return;
    }
    if (isCancelRef.current) {
      return;
    }
    const { connection } = deviceRef.current;
    const { integrationKey, tid, mid } = connection;
    numRef.current = (0, import_helper.getUuid)();
    dispatch(
      (0, import_store.updateState)({
        number: numRef.current
      })
    );
    console.log(
      "deviceRef.current?.settings?.useOriginSurcharge = ",
      (_b = (_a = deviceRef.current) == null ? void 0 : _a.setting) == null ? void 0 : _b.useOriginSurcharge
    );
    requestParams.current = {
      amount: new import_decimal.Decimal((_c = payRef.current) == null ? void 0 : _c.total).mul(100).toFixed(0, import_decimal.Decimal.ROUND_HALF_UP),
      // 手续费 true tyro 手续费, false 系统手续费
      enableSurcharge: ((_e = (_d = deviceRef.current) == null ? void 0 : _d.setting) == null ? void 0 : _e.useOriginSurcharge) || false,
      // 打印小票 true 打印到系统上 false 打印到pos机上
      integratedReceipt: !((_g = (_f = deviceRef.current) == null ? void 0 : _f.setting) == null ? void 0 : _g.receipts),
      integrationKey,
      transactionId: numRef.current,
      mid,
      tid,
      device: JSON.stringify(deviceRef.current),
      isPrintMerchant: isPrint("merchant"),
      isPrintCustomer: isPrint("customer"),
      browserVersion: (0, import_helper.getBrowserVersion)()
    };
    dispatch(
      (0, import_store.updateCustom)({
        requestParams: requestParams.current
      })
    );
    setStatus(Date.now());
    merchantReceiptRef.current = {};
    api.addTransaction({
      order_id: orderIdRef.current,
      number: numRef.current,
      card_reader_id: (_h = deviceRef.current) == null ? void 0 : _h.id,
      card_reader_type: eftpos,
      amount: requestParams.current.amount,
      action: modeRef.current === import_const.ModeEnum.FullPay ? import_const.ModeEnum.Pay : modeRef.current,
      status: "pending",
      request: requestParams.current,
      response: {},
      metadata: {
        receipt: []
      },
      _config: {
        retry: {
          count: 10,
          delay: 500
        }
      }
    }).then((res) => {
      requestIdRef.current = res.data.id;
      dispatch(
        (0, import_store.updateCustom)({
          requestId: res.data.id
        })
      );
    });
    import_payLog.default.setContext({ transactionNumber: numRef.current });
    import_payLog.default.log("Tyro：发起支付", { number: numRef.current, amount: requestParams.current.amount });
    iClient.initiatePurchase(requestParams.current, {
      receiptCallback: receiptCallbackImpl,
      transactionCompleteCallback: transactionCompleteCallbackImpl,
      questionCallback: questionCallbackImpl,
      statusMessageCallback: statusMessageCallbackImpl
    });
  };
  const continueLastOrder = () => {
    const iClient = iClientRef.current;
    if (!iClient) {
      return;
    }
    if (isCancelRef.current) {
      return;
    }
    setStatus(Date.now());
    merchantReceiptRef.current = {};
    import_payLog.default.log("Tyro：恢复上次交易");
    iClient.continueLastTransaction({
      receiptCallback: receiptCallbackImpl,
      transactionCompleteCallback: transactionCompleteCallbackImpl,
      questionCallback: questionCallbackImpl,
      statusMessageCallback: statusMessageCallbackImpl
    });
  };
  const receiptCallbackImpl = ({ signatureRequired, merchantReceipt }) => {
    import_payLog.default.log("Tyro：小票回调", { signatureRequired, hasReceipt: !!merchantReceipt });
    const receipt = [merchantReceipt].filter((item) => typeof item === "string").filter(Boolean);
    merchantReceiptRef.current = { signatureRequired, merchantReceipt };
    if (signatureRequired) {
      onChange("print", receipt);
      return;
    }
    if (isPrint("merchant")) {
      onChange("print", receipt);
    }
  };
  const statusMessageCallbackImpl = (message) => {
    var _a;
    import_payLog.default.log("Tyro：状态消息", { message });
    const translateMsg = import_utils.locales.getText("page.eftpos-pay.text.tyro")(message);
    const msg = Array.isArray(translateMsg) ? translateMsg.reduce(
      (accumulator, currentValue) => accumulator + " " + currentValue,
      ""
    ) : translateMsg;
    const lastitem = listRef.current[listRef.current.length - 1];
    const key = import_utils.locales.getText("page.eftpos-pay.text.tyro")(
      "Connection lost. Attempting to recover"
    );
    if (msg === key && lastitem && lastitem.pedding === key) {
      return;
    }
    console.log("message = ", message);
    console.log("msg = ", msg);
    dispatch(
      (0, import_store.updateCustom)({
        list: [
          ...listRef.current || [],
          {
            status: "pendding",
            pedding: msg,
            resolve: msg,
            reject: msg,
            index: ((_a = listRef.current) == null ? void 0 : _a.length) || 0
          }
        ]
      })
    );
  };
  const questionCallbackImpl = (question, answerCallback) => {
    import_payLog.default.log("Tyro：交互问题回调", { question });
    setStatus(-1);
    setManually(false);
    const msg = import_utils.locales.getText("page.eftpos-pay.text.tyro")(question.text);
    dispatch(
      (0, import_store.updateCustom)({
        btnList: question.options.map((item) => {
          return /* @__PURE__ */ import_react.default.createElement(
            import_antd.Button,
            {
              key: item,
              type: item === "YES" || item === "RETRY" ? "primary" : "default",
              className: "pisell-lowcode__eft-pay-step-item-btn",
              onClick: () => {
                dispatch(
                  (0, import_store.updateCustom)({
                    btnList: []
                  })
                );
                setManually(false);
                dispatch(
                  (0, import_store.updateState)({
                    status: "loading",
                    title: import_utils.locales.getText("page.eftpos-pay.text.loading")(
                      modeRef.current
                    ),
                    subTitle: ""
                  })
                );
                setStatus(Date.now());
                answerCallback(item);
              }
            },
            import_utils.locales.getText("page.eftpos-pay.text.tyro-btn")(item)
          );
        })
      })
    );
    const status2 = question.isError ? "fail" : "warn";
    dispatch(
      (0, import_store.updateState)(
        Array.isArray(msg) ? {
          status: status2,
          title: msg[0],
          subTitle: msg[1]
        } : {
          status: status2,
          title: msg
        }
      )
    );
  };
  const transactionCompleteCallbackImpl = (response) => {
    var _a, _b;
    setStatus(-1);
    setManually(false);
    import_payLog.default.log("Tyro：交易完成回调", { response });
    const receipt = [
      // merchantReceiptRef.current?.merchantReceipt,
      response == null ? void 0 : response.customerReceipt
    ].filter((item) => typeof item === "string").filter(Boolean);
    api.editTransaction(requestIdRef.current, {
      order_id: orderIdRef.current,
      number: numRef.current,
      card_reader_id: (_a = deviceRef.current) == null ? void 0 : _a.id,
      card_reader_type: eftpos,
      amount: requestParams.current.amount,
      action: modeRef.current === import_const.ModeEnum.FullPay ? import_const.ModeEnum.Pay : modeRef.current,
      request: requestParams.current,
      status: response.result === "APPROVED" ? "succeed" : "failed",
      response: { ...response, merchantReceipt: merchantReceiptRef.current },
      metadata: {
        receipt
      }
    });
    dispatch(
      (0, import_store.updateCustom)({
        btnList: []
      })
    );
    if (response.result === "APPROVED") {
      dispatch(
        (0, import_store.updateState)({
          status: "success",
          title: import_utils.locales.getText("page.eftpos-pay.text.successful")(mode),
          subTitle: ""
        })
      );
      dispatch(
        (0, import_store.updateCustom)({
          card_reader_surcharge: response.surchargeAmount || 0,
          receipt
        })
      );
      clearRef.current = setTimeout(() => {
        const params = (0, import_helper.getPayParams)(
          {
            mode: modeRef.current,
            amount: amountRef.current,
            order_id: orderIdRef.current,
            number: numRef.current,
            device: deviceRef.current,
            pay: payRef.current,
            custom: {
              card_reader_surcharge: response.surchargeAmount || 0,
              receipt
            }
          },
          "success"
        );
        onChange("success", {
          ...params,
          receipt: isPrint("customer") ? receipt : []
        });
      }, 1e3);
      return;
    } else {
      const current = ((_b = deviceRef.current) == null ? void 0 : _b.setting.receipts) ? [] : receipt;
      if (current.length > 0) {
        if (isPrint("customer")) {
          onChange("print", receipt);
        }
      }
    }
    if (response.result === "UNKNOWN") {
      dispatch(
        (0, import_store.updateCustom)({
          errorStatus: "unknow"
          // unknow know unknown
        })
      );
      dispatch((0, import_store.updateComponent)("UnknowFail"));
      return;
    }
    dispatch(
      (0, import_store.updateState)({
        status: "fail"
      })
    );
    dispatch(
      (0, import_store.updateCustom)({
        failCustom: {
          isPosNetworkError: false,
          status: "fail",
          fail: response.result,
          //locales.getText('page.eftpos-pay.text.transaction.fail'),
          warn: null,
          title: import_utils.locales.getText("page.eftpos-pay.text.failed")(
            modeRef.current
          )
        }
      })
    );
    dispatch((0, import_store.updateComponent)("FailCustom"));
  };
  (0, import_react.useEffect)(() => {
    const { config } = deviceRef.current;
    const { apiKey, posProductData } = config;
    if (load && TyroRef.current) {
      const IClient = TyroRef.current.IClient;
      if (IClient) {
        const iclient = new IClient(apiKey, posProductData);
        iClientRef.current = iclient;
        import_payLog.default.log("Tyro：SDK 初始化完成");
        if (isCancelRef.current) {
          return;
        }
        if (!numRef.current) {
          if (modeRef.current === import_const.ModeEnum.Pay || modeRef.current === import_const.ModeEnum.FullPay) {
            import_payLog.default.log("Tyro：支付交易，查询终端信息");
            getTerminalInfo(payOrder);
          } else if (modeRef.current === import_const.ModeEnum.Refund) {
            import_payLog.default.log("Tyro：退款交易，查询终端信息");
            getTerminalInfo(refundOrder);
          }
        } else {
          import_payLog.default.log("Tyro：恢复上次交易，查询终端信息");
          getTerminalInfo(continueLastOrder);
        }
      }
    }
  }, [load]);
  const onNotin = () => {
    onChange("print", [], "print_on_timeout");
  };
  (0, import_react.useEffect)(() => {
    let clear;
    if (status === -1) {
      return () => {
        if (clear) {
          clearTimeout(clear);
        }
      };
    }
    if (status === 0) {
      clear = setTimeout(() => {
        import_payLog.default.log("Tyro：连接超时");
        dispatch(
          (0, import_store.updateState)({
            status: "fail"
          })
        );
        dispatch(
          (0, import_store.updateCustom)({
            failCustom: {
              status: "fail",
              fail: import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.pay.fail.timeout"
              ),
              title: import_utils.locales.getText(
                "page.eftpos-pay.text.transaction.fail.timeout"
              ),
              warn: null
            }
          })
        );
        dispatch((0, import_store.updateComponent)("FailCustom"));
      }, Minute);
      return () => {
        if (clear) {
          clearTimeout(clear);
        }
      };
    }
    clear = setTimeout(() => {
      const iClient = iClientRef.current;
      if (!iClient) {
        return;
      }
      import_payLog.default.log("Tyro：交易超时，显示手动标记");
      setManually(true);
    }, Minute);
    return () => {
      if (clear) {
        clearTimeout(clear);
      }
    };
  }, [status]);
  const onManually = () => {
    import_payLog.default.log("Tyro：点击手动标记");
    dispatch(
      (0, import_store.updateState)({
        manual: {
          title: import_utils.locales.getText("page.eftpos-pay.text.request.title")(mode),
          text: import_utils.locales.getText("page.eftpos-pay.text.request.text")(mode)
        }
      })
    );
    dispatch((0, import_store.updateComponent)("Manual", true));
  };
  const onCancel = () => {
    const iClient = iClientRef.current;
    if (!iClient) {
      return;
    }
    if (status > 0) {
      import_payLog.default.log("Tyro：取消当前交易");
      iClient.cancelCurrentTransaction();
      return;
    }
    if (isCancelRef.current) {
      return;
    }
    import_payLog.default.log("Tyro：取消（交易未开始）");
    isCancelRef.current = true;
    dispatch(
      (0, import_store.updateState)({
        status: "fail"
      })
    );
    dispatch(
      (0, import_store.updateCustom)({
        failCustom: {
          status: "fail",
          fail: import_utils.locales.getText("page.eftpos-pay.text.transaction.fail.cancel"),
          title: import_utils.locales.getText(
            "page.eftpos-pay.text.transaction.fail.cancel.title"
          ),
          warn: null
        }
      })
    );
    dispatch((0, import_store.updateComponent)("FailCustom"));
  };
  (0, import_react.useEffect)(
    () => () => {
      unloadRef.current = true;
      if (clearRef.current) {
        clearTimeout(clearRef.current);
      }
    },
    []
  );
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-body" }, ((custom == null ? void 0 : custom.list) || []).map((item) => /* @__PURE__ */ import_react.default.createElement(
    import_step.default,
    {
      key: item.index,
      pedding: item.pedding,
      resolve: item.resolve,
      reject: item.reject,
      status: item.status
    }
  ))), isManually ? /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__eft-pay-step-item-btns" }, client === import_const.ClientEnum.Merchant ? /* @__PURE__ */ import_react.default.createElement(
    import_antd.Button,
    {
      block: true,
      className: "pisell-lowcode__eft-pay-step-item-btn",
      onClick: onManually
    },
    import_utils.locales.getText("page.eftpos-pay.text.manual.marking")
  ) : /* @__PURE__ */ import_react.default.createElement(
    import_antd.Button,
    {
      block: true,
      className: "pisell-lowcode__eft-pay-step-item-btn",
      onClick: onNotin
    },
    import_utils.locales.getText("page.eftpos-pay.text.manual.print_receipt")
  )) : null, /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: "pisell-lowcode__eft-pay-step-item-btns",
      style: { flexWrap: "wrap" }
    },
    Array.isArray(custom == null ? void 0 : custom.btnList) && (custom == null ? void 0 : custom.btnList).length > 0 ? /* @__PURE__ */ import_react.default.createElement("div", { style: { width: "100%", display: "flex", gap: "12px" } }, custom == null ? void 0 : custom.btnList) : null,
    !(payStatus === "success" || payStatus === "fail") ? /* @__PURE__ */ import_react.default.createElement(
      import_antd.Button,
      {
        block: true,
        type: "text",
        disabled: Array.isArray(custom == null ? void 0 : custom.btnList) && (custom == null ? void 0 : custom.btnList).length > 0,
        className: "pisell-lowcode__eft-pay-step-item-btn",
        onClick: onCancel
      },
      import_utils.locales.getText("page.eftpos-pay.text.manual.cancel")
    ) : null
  ));
};
