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/EFTPos.tsx
var EFTPos_exports = {};
__export(EFTPos_exports, {
  default: () => EFTPos_default
});
module.exports = __toCommonJS(EFTPos_exports);
var import_react = __toESM(require("react"));
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_serve = require("./serve");
var import_index = __toESM(require("./index"));
var isDev = location.host.indexOf("-dev.cn");
var EFTPos = (props, ref) => {
  var _a;
  const [visible, setVisible] = (0, import_react.useState)(false);
  const [footer, setFooter] = (0, import_react.useState)(null);
  const [type, setType] = (0, import_react.useState)("payo");
  const [terminal, setTerminal] = (0, import_react.useState)({ network: true });
  const [apiParams, setApiParams] = (0, import_react.useState)({});
  const [source, setSource] = (0, import_react.useState)("normal");
  const [action, setAction] = (0, import_react.useState)("");
  const [mode, setMode] = (0, import_react.useState)("auto");
  const [key, setKey] = (0, import_react.useState)(0);
  const [tyroUrl] = (0, import_react.useState)(
    isDev === -1 ? "https://iclient.tyro.com" : "https://iclientsimulator.test.tyro.com"
  );
  const [tyroVersion] = (0, import_react.useState)("iclient-v1.js");
  const isComplete = (0, import_react.useRef)(false);
  const context = (0, import_useEngineContext.default)();
  const {
    lowcodeRef,
    store,
    storage,
    interaction,
    isTerminal,
    sendWarningLog
  } = ((_a = context.appHelper) == null ? void 0 : _a.utils) || {};
  const isTer = (0, import_react.useMemo)(() => {
    return isTerminal();
  }, [isTerminal]);
  const install = () => {
    var _a2, _b, _c, _d, _e;
    if (sendWarningLog) {
      sendWarningLog({
        title: "页面eftpos进入",
        content: [
          {
            key: "time",
            value: Date.now()
          }
        ]
      });
    }
    isComplete.current = false;
    if (lowcodeRef) {
      lowcodeRef.onReady({});
    }
    if (interaction) {
      (_b = (_a2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _a2.postMessageToApp) == null ? void 0 : _b.call(_a2, {
        module: "pos",
        key: "page_load"
      });
      (_c = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _c.mountFunction("pos", "onPay", (params) => {
        var _a3, _b2, _c2, _d2, _e2;
        sendWarningLog && sendWarningLog({
          title: "进入eftpos",
          content: [
            {
              key: "eftposPay",
              value: params
            },
            {
              key: "time",
              value: Date.now()
            }
          ]
        });
        try {
          console.log("onPay params =", params, (_a3 = storage == null ? void 0 : storage.get) == null ? void 0 : _a3.call(storage, "channel"));
          const json = JSON.parse(params);
          json.card_reader_type = json.code.split("_")[1].toLocaleLowerCase();
          json.type = json.card_reader_type;
          json.symbol = ((_e2 = (_d2 = (_c2 = (_b2 = store == null ? void 0 : store.getState) == null ? void 0 : _b2.call(store)) == null ? void 0 : _c2.global) == null ? void 0 : _d2.globalConfig) == null ? void 0 : _e2.currency_symbol) || "$";
          if (!json.client) {
            json.client = "merchant";
          }
          if (!json.name) {
            json.name = json.code;
          }
          update({
            type: json.card_reader_type,
            terminal: { network: true },
            apiParams: json,
            mode: json.mode || "pay",
            key: Date.now()
          });
          console.log("json=====>", json);
        } catch (error) {
          console.log(typeof params);
          console.log("error onPay", params);
          console.error(error);
        }
      });
      (_d = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _d.mountFunction(
        "pos",
        "onPayBackup",
        (params) => {
          try {
            const json = JSON.parse(
              decodeURIComponent(atob(decodeURIComponent(params)))
            );
            console.log("json = ", json);
            update(
              {
                apiParams: json,
                terminal: { network: true },
                key: Date.now()
              },
              "restore"
            );
          } catch (error) {
            console.log(typeof params);
            console.log("error onPayBackup", JSON.stringify(params));
            console.error(error);
          }
        }
      );
      (_e = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _e.mountFunction(
        "pos",
        "onPayNetWork",
        (params) => {
          try {
            const json = JSON.parse(params);
            updateTerminal(json);
          } catch (error) {
            console.error("onPayNetWork ", params);
            console.error(error);
          }
        }
      );
    }
  };
  const uninstall = () => {
    if (sendWarningLog) {
      sendWarningLog({
        title: "页面eftpos离开",
        content: [
          {
            key: "time",
            value: Date.now()
          }
        ]
      });
    }
  };
  (0, import_react.useEffect)(() => {
    install();
    return uninstall;
  }, []);
  const onChangeStatus = (status, params, other) => {
    var _a2, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
    console.log("---------------------------");
    console.log(
      "status, params = ",
      status,
      params,
      params == null ? void 0 : params.uniquePaymentNumber,
      other
    );
    console.log("---------------------------");
    if (status === "success" || status === "fail") {
      isComplete.current = true;
    }
    if (lowcodeRef) {
      lowcodeRef.onChange({
        status,
        params
      });
      if (status === "success" || status === "fail") {
        setVisible(false);
        isComplete.current = false;
      }
      return;
    }
    if (props == null ? void 0 : props.onPayResult) {
      props.onPayResult({ status, params });
      if (status === "success" || status === "fail") {
        setVisible(false);
        isComplete.current = false;
      }
      return;
    }
    if (interaction) {
      if (status === "page") {
        console.log(" 页面 = ", params);
        if (params === "amount" || params === "deviceList" || params === "fail") {
          (_b = (_a2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _a2.postMessageToApp) == null ? void 0 : _b.call(_a2, {
            module: "pos",
            key: "other",
            data: {
              key: "show_close_button"
              // hide_close_button:隐藏关闭按钮 show_close_button:显示关闭按钮
            }
          });
        }
        if (params === "pay") {
          (_d = (_c = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _c.postMessageToApp) == null ? void 0 : _d.call(_c, {
            module: "pos",
            key: "other",
            data: {
              key: "hide_close_button"
              // hide_close_button:隐藏关闭按钮 show_close_button:显示关闭按钮
            }
          });
        }
        return;
      }
      if (status === "print") {
        if (other === "print_on_timeout") {
          (_f = (_e = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _e.postMessageToApp) == null ? void 0 : _f.call(_e, {
            module: "pos",
            key: "print_on_timeout"
          });
        } else if (other === "back_home") {
          (_h = (_g = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _g.postMessageToApp) == null ? void 0 : _h.call(_g, {
            module: "pos",
            key: "back_home"
          });
        } else {
          const list = Array.isArray(params) ? params.filter((item) => typeof item === "string").filter(Boolean) : [];
          if (list.length > 0) {
            (_j = (_i = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _i.postMessageToApp) == null ? void 0 : _j.call(_i, {
              module: "pos",
              key: "print",
              data: list
            });
          }
        }
        return;
      }
      if (status === "mark_tx_processed") {
        (_l = (_k = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _k.postMessageToApp) == null ? void 0 : _l.call(_k, {
          module: "pos",
          key: "mark_tx_processed",
          data: {
            params: {
              uniquePaymentNumberList: params
            }
          }
        });
        return;
      }
      if (typeof params === "object" && params && "uniquePaymentNumber" in params && params.uniquePaymentNumber) {
        (_n = (_m = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _m.postMessageToApp) == null ? void 0 : _n.call(_m, {
          module: "pos",
          key: "mark_tx_processed",
          data: {
            params: {
              uniquePaymentNumberList: [params.uniquePaymentNumber]
            }
          }
        });
      }
      if (status === "success" && typeof params === "object" && params && "receipt" in params && Array.isArray(params.receipt) && params.receipt.length > 0) {
        const receiptList = params.receipt.filter((item) => typeof item === "string").filter(Boolean);
        if (receiptList.length > 0) {
          (_p = (_o = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _o.postMessageToApp) == null ? void 0 : _p.call(_o, {
            module: "pos",
            key: "print",
            data: receiptList
          });
        }
      }
      sendWarningLog({
        title: "离开eftpos",
        content: [
          {
            key: "eftposPay",
            value: JSON.stringify(params)
          },
          {
            key: "time",
            value: Date.now()
          }
        ]
      });
      (_r = (_q = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _q.postMessageToApp) == null ? void 0 : _r.call(_q, {
        module: "pos",
        key: "payChange",
        data: {
          status: status === "success" ? 1 : 0,
          params
        }
      });
      setVisible(false);
      isComplete.current = false;
    }
  };
  const update = (params, source2) => {
    setVisible(true);
    setSource(source2 || "");
    if (params.type) {
      setType(params.type);
    }
    if (params.terminal !== void 0) {
      setTerminal(params.terminal);
    }
    if (params.apiParams !== void 0) {
      setApiParams(params.apiParams);
    }
    if (params.mode !== void 0) {
      setMode(params.mode);
    }
    if (params.key !== void 0) {
      setKey(params.key);
    }
    if (params.source !== void 0) {
      setSource(params.source);
    }
  };
  const updateNetwork = (terminal2) => {
    setTerminal(terminal2);
  };
  const updateTerminal = (terminal2) => {
    setTerminal(terminal2);
  };
  const getApi = () => {
    return {
      pay(params, config) {
        return (0, import_serve.payData)(params, { ...config || {}, customResponse: true }).then((res) => {
          console.log("====> 支付结果", res);
          if (sendWarningLog) {
            sendWarningLog({
              title: "支付结果",
              content: [
                { key: "res", value: JSON.stringify(res) },
                { key: "params", value: JSON.stringify(params) }
              ]
            });
          }
          if (res && (res.code === "200" || res.code === 200)) {
            return res;
          }
          return Promise.reject(res);
        }).catch((error) => {
          console.log("====> 支付失败", error);
          if (sendWarningLog) {
            sendWarningLog({
              title: "api.pay支付失败",
              content: [
                { key: "params", value: JSON.stringify(params) },
                { key: "error", value: JSON.stringify(error) }
              ]
            });
          }
          return error;
        });
      },
      check(params, config) {
        return (0, import_serve.verifyData)(params, {
          ...config || {},
          customResponse: true
        }).then((res) => {
          console.log("--------- verifyData  ----", res);
          if (res && (res.code === "200" || res.code === 200)) {
            return res;
          }
          return Promise.reject(res);
        });
      },
      getDeviceList(params, config) {
        if (sendWarningLog) {
          sendWarningLog({
            title: "getDeviceList",
            content: [
              {
                key: "params",
                value: JSON.stringify(params)
              }
            ]
          });
        }
        return (0, import_serve.getDeviceList)(params, config).then((res) => {
          var _a2, _b;
          console.log("getDeviceList res", res);
          if (res && (res.code === "200" || res.code === 200)) {
            (_a2 = props == null ? void 0 : props.onEftposLoad) == null ? void 0 : _a2.call(props, true);
            return res.data;
          }
          (_b = props == null ? void 0 : props.onEftposLoad) == null ? void 0 : _b.call(props, false);
          return Promise.reject(res);
        }).catch((err) => {
          var _a2;
          console.log("getDeviceList_error>>>>>>", err);
          (_a2 = props == null ? void 0 : props.onEftposLoad) == null ? void 0 : _a2.call(props, false);
          return Promise.reject(err);
        });
      },
      update(params, config) {
        return (0, import_serve.payButton)(params, {
          ...config || {},
          customResponse: true
        }).then((res) => {
          console.log("--------- payButton  ----", res);
          if (res && (res.code === "200" || res.code === 200)) {
            return res;
          }
          return Promise.reject(res);
        });
      },
      refund(params, config) {
        return (0, import_serve.refundData)(params, {
          ...config || {},
          customResponse: true
        }).then((res) => {
          console.log("--------- refundData  ----", res);
          if (res && (res.code === "200" || res.code === 200)) {
            return res;
          }
          return Promise.reject(res);
        });
      },
      getTransaction(params, config) {
        console.log("params", params, config);
        return (0, import_serve.getTransaction)(params, config).then((res) => {
          var _a2, _b;
          if (res && (res.code === "200" || res.code === 200)) {
            (_a2 = props == null ? void 0 : props.onEftposLoad) == null ? void 0 : _a2.call(props, true);
            return res;
          }
          (_b = props == null ? void 0 : props.onEftposLoad) == null ? void 0 : _b.call(props, false);
          return Promise.reject(res);
        }).catch((err) => {
          var _a2;
          console.log("getTransaction_error>>>>>>", err);
          (_a2 = props == null ? void 0 : props.onEftposLoad) == null ? void 0 : _a2.call(props, false);
          return Promise.reject(err);
        });
      },
      addTransaction(params, config) {
        console.log("params", params, config);
        return (0, import_serve.addTransaction)(params, config).then((res) => {
          if (res && (res.code === "200" || res.code === 200)) {
            return res;
          }
          return Promise.reject(res);
        });
      },
      editTransaction(params, config) {
        const [id, ...otherParams] = params;
        console.log("editTransaction id = ", id);
        return new Promise((resolve) => {
          resolve(id);
        }).then(() => (0, import_serve.editTransaction)({ id, ...otherParams })).then(
          (res) => {
            if (res && (res.code === "200" || res.code === 200)) {
              return res;
            }
            return Promise.reject(res);
          },
          (err) => {
            console.log(err);
            return Promise.reject(err);
          }
        );
      },
      linklyPayQuery(params, config) {
        console.log("linklyPayQuery>>>>>>>params", params, config);
        return (0, import_serve.linklyPayQuery)(params, config).then((res) => {
          console.log("linklyPayQuery>>>>>>then", res);
          if (res && (res.code === "200" || res.code === 200)) {
            return res;
          }
          return Promise.reject(res);
        }).catch((err) => {
          console.log("linklyPayQuery>>>>>>error", err);
          return Promise.reject(err);
        });
      },
      linklyRefundQuery(params, config) {
        return (0, import_serve.linklyRefundQuery)(params, config).then((res) => {
          if (res && (res.code === "200" || res.code === 200)) {
            return res;
          }
          return Promise.reject(res);
        }).catch((err) => {
          return Promise.reject(err);
        });
      }
    };
  };
  const onChangeParams = (params) => {
    var _a2, _b;
    if (isComplete.current) {
      return;
    }
    if (lowcodeRef) {
      lowcodeRef.onChange({
        status: "cache",
        params
      });
      return;
    }
    if (interaction) {
      const json = JSON.stringify(params);
      const base64JSon = encodeURIComponent(btoa(encodeURIComponent(json)));
      (_b = (_a2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _a2.postMessageToApp) == null ? void 0 : _b.call(_a2, {
        module: "pos",
        key: "paymentInfo",
        data: base64JSon
      });
    }
  };
  (0, import_react.useImperativeHandle)(ref, () => ({
    updateNetwork,
    update
  }));
  return visible ? /* @__PURE__ */ import_react.default.createElement(
    import_index.default,
    {
      key,
      type,
      tyroUrl,
      tyroVersion,
      source,
      mode,
      terminal,
      onChangeStatus,
      onChangeParams,
      getApi,
      params: apiParams,
      styles: props == null ? void 0 : props.styles,
      isWebPos: props == null ? void 0 : props.isWebPos
    }
  ) : null;
};
var EFTPos_default = (0, import_react.forwardRef)(EFTPos);
