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/pay/toC/index.tsx
var toC_exports = {};
__export(toC_exports, {
  default: () => toC_default
});
module.exports = __toCommonJS(toC_exports);
var import_react = __toESM(require("react"));
var import_decimal = require("decimal.js");
var import_ahooks = require("ahooks");
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_PayCountdown = __toESM(require("./PayCountdown"));
var import_PayAmount = __toESM(require("./PayAmount"));
var import_WalletPassBlock = __toESM(require("./WalletPassBlock"));
var import_PaymentList = __toESM(require("./PaymentList"));
var import_PaymentMethods = __toESM(require("./PaymentMethods"));
var import_serve = require("./serve");
var import_model = require("./model");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_utils2 = require("../../../utils");
var import_payGroup = require("./payGroup");
var import_locales = __toESM(require("./locales"));
var import_utils3 = require("./utils");
var import_index = require("./index.less");
var ToCPay = (props, ref) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t;
  const { state, dispatch } = (0, import_react.useContext)(import_model.Context);
  const paymentListRef = (0, import_react.useRef)();
  const paymentMethodsRef = (0, import_react.useRef)();
  const [loading, setLoading] = (0, import_react.useState)(true);
  const [submitLoading, setSubmitLoading] = (0, import_react.useState)(false);
  const [open, setOpen] = (0, import_react.useState)(false);
  const [renderType, setRenderType] = (0, import_react.useState)("modal");
  const walletPassBlockRef = (0, import_react.useRef)(null);
  const context = (0, import_useEngineContext.default)();
  const [showInformation, setShowInformation] = (0, import_react.useState)(false);
  const [showDetectIncognitoConfirm, setShowDetectIncognitoConfirm] = (0, import_react.useState)(false);
  const utils = context.appHelper.utils || {};
  const dvaStore = (_c = (_b = (_a = context.appHelper.utils) == null ? void 0 : _a.getStore) == null ? void 0 : _b.call(_a)) == null ? void 0 : _c.getState();
  const customer_id = (_i = (_h = (_g = (_f = (_e = (_d = context.appHelper.utils) == null ? void 0 : _d.getStore()) == null ? void 0 : _e.getState) == null ? void 0 : _f.call(_e)) == null ? void 0 : _g.global) == null ? void 0 : _h.userInfo) == null ? void 0 : _i.id;
  const shopName = (_l = (_k = (_j = dvaStore.core) == null ? void 0 : _j.core) == null ? void 0 : _k.shop) == null ? void 0 : _l.name;
  import_utils.locales.init(import_locales.default, ((_m = dvaStore.core) == null ? void 0 : _m.translateLocale) || "en");
  import_utils2.request.setRequest(utils == null ? void 0 : utils.request);
  const _initStore = (initProps) => {
    var _a2;
    dispatch({
      type: "init",
      payload: {
        ...initProps,
        status: "init",
        // 将支付回调储存在store, 方便其他模块调用
        payCallback: props.callback,
        history: (_a2 = context.appHelper.utils) == null ? void 0 : _a2.history
        // 支付组
        // payGroup: {
        //   order_id: initProps?.order?.order_id,
        //   total_amount: initProps?.order?.amount,
        //   // 原订单信息
        //   _order: initProps?.order,
        //   payment_group_id: initProps?.order?.payment_group_id,
        // },
      }
    });
  };
  const getWalletSetting = async (initProps) => {
    var _a2, _b2;
    const sale_channel = ((_a2 = initProps == null ? void 0 : initProps.order) == null ? void 0 : _a2.sale_channel) || "online-store";
    const { wallet, wallet_setting } = await (0, import_serve.getWalletNameAndPopupStatus)({
      setting_type: `${sale_channel}-wallet-setting`
    });
    const setting = {
      name: ((_b2 = utils == null ? void 0 : utils.translation) == null ? void 0 : _b2.call(utils, wallet == null ? void 0 : wallet.name)) || import_utils.locales.getText("tocPay.text.walletName")(shopName),
      popup_status: (wallet_setting == null ? void 0 : wallet_setting.popup_status) ?? 1
    };
    if (setting.popup_status === 1) {
      setTimeout(() => {
        var _a3;
        (_a3 = walletPassBlockRef.current) == null ? void 0 : _a3.open();
      });
    }
    dispatch({
      type: "setWalletSetting",
      payload: setting
    });
  };
  const init = async (initProps) => {
    const { renderType: renderType2 } = initProps;
    setRenderType(renderType2 ?? "modal");
    setOpen(true);
    setSubmitLoading(false);
    setLoading(true);
    _initStore(initProps);
    (0, import_payGroup.removePayGroupFromStorage)(initProps.order.order_id);
    await _getPaymentsAndWalletPass(initProps.order);
    await getWalletSetting(initProps);
  };
  const _getPaymentsAndWalletPass = async (order) => {
    var _a2, _b2;
    try {
      const data = await (0, import_serve.getPaymentsAndWalletPass)({
        order_id: order.order_id,
        total_amount: order.amount,
        sale_channel: order.sale_channel || "online-store"
      });
      const {
        remain_amount = 0,
        wallet_pass_recommend_list,
        wallet_pass_amount,
        payment_list,
        walletPass
      } = data || {};
      dispatch({
        type: "setPayGroup",
        payload: {
          // ...state.payGroup,
          order_id: order == null ? void 0 : order.order_id,
          // total_amount: order?.amount,
          // 原订单信息
          _order: order,
          payment_group_id: order == null ? void 0 : order.payment_group_id,
          // 支付方式没有walletPass时walletPass设置null
          walletPass: walletPass ? {
            ...(_a2 = state.payGroup) == null ? void 0 : _a2.walletPass,
            ...walletPass,
            amount: wallet_pass_amount,
            cards: wallet_pass_recommend_list
          } : null,
          total_amount: order == null ? void 0 : order.amount,
          wait_amount: remain_amount
        }
      });
      await ((_b2 = paymentListRef.current) == null ? void 0 : _b2.init(payment_list));
      setTimeout(() => {
        setLoading(false);
      }, 100);
    } catch (err) {
      console.log("err", err);
      payCallback({
        key: "fail",
        data: {
          err,
          order,
          fn: "_getPaymentsAndWalletPass"
        }
      });
    }
  };
  const handlePaymentByType = async (type, payGroup) => {
    var _a2, _b2, _c2;
    setSubmitLoading(true);
    await ((_c2 = paymentMethodsRef.current) == null ? void 0 : _c2.onPay({
      type: type || ((_b2 = (_a2 = state.payGroup) == null ? void 0 : _a2.otherPayment) == null ? void 0 : _b2.service),
      payGroup: payGroup || state.payGroup
    }));
    setSubmitLoading(false);
  };
  const paymentInit = async (newOrderId) => {
    var _a2, _b2;
    const orderId = newOrderId || ((_a2 = state.payGroup) == null ? void 0 : _a2.order_id);
    setSubmitLoading(true);
    try {
      const data = await (0, import_serve.getPaymentInit)({
        order_id: orderId,
        amount: (_b2 = state.payGroup) == null ? void 0 : _b2.total_amount
      });
      dispatch({
        type: "setPayGroup",
        payload: {
          order_id: orderId,
          total_amount: data.amount,
          payment_group_id: data.payment_group_id,
          payment_priority: data.payment_priority
        }
      });
      return {
        ...state.payGroup,
        order_id: orderId,
        total_amount: data.amount,
        payment_group_id: data.payment_group_id,
        payment_priority: data.payment_priority
      };
    } catch (err) {
      (0, import_utils.sendWarningLog)({
        title: "创建交易组失败 paymentInit catch",
        content: [
          { key: "错误信息", value: (err == null ? void 0 : err.message) || "未知错误" },
          { key: "错误堆栈", value: (err == null ? void 0 : err.stack) || "无堆栈信息" },
          { key: "错误类型", value: (err == null ? void 0 : err.name) || "未知错误类型" }
        ]
      });
      setSubmitLoading(false);
      payCallback({
        key: "fail",
        data: {
          err,
          orderId,
          fn: "paymentInit"
        }
      });
    }
  };
  const waitAmount = (0, import_react.useMemo)(() => {
    var _a2;
    return ((_a2 = state.payGroup) == null ? void 0 : _a2.wait_amount) || 0;
  }, [(_n = state.payGroup) == null ? void 0 : _n.wait_amount]);
  const isWalletPassPay = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2;
    const isWalletPass = (_c2 = (_b2 = (_a2 = state.payGroup) == null ? void 0 : _a2.walletPass) == null ? void 0 : _b2.cards) == null ? void 0 : _c2.length;
    return waitAmount <= 0 && isWalletPass;
  }, [state.payGroup, waitAmount]);
  const isDisabled = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    if (waitAmount > 0) {
      const isOtherPayment = (_b2 = (_a2 = state.payGroup) == null ? void 0 : _a2.otherPayment) == null ? void 0 : _b2.service;
      return !isOtherPayment;
    } else {
      return !isWalletPassPay;
    }
  }, [state.payGroup, waitAmount, isWalletPassPay]);
  const getIsShowDetectIncognitoConfirm = async (payGroup) => {
    const { isPrivate } = await (0, import_utils.detectIncognito)();
    return ((payGroup == null ? void 0 : payGroup.wait_amount) || 0) > 0 && (0, import_utils3.getIsWalletPassAndTripartitePayment)(payGroup) && isPrivate;
  };
  const onSubmit = async (newOrderId) => {
    var _a2;
    try {
      let newPayGroup = state.payGroup;
      const result = await getIsShowDetectIncognitoConfirm(newPayGroup);
      if (result) {
        setShowDetectIncognitoConfirm(true);
        return;
      }
      if (!((_a2 = state.payGroup) == null ? void 0 : _a2.payment_group_id)) {
        newPayGroup = await paymentInit(newOrderId);
      }
      handlePaymentByType(void 0, newPayGroup);
    } catch (err) {
      console.log("err", err);
      (0, import_utils.sendWarningLog)({
        title: "提交支付失败 onSubmit catch",
        content: [
          { key: "错误信息", value: (err == null ? void 0 : err.message) || "未知错误" },
          { key: "错误堆栈", value: (err == null ? void 0 : err.stack) || "无堆栈信息" },
          { key: "错误类型", value: (err == null ? void 0 : err.name) || "未知错误类型" }
        ]
      });
    }
  };
  const paymentTypeChange = (payload) => {
    dispatch({
      type: "setPayGroup",
      payload: {
        otherPayment: payload
      }
    });
  };
  const okText = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2, _d2;
    let current = (_a2 = state.payGroup) == null ? void 0 : _a2.otherPayment;
    if (((_b2 = state.payGroup) == null ? void 0 : _b2.wait_amount) == 0) {
      return import_utils.locales.getText("tocPay.text.submit");
    }
    if (current == null ? void 0 : current.surcharge) {
      return /* @__PURE__ */ import_react.default.createElement("span", { className: "" }, import_utils.locales.getText("tocPay.text.pay"), " ", /* @__PURE__ */ import_react.default.createElement(import_materials.PisellText.Amount, { value: ((_c2 = state.payGroup) == null ? void 0 : _c2.wait_amount) || 0 }), " +", import_utils.locales.getText("tocPay.text.surcharge"));
    } else {
      return /* @__PURE__ */ import_react.default.createElement("span", { className: "" }, import_utils.locales.getText("tocPay.text.pay"), " ", /* @__PURE__ */ import_react.default.createElement(import_materials.PisellText.Amount, { value: ((_d2 = state.payGroup) == null ? void 0 : _d2.wait_amount) || 0 }));
    }
  }, [state.payGroup]);
  const payCallback = async (res) => {
    var _a2;
    if (res.key === "cancel") {
      setOpen(false);
    }
    (_a2 = props.callback) == null ? void 0 : _a2.call(props, res);
  };
  const onCancel = () => {
    var _a2, _b2;
    (0, import_payGroup.removePayGroupFromStorage)((_a2 = state.payGroup) == null ? void 0 : _a2.order_id);
    setShowInformation(false);
    setOpen(false);
    payCallback({
      key: "cancel",
      data: {
        order_id: (_b2 = state.payGroup) == null ? void 0 : _b2.order_id
      }
    });
  };
  (0, import_ahooks.useUpdateEffect)(() => {
    var _a2, _b2;
    (_b2 = paymentListRef.current) == null ? void 0 : _b2.calculateSurcharge(
      ((_a2 = state.payGroup) == null ? void 0 : _a2.wait_amount) || 0
    );
  }, [(_o = state.payGroup) == null ? void 0 : _o.wait_amount]);
  (0, import_react.useImperativeHandle)(ref, () => {
    return {
      init,
      payCallback,
      onSubmit
    };
  });
  const renderPaymentListTitle = () => {
    var _a2, _b2;
    if (waitAmount == 0) {
      return /* @__PURE__ */ import_react.default.createElement("div", { className: "custom-payment-list-title" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "" }, import_utils.locales.getText("tocPay.text.clickSubmitToComplete")), /* @__PURE__ */ import_react.default.createElement("div", { className: "custom-payment-list-title-desc" }, import_utils.locales.getText("tocPay.text.noExtraPayNeeded")));
    }
    if (((_a2 = state.payGroup) == null ? void 0 : _a2.total_amount) !== waitAmount) {
      return /* @__PURE__ */ import_react.default.createElement("div", { className: "custom-payment-list-title" }, import_utils.locales.getText("tocPay.text.continuePayment"), " ", /* @__PURE__ */ import_react.default.createElement(
        import_materials.PisellText.Amount,
        {
          className: "custom-payment-list-title-price",
          value: ((_b2 = state.payGroup) == null ? void 0 : _b2.wait_amount) || 0
        }
      ));
    }
    return import_utils.locales.getText("tocPay.text.paymentMethod");
  };
  const onWalletPassChange = (0, import_ahooks.useMemoizedFn)(
    (walletPass) => {
      var _a2, _b2;
      const _waitAmount = new import_decimal.Decimal(String(((_a2 = state.payGroup) == null ? void 0 : _a2.total_amount) || 0)).minus(new import_decimal.Decimal(String(walletPass.amount || 0))).toNumber();
      dispatch({
        type: "setPayGroup",
        payload: {
          walletPass: {
            ...(_b2 = state.payGroup) == null ? void 0 : _b2.walletPass,
            ...walletPass
          },
          wait_amount: _waitAmount
        }
      });
    }
  );
  return /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellContainer,
    {
      renderType,
      props: {
        forceRender: true,
        title: /* @__PURE__ */ import_react.default.createElement("div", null, import_utils.locales.getText("tocPay.text.checkout")),
        open,
        cancelVisible: false,
        okText,
        bodyStyle: {
          padding: 24
        },
        onCancel: () => {
          setShowInformation(true);
        },
        okButtonProps: {
          disabled: isDisabled,
          loading: submitLoading,
          className: "toc-pay-submit-btn"
        },
        onOk: () => {
          onSubmit();
        }
      }
    },
    /* @__PURE__ */ import_react.default.createElement(
      import_materials.PisellModal.Information,
      {
        open: showInformation,
        title: import_utils.locales.getText("tocPay.text.prompt"),
        describe: import_utils.locales.getText("tocPay.text.confirmLeave"),
        okText: import_utils.locales.getText("tocPay.text.continuePay"),
        cancelText: import_utils.locales.getText("tocPay.text.leave"),
        closable: true,
        cancelButtonProps: {
          onClick: () => {
            onCancel();
          }
        },
        maskClosable: false,
        onCancel: () => {
          setShowInformation(false);
        },
        onOk: () => {
          setShowInformation(false);
        }
      }
    ),
    /* @__PURE__ */ import_react.default.createElement(
      import_materials.PisellModal.Information,
      {
        open: showDetectIncognitoConfirm,
        describe: import_utils.locales.getText("tocPay.text.detectIncognitoConfirm"),
        okText: import_utils.locales.getText("tocPay.text.copyLink"),
        closable: true,
        maskClosable: false,
        onCancel: () => {
          setShowDetectIncognitoConfirm(false);
        },
        onOk: async () => {
          await (0, import_utils.copyToClipboard)(window.location.href);
          (0, import_materials.PisellToast)({
            content: import_utils.locales.getText("tocPay.text.copySuccess")
          });
        }
      }
    ),
    /* @__PURE__ */ import_react.default.createElement(
      import_materials.PisellLoading,
      {
        loading,
        mask: true
      },
      ((_p = state.order) == null ? void 0 : _p.countdown) && /* @__PURE__ */ import_react.default.createElement(import_PayCountdown.default, { time: (_q = state.order) == null ? void 0 : _q.countdown }),
      /* @__PURE__ */ import_react.default.createElement(import_PayAmount.default, { amount: ((_r = state.payGroup) == null ? void 0 : _r.total_amount) || 0 }),
      ((_s = state.payGroup) == null ? void 0 : _s.walletPass) && /* @__PURE__ */ import_react.default.createElement(
        import_WalletPassBlock.default,
        {
          customer_id,
          payGroup: state.payGroup,
          onWalletPassChange,
          ref: walletPassBlockRef,
          walletSetting: state.walletSetting
        }
      ),
      /* @__PURE__ */ import_react.default.createElement(
        import_PaymentList.default,
        {
          ref: paymentListRef,
          handlePayment: (detail) => {
            handlePaymentByType(detail == null ? void 0 : detail.service);
          },
          paymentTypeChange,
          hide: ((_t = state.payGroup) == null ? void 0 : _t.wait_amount) == 0,
          renderTitle: renderPaymentListTitle
        }
      )
    ),
    /* @__PURE__ */ import_react.default.createElement(import_PaymentMethods.default, { ref: paymentMethodsRef, payCallback })
  );
};
var toC_default = (0, import_model.Provider)((0, import_react.forwardRef)(ToCPay));
