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/checkout/plugin.tsx
var plugin_exports = {};
__export(plugin_exports, {
  default: () => plugin_default
});
module.exports = __toCommonJS(plugin_exports);
var import_useEngineContext = __toESM(require("../../hooks/useEngineContext"));
var import_react = __toESM(require("react"));
var import_PaymentModal = __toESM(require("./PaymentModal"));
var import_serve = require("../booking/editBookingModal/serve");
var import_ticketBooking = require("../ticketBooking/components/ticketBooking");
var import_utils = require("../../utils");
var import_utils2 = require("../booking/components/footer/utils");
var import_amount = require("../booking/components/footer/amount");
var import_utils3 = require("@pisell/utils");
var import_model = require("../booking/info/model");
var import_materials = require("@pisell/materials");
var import_useLogger = __toESM(require("../../hooks/useLogger"));
var import_utils4 = require("../ticketBooking/utils");
var PaymentModalContent = ({ state, dispatch }) => {
  var _a, _b;
  const [dataReady, setDataReady] = (0, import_react.useState)(false);
  const [data, setData] = (0, import_react.useState)(null);
  const [client, setClient] = (0, import_react.useState)(null);
  const context = (0, import_useEngineContext.default)();
  const engineProps = ((_a = context.engine) == null ? void 0 : _a.props) || {};
  import_utils.request.setRequest(context.appHelper.utils.request);
  const { getData, pisellos, pisellosAllModule } = context.appHelper.utils;
  const Toast = (0, import_materials.useToast)();
  const logger = (0, import_useLogger.default)();
  const { BookingTicket } = pisellosAllModule || {};
  const bookingTicketModule = pisellos == null ? void 0 : pisellos.getModule((0, import_utils4.getBookingTicketKey)("ticket"));
  const getExternalPaymentModalData = () => {
    if (engineProps.paymentModalData) return engineProps.paymentModalData;
    if (engineProps.order_info && engineProps.subtotal_info) {
      return {
        order_info: engineProps.order_info,
        subtotal_info: engineProps.subtotal_info,
        existPayment: engineProps.existPayment
      };
    }
    return null;
  };
  const getEditModeClient = (bookingOrigin, booking) => {
    var _a2;
    const formattedClient = ((_a2 = booking == null ? void 0 : booking.client) == null ? void 0 : _a2.value) || {};
    const originCustomer = (bookingOrigin == null ? void 0 : bookingOrigin.customer) || {};
    const displayName = (originCustomer.display_name || "").trim() || (formattedClient.display_name || "").trim() || ((bookingOrigin == null ? void 0 : bookingOrigin.customer_name) || "").trim();
    const nickname = (originCustomer.nickname || "").trim() || (formattedClient.nickname || "").trim() || (formattedClient.name || "").trim();
    return {
      ...originCustomer,
      ...formattedClient,
      id: formattedClient.id || originCustomer.id || (bookingOrigin == null ? void 0 : bookingOrigin.customer_id),
      name: formattedClient.name || displayName || nickname,
      display_name: displayName,
      nickname,
      email: formattedClient.email || originCustomer.email || (bookingOrigin == null ? void 0 : bookingOrigin.email) || "",
      phone: formattedClient.phone || originCustomer.phone || (bookingOrigin == null ? void 0 : bookingOrigin.phone) || "",
      country_calling_code: formattedClient.country_calling_code || originCustomer.country_calling_code || (bookingOrigin == null ? void 0 : bookingOrigin.country_calling_code) || "",
      cover: formattedClient.cover || originCustomer.cover || ""
    };
  };
  (0, import_react.useLayoutEffect)(() => {
    if (BookingTicket && !bookingTicketModule) {
      pisellos == null ? void 0 : pisellos.registerModule(new BookingTicket((0, import_utils4.getBookingTicketKey)("ticket")), {
        initialState: {},
        otherParams: {
          cacheId: (0, import_utils4.getBookingTicketKey)("ticket"),
          platform: "shop"
        }
      });
    }
    setTimeout(() => {
      var _a2;
      const module2 = pisellos == null ? void 0 : pisellos.getModule((0, import_utils4.getBookingTicketKey)("ticket"));
      (_a2 = module2 == null ? void 0 : module2.initPeripheralsListener) == null ? void 0 : _a2.call(module2);
    }, 0);
  }, []);
  const getDataFromHost = () => {
    try {
      const is_price_include_tax = getData("is_price_include_tax");
      const tax_rate = getData("tax_rate") || "10";
      const tax_title = getData("tax_title") || "GST";
      const surcharge_list = getData("surcharge_list");
      const schedule_list = getData("schedule_list");
      let scheduleById = {};
      if (Array.isArray(schedule_list)) {
        for (let item of schedule_list) {
          scheduleById[item.id] = item;
        }
      }
      return {
        is_price_include_tax,
        tax_rate,
        tax_title,
        surcharge_list,
        schedule_list,
        scheduleById
      };
    } catch (error) {
      console.error(error);
      return {};
    }
  };
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c, _d, _e;
    const externalModalData = getExternalPaymentModalData();
    if (!engineProps.order_id) {
      if (!(externalModalData == null ? void 0 : externalModalData.order_info) || !(externalModalData == null ? void 0 : externalModalData.subtotal_info)) {
        (_a2 = logger == null ? void 0 : logger.addLog) == null ? void 0 : _a2.call(logger, {
          metadata: {
            engineProps
          },
          title: "打开支付弹窗失败-缺少 order_id 或 paymentModalData"
        });
        setDataReady(false);
        setData(null);
        return;
      }
      setClient(
        engineProps.client || ((_c = (_b2 = externalModalData.order_info) == null ? void 0 : _b2.client) == null ? void 0 : _c.value) || ((_d = externalModalData.order_info) == null ? void 0 : _d.client)
      );
      setData(externalModalData);
      setDataReady(true);
      window.isPaymentModalPluginOpen = true;
      (_e = Toast == null ? void 0 : Toast.hide) == null ? void 0 : _e.call(Toast);
      return;
    }
    const getBookingDetail = async () => {
      var _a3, _b3, _c2, _d2, _e2, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o;
      (_a3 = Toast == null ? void 0 : Toast.loading) == null ? void 0 : _a3.call(Toast, "", 0);
      (_b3 = logger == null ? void 0 : logger.addLog) == null ? void 0 : _b3.call(logger, {
        metadata: {},
        title: `开始编辑订单-获取订单详情 ${engineProps.order_id}`
      });
      try {
        let bookingOrigin = await (0, import_serve._getBookingDetail)(engineProps.order_id);
        (_c2 = logger == null ? void 0 : logger.addLog) == null ? void 0 : _c2.call(logger, {
          metadata: {
            bookingOrigin
          },
          title: `开始编辑订单-格式化订单详情 ${engineProps.order_id}`
        });
        let booking = (0, import_ticketBooking._formatBookingDetail)(bookingOrigin, {});
        (_d2 = logger == null ? void 0 : logger.addLog) == null ? void 0 : _d2.call(logger, {
          metadata: {},
          title: `开始编辑订单-formatValues ${engineProps.order_id}`
        });
        let values = (0, import_utils2.formatValues)({ ...booking, order_type: bookingOrigin.type });
        const ids = [];
        (_e2 = values.relation_products) == null ? void 0 : _e2.forEach((item) => {
          ids.push(item.product_id);
        });
        (_f = values.bookings) == null ? void 0 : _f.forEach((item) => {
          var _a4;
          ids.push((_a4 = item.product) == null ? void 0 : _a4.product_id);
        });
        if ((ids == null ? void 0 : ids.length) > 0) {
          console.log("开始获取定金数据");
          const products = await (bookingTicketModule == null ? void 0 : bookingTicketModule.getProductByIds(ids));
          console.log(ids, products);
          products == null ? void 0 : products.forEach((item) => {
            var _a4, _b4, _c3;
            if (((_a4 = item == null ? void 0 : item.custom_deposit_data) == null ? void 0 : _a4.has_deposit) == 1) {
              (_b4 = values.relation_products) == null ? void 0 : _b4.forEach((relationProduct) => {
                if (relationProduct.product_id === item.id) {
                  relationProduct.custom_deposit_data = item.custom_deposit_data;
                }
              });
              (_c3 = values.bookings) == null ? void 0 : _c3.forEach((booking2) => {
                var _a5;
                if (((_a5 = booking2.product) == null ? void 0 : _a5.product_id) === item.id) {
                  booking2.product.custom_deposit_data = item.custom_deposit_data;
                }
              });
            }
          });
        }
        let ScheduleModule = context.appHelper.utils.pisellos.getModule("schedule") || context.appHelper.utils.pisellos.getModule("appointmentBooking_schedule");
        (_g = logger == null ? void 0 : logger.addLog) == null ? void 0 : _g.call(logger, {
          metadata: {},
          title: `开始编辑订单-getSumTotal ${engineProps.order_id}`
        });
        let total = (0, import_amount.getSumTotal)(booking, {
          isEdit: true,
          ScheduleModule,
          ...getDataFromHost()
        });
        (_h = logger == null ? void 0 : logger.addLog) == null ? void 0 : _h.call(logger, {
          metadata: {},
          title: `开始编辑订单-total ${engineProps.order_id}`
        });
        total = {
          ...total,
          expectAmount: bookingOrigin.expect_amount,
          actualPaidAmount: bookingOrigin.paid_amount,
          dueAmount: bookingOrigin.total_amount,
          notPaidAmount: bookingOrigin.amount_gap,
          orderPaidAmount: bookingOrigin.order_paid_amount,
          originExpectAmount: bookingOrigin.expect_amount,
          shopDiscount: bookingOrigin.shop_discount,
          roundingAmount: bookingOrigin.rounding_amount,
          sumTotalAmount: bookingOrigin.total_amount,
          tax: bookingOrigin.tax_fee,
          productAmount: bookingOrigin.product_expect_amount,
          paySurchargeFee: bookingOrigin.surcharge_fee,
          taxInfo: {
            title: bookingOrigin.tax_title,
            rate: bookingOrigin.tax_rate,
            is_price_include_tax: bookingOrigin.is_price_include_tax
          }
        };
        const orderTotalList = [
          // 订单已付金额
          {
            hidden: !booking.bookingId,
            key: "custom_orderPaidAmount",
            value: total.orderPaidAmount,
            label: import_utils3.locales.getText("pisell2.text.amount-paid-on-order")
          },
          // 支付手续费
          {
            hidden: !booking.bookingId,
            key: "custom_paySurchargeFee",
            value: total.paySurchargeFee,
            label: import_utils3.locales.getText("pisell1.text.payment-fee")
          },
          // 客户实付金额
          {
            hidden: !booking.bookingId,
            key: "custom_actualPaidAmount",
            value: total.actualPaidAmount,
            label: import_utils3.locales.getText(
              "pisell2.text.amount-actually-paid-by-the-customer"
            )
          },
          // 退款金额
          {
            hidden: !booking.bookingId || !total.totalRefundAmount,
            key: "custom_totalRefundAmount",
            value: total.totalRefundAmount,
            label: import_utils3.locales.getText("pisell2.text.refunded-amount")
          }
        ];
        const subTotalList = [
          // 小计
          {
            key: "sub_total",
            value: total.productAmount
          },
          // 自定义手续费
          ...total.surcharge || [],
          // 税费
          {
            key: "tax",
            value: total.tax,
            tax: total.taxInfo
          },
          // 订单折扣（优惠券等）
          {
            key: "discount",
            value: total.shopDiscount
          },
          // 手动折扣
          // {
          //   key: 'shop_discount',
          //   value: Number(state.shop_discount) || 0,
          //   label: locales.getText('pisell2.text.manual-price-adjustment'),
          // },
          // 总计
          {
            key: "expect_amount",
            value: total.expectAmount,
            label: import_utils3.locales.getText("pisell2.subtotal.total")
          },
          // 舍入金额
          {
            hidden: !total.roundingAmount,
            key: "custom_roundingAmount",
            value: total.roundingAmount,
            label: import_utils3.locales.getText("pisell1.text.rounding")
          }
        ];
        (_i = logger == null ? void 0 : logger.addLog) == null ? void 0 : _i.call(logger, {
          metadata: {},
          title: `开始编辑订单-subTotalList ${engineProps.order_id}`
        });
        console.log(values);
        const checkoutModule = await pisellos.getModule("checkout");
        const paymentMethodList = await checkoutModule.getPaymentMethodsAsync();
        (_j = logger == null ? void 0 : logger.addLog) == null ? void 0 : _j.call(logger, {
          metadata: {},
          title: `开始编辑订单-getPaymentMethodsAsync ${engineProps.order_id}`
        });
        const onlineStorePaymentCodeList = ["WXPAY", "WECHAT", "ALIPAY", "APPLE_PAY", "CREDIT_CARD_3DS", "CREDIT_CARD_TOKEN", "GOOGLE_PAY", "GOOGLE_PAY_3DS", "CREDIT_CARD"];
        const existPayment = (_l = (_k = bookingOrigin.payments) == null ? void 0 : _k.filter((item) => item.status === "paid")) == null ? void 0 : _l.map((item) => {
          var _a4;
          let paymentMethod = paymentMethodList.find((method) => method.code === item.payment_method);
          if (!paymentMethod && onlineStorePaymentCodeList.includes(item.payment_method)) {
            paymentMethod = {
              id: "",
              name: item.payment_method,
              code: item.payment_method,
              type: item.payment_method
            };
          }
          return {
            uuid: ((_a4 = item == null ? void 0 : item.metadata) == null ? void 0 : _a4.unique_payment_number) || item.pay_number,
            custom_payment_id: paymentMethod.id,
            order_payment_id: item.id,
            name: paymentMethod == null ? void 0 : paymentMethod.name,
            code: item.payment_method,
            type: paymentMethod == null ? void 0 : paymentMethod.type,
            amount: item.origin_amount,
            rounding_amount: item.rounding_amount,
            status: "active",
            order_payment_type: item.type,
            metadata: item.metadata,
            voucher_id: item.voucher_id,
            service_charge: item.service_charge && typeof item.service_charge === "object" && !Array.isArray(item.service_charge) ? item.service_charge : {},
            created_at: item.created_at,
            updated_at: item.updated_at
          };
        });
        console.log(values);
        const modalData = {
          order_info: values,
          subtotal_info: {
            subTotalList,
            orderTotalList,
            total
          },
          existPayment
        };
        (_m = logger == null ? void 0 : logger.addLog) == null ? void 0 : _m.call(logger, {
          metadata: {},
          title: `开始编辑订单-dispatch ${engineProps.order_id}`
        });
        if (dispatch) {
          dispatch({
            type: "setState",
            payload: {
              ...booking
            }
          });
        }
        setClient(getEditModeClient(bookingOrigin, booking));
        setData(modalData);
        setDataReady(true);
        window.isPaymentModalPluginOpen = true;
        (_n = Toast == null ? void 0 : Toast.hide) == null ? void 0 : _n.call(Toast);
      } catch (error) {
        (_o = logger == null ? void 0 : logger.addLog) == null ? void 0 : _o.call(logger, {
          metadata: {
            error: error == null ? void 0 : error.message
          },
          title: `开始编辑订单-error ${engineProps.order_id}`
        });
      }
    };
    getBookingDetail();
  }, [
    engineProps.order_id,
    engineProps.paymentModalData,
    engineProps.order_info,
    engineProps.subtotal_info,
    engineProps.existPayment,
    engineProps.client
  ]);
  console.log(dataReady, "dataReady");
  if (!dataReady) return null;
  const totalInfo = ((_b = data == null ? void 0 : data.subtotal_info) == null ? void 0 : _b.total) || (data == null ? void 0 : data.total) || {};
  return /* @__PURE__ */ import_react.default.createElement(
    import_PaymentModal.default,
    {
      open: true,
      editOrderId: engineProps.order_id,
      data,
      paymentResultDisplayMode: engineProps.paymentResultDisplayMode || "toast",
      shopDiscount: engineProps.shopDiscount ?? (totalInfo == null ? void 0 : totalInfo.shopDiscount),
      client,
      currentTotalPrice: engineProps.currentTotalPrice ?? (totalInfo == null ? void 0 : totalInfo.productAmount),
      config: engineProps == null ? void 0 : engineProps.config,
      setEditCartMode: () => {
        engineProps == null ? void 0 : engineProps.callback({ type: "close" });
      },
      onClose: (reset) => {
        window.isPaymentModalPluginOpen = false;
        engineProps == null ? void 0 : engineProps.callback({ type: "close", reset });
      },
      callback: (result) => {
        console.log(result);
        engineProps == null ? void 0 : engineProps.callback({ type: "callback", data: result });
        window.isPaymentModalPluginOpen = false;
      }
    }
  );
};
var PaymentModalPlugin = (0, import_model.Provider)(PaymentModalContent);
var plugin_default = PaymentModalPlugin;
