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/booking/addons/index.tsx
var addons_exports = {};
__export(addons_exports, {
  default: () => addons_default,
  formatProducts: () => formatProducts
});
module.exports = __toCommonJS(addons_exports);
var import_react = __toESM(require("react"));
var import_SearchLg = __toESM(require("@pisell/icon/es/SearchLg"));
var import_antd = require("antd");
var import_drawer = __toESM(require("../components/drawer"));
var import_tabPane = __toESM(require("../components/tabPane"));
var import_model = require("./model");
var import_selectProductItem = __toESM(require("../components/TabProduct/selectProductItem"));
var import_TabProduct = __toESM(require("../components/TabProduct"));
var import_emptyBooking = __toESM(require("../components/emptyBooking"));
var import_footer = __toESM(require("../components/footer"));
var import_utils = require("../components/footer/utils");
var import_utils2 = require("../utils");
var import_utils3 = require("@pisell/utils");
var import_index = require("./index.less");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var formatProducts = (values) => {
  let arr = [];
  arr = values.map((item) => {
    var _a, _b, _c, _d, _e, _f, _g, _h, _i;
    const bundleDiscountList = (0, import_utils.getBundleDiscountList)(((_b = (_a = item._extend) == null ? void 0 : _a.other) == null ? void 0 : _b.bundle) || []);
    const discount_list = [...(item == null ? void 0 : item.discount_list) || []];
    discount_list.push(...bundleDiscountList);
    return {
      order_detail_id: item.order_detail_id || 0,
      num: item._extend.quantity,
      price: (0, import_utils.formatProductPrice)(item),
      product_id: item.id,
      discount_list: discount_list || [],
      discount_amount: 0,
      product_discount_reason: "",
      is_charge_tax: item.is_charge_tax,
      note: "",
      discountway: "num",
      discount_type: "discount",
      bundle_edit: (_c = item._extend) == null ? void 0 : _c.bundle_edit,
      product_bundle: (0, import_utils.formatProductBundle)((_e = (_d = item._extend) == null ? void 0 : _d.other) == null ? void 0 : _e.bundle),
      "product_option_item": (0, import_utils.formatProductOption)((_g = (_f = item._extend) == null ? void 0 : _f.other) == null ? void 0 : _g.option),
      "product_variant_id": ((_i = (_h = item._extend) == null ? void 0 : _h.other) == null ? void 0 : _i.product_variant_id) || 0,
      "source_product_price": (0, import_utils.getSourceProductPrice)(item),
      "main_product_selling_price": (0, import_utils.getMainProductSellingPrice)(item) ?? (0, import_utils.formatProductPrice)(item),
      "calculated_original_price": (0, import_utils.formatOriginalPrice)(item),
      "calculated_selling_price": (0, import_utils.formatSellingPrice)(item),
      "tax_fee": item._extend.tax_fee
    };
  });
  return arr;
};
var restoreProductOtherData = (data) => {
  let detail = data;
  return {
    product_id: detail.product_id,
    option: [],
    bundle: (detail.product_bundle || []).map((bundleItem) => {
      return {
        ...bundleItem,
        title: bundleItem.bundle_title,
        group_id: bundleItem.bundle_group_id,
        id: bundleItem.bundle_id,
        product_id: bundleItem.bundle_product_id,
        bundle_variant_id: bundleItem.bundle_variant_id,
        quantity: bundleItem.num,
        option: bundleItem.option.map((optionItem) => {
          return {
            ...optionItem,
            name: optionItem.name["auto"],
            quantity: bundleItem.num,
            product_option_item_id: optionItem.option_group_item_id
          };
        })
      };
    }),
    product_variant_id: detail.product_variant_id || 0,
    quantity: Number(detail.product_quantity)
  };
};
var formatProductValues = (data) => {
  return data.map((d) => {
    return {
      ...d,
      id: d.product_id,
      title: d.product_title,
      isAddons: true,
      quantity: d.product_quantity,
      cover: d.product_cover,
      price: Number(d.source_product_price),
      _extend: {
        total: Number(d.selling_price),
        origin_total: Number(d.selling_price),
        payment_price: Number(d.payment_price),
        price: Number(d.source_product_price),
        quantity: d.product_quantity,
        bundle_edit: 0,
        other: restoreProductOtherData(d)
      },
      payment_price: Number(d.payment_price)
    };
  });
};
var Addons = (0, import_model.Provider)((props) => {
  var _a, _b, _c;
  const { globalState } = props;
  const { state, dispatch } = (0, import_react.useContext)(import_model.Context);
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [listLoading, setListLoading] = (0, import_react.useState)(false);
  const [search, setSearch] = (0, import_react.useState)("");
  const searchRef = (0, import_react.useRef)();
  const context = (0, import_useEngineContext.default)();
  const [modal, contextHolder] = import_antd.Modal.useModal();
  const { isTerminal, interaction } = ((_a = context.appHelper) == null ? void 0 : _a.utils) || {};
  import_utils2.request.setRequest(context.appHelper.utils.request);
  (0, import_react.useEffect)(() => {
    dispatch({
      type: "setState",
      payload: {
        setGlobalState: props.setGlobalState
      }
    });
  }, []);
  (0, import_react.useEffect)(() => {
    dispatch({
      type: "setState",
      payload: {
        ...globalState
      }
    });
  }, [globalState]);
  const init = () => {
    getAddonsByOrderId();
  };
  (0, import_react.useEffect)(() => {
    var _a2;
    if (isTerminal == null ? void 0 : isTerminal()) {
      (_a2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _a2.mountFunction(
        "booking",
        "refreshBookingDetailAddons",
        () => {
          init();
        }
      );
    }
  }, [state]);
  const getAddonsByOrderId = async () => {
    setLoading(true);
    let data = await state.apis.getAddonsByOrderId();
    dispatch({
      type: "setAddons",
      payload: {
        value: formatProductValues(data || []),
        load: true,
        edit: false
      }
    });
    setLoading(false);
  };
  const getProducts = async () => {
    setListLoading(true);
    let data = await state.apis.getProducts({
      skip: 1,
      num: 500,
      extension_type: [
        "normal",
        "product_bundle",
        "product_package_ticket",
        "ticket"
      ],
      with: ["category"],
      // include_formula: "no",
      // include_bundle: "no",
      // include_option: "no",
      // include_variant: "no",
      status: "published",
      open_quotation: 1,
      with_schedule: 0,
      with_count: ["bundleGroup", "optionGroup"],
      order_by_string: "sort:desc",
      _config: {
        useCache: true
      }
    });
    setListLoading(false);
    dispatch({
      type: "setAddons",
      payload: {
        originData: (data == null ? void 0 : data.list) || []
      }
    });
  };
  const handleAddProduct = (item, type) => {
    let _list = [...state.addons.value];
    const isSession = (0, import_utils2.isSessionProduct)(item);
    const isEject = (0, import_utils2.getIsEject)(item, type);
    const isOnlySession = (0, import_utils2.getIsOnlySession)(item);
    state.action({
      type: "pisell1.handleOpenProductModal",
      data: {
        id: item.id,
        date: state.date.value.format("YYYY-MM-DD"),
        showConfig: {
          option: true,
          session: isSession,
          variant: true,
          package: true,
          number: true
        },
        isOnlySession,
        is_eject: isEject ? 1 : 0,
        isOS: isSession
      },
      callback: (e, extension_type, detail) => {
        const _detail = detail || item;
        let product = {
          ..._detail,
          _id: (0, import_utils3.getUniqueId)(),
          isAddons: true,
          _key: e.key,
          _extend: {
            other: e,
            quantity: (e == null ? void 0 : e.quantity) || 1
          },
          quantity: (e == null ? void 0 : e.quantity) || 1
        };
        product._extend.price = (0, import_utils2.getMainPrice)(product, _detail.price);
        let _total = (0, import_utils2.getProductTotalPrice)(product);
        product._extend.total = _total;
        product._extend.origin_total = _total;
        let _item = _list.find((d) => {
          var _a2;
          return d._extend.other.rowKey === e.rowKey && !d.booking_id && !((_a2 = d.discount_list) == null ? void 0 : _a2.length);
        });
        if (_item) {
          _item._extend.quantity = _item._extend.quantity + product.quantity;
        } else {
          _list.push(product);
        }
        dispatch({
          type: "setAddons",
          payload: {
            value: _list,
            showModal: false,
            // 编辑态
            edit: true
          }
        });
      }
    });
  };
  const onChangeQuantity = (e, item) => {
    var _a2;
    let quantity = e.target.value;
    let _list = [...state.addons.value];
    if (quantity == 0) {
      _list = _list.filter((d) => d._id !== item._id);
    } else {
      let _item = {
        ...item,
        _extend: {
          ...item._extend,
          quantity: Number(e.target.value)
        }
      };
      if (((_a2 = _item._extend) == null ? void 0 : _a2.bundle_edit) !== void 0) {
        _item._extend.bundle_edit = 1;
      }
      _list = _list.map((d) => d._id === item._id ? _item : d);
    }
    dispatch({
      type: "setAddons",
      payload: {
        value: _list,
        edit: true
      }
    });
  };
  const renderList = (0, import_react.useMemo)(() => {
    var _a2;
    let _list = ((_a2 = state.addons) == null ? void 0 : _a2.originData) || [];
    const isIncludes = (str) => {
      return str.toLowerCase().indexOf(search.toLowerCase()) !== -1;
    };
    return (0, import_utils2.formatProductListByCategory)(
      _list,
      search ? (item) => isIncludes(item.title) : void 0
    );
  }, [search, (_b = state.addons) == null ? void 0 : _b.originData]);
  const isEdit = (0, import_react.useMemo)(() => {
    var _a2;
    return (_a2 = state == null ? void 0 : state.addons) == null ? void 0 : _a2.edit;
  }, [(_c = state == null ? void 0 : state.addons) == null ? void 0 : _c.edit]);
  const handleOpenAdd = () => {
    var _a2, _b2;
    if (isTerminal == null ? void 0 : isTerminal()) {
      return (_b2 = (_a2 = interaction == null ? void 0 : interaction.utils) == null ? void 0 : _a2.postMessageToApp) == null ? void 0 : _b2.call(_a2, {
        module: "booking",
        key: "edit_order",
        data: {
          order_id: state.bookingId
        }
      });
    }
    getProducts();
    setSearch("");
    dispatch({
      type: "setAddons",
      payload: {
        showModal: true
      }
    });
    if (!state.isTerminal) {
      setTimeout(() => {
        var _a3, _b3;
        (_b3 = (_a3 = searchRef.current) == null ? void 0 : _a3.focus) == null ? void 0 : _b3.call(_a3);
      }, 100);
    }
  };
  const _footer = (0, import_react.useMemo)(() => {
    if (state.disabledEdit) {
      return [];
    }
    let arr = [
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Button,
        {
          className: "pisell-lowcode__booking-footer-buttons-item",
          type: "default",
          disabled: loading,
          onClick: handleOpenAdd
        },
        import_utils3.locales.getText("pisell2.text.add")
      )
    ];
    return arr;
  }, [state, isEdit, loading]);
  const footer = (0, import_react.useMemo)(() => {
    if (!state.bookingId) {
      return null;
    }
    return /* @__PURE__ */ import_react.default.createElement(import_footer.default, { state, dispatch, buttons: _footer, source: "addons" });
  }, [state, _footer]);
  const editProductDetail = (item) => {
    if (state.disabledEdit) {
      return;
    }
    const isSession = (0, import_utils2.isSessionProduct)(item);
    state.action({
      type: "pisell1.handleOpenProductModal",
      data: {
        id: item.id,
        date: state.date.value.format("YYYY-MM-DD"),
        showConfig: {
          option: true,
          session: isSession,
          variant: true,
          package: true,
          number: true
        },
        value: item._extend.other,
        isOS: isSession
      },
      callback: (e, extension_type, detail) => {
        var _a2;
        const _detail = detail || item;
        let product = {
          ...item,
          ..._detail,
          isAddons: true,
          // 编辑商品时清除折扣信息
          discount_list: [],
          _extend: {
            ...item._extend,
            other: e,
            quantity: (e == null ? void 0 : e.quantity) || 1
          }
        };
        if (((_a2 = product._extend) == null ? void 0 : _a2.bundle_edit) !== void 0) {
          product._extend.bundle_edit = 1;
        }
        let _total = (0, import_utils2.getProductTotalPrice)(product);
        product._extend.total = _total;
        product._extend.origin_total = _total;
        let _list = [...state.addons.value];
        _list = _list.map((d) => d._id === product._id ? product : d);
        dispatch({
          type: "setAddons",
          payload: {
            value: _list,
            showModal: false,
            // 编辑态
            edit: true
          }
        });
      }
    });
  };
  return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(
    import_tabPane.default,
    {
      loading,
      header: import_utils3.locales.getText("pisell2.text.addons"),
      footer,
      state,
      dispatch,
      source: "addons"
    },
    !state.bookingId ? /* @__PURE__ */ import_react.default.createElement(import_emptyBooking.default, null) : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, state.addons.value.length ? /* @__PURE__ */ import_react.default.createElement("div", { className: "", style: { margin: "0 -32px" } }, state.addons.value.map((d) => {
      return /* @__PURE__ */ import_react.default.createElement(
        import_selectProductItem.default,
        {
          disabled: state.disabledEdit,
          item: d,
          key: d.id,
          amountSymbol: state.amountSymbol,
          onClick: editProductDetail,
          onChangeQuantity: (e) => {
            onChangeQuantity(e, d);
          }
        }
      );
    })) : /* @__PURE__ */ import_react.default.createElement(
      import_emptyBooking.default,
      {
        description: import_utils3.locales.getText("pisell1.text.no-addons")
      }
    ), /* @__PURE__ */ import_react.default.createElement(
      import_drawer.default,
      {
        titleNoWrap: true,
        open: state.addons.showModal,
        title: import_utils3.locales.getText("pisell2.text.addons"),
        onClose: () => {
          dispatch({
            type: "setAddons",
            payload: {
              showModal: false
            }
          });
        },
        rootClassName: "booking-addons-wrap",
        header: /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-service-header" }, /* @__PURE__ */ import_react.default.createElement(
          import_antd.Input,
          {
            ref: searchRef,
            prefix: /* @__PURE__ */ import_react.default.createElement(import_SearchLg.default, null),
            style: { marginTop: 16, height: 44 },
            placeholder: import_utils3.locales.getText("pisell2.text.search"),
            allowClear: true,
            value: search,
            onChange: (e) => {
              setSearch(e.target.value);
            }
          }
        ))
      },
      /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-service-body" }, /* @__PURE__ */ import_react.default.createElement(
        import_antd.Skeleton,
        {
          loading: listLoading,
          active: true,
          round: true,
          style: { padding: 20 }
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_TabProduct.default,
          {
            scrollDom: ".booking-addons-wrap .pisell-lowcode-drawer-body",
            list: renderList,
            amountSymbol: state.amountSymbol,
            onChange: handleAddProduct
          }
        )
      ))
    ))
  ), contextHolder);
});
var addons_default = Addons;
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  formatProducts
});
