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/info/service/addService/index.tsx
var addService_exports = {};
__export(addService_exports, {
  default: () => addService_default
});
module.exports = __toCommonJS(addService_exports);
var import_SearchLg = __toESM(require("@pisell/icon/es/SearchLg"));
var import_utils = require("@pisell/utils");
var import_ahooks = require("ahooks");
var import_antd = require("antd");
var import_debounce = __toESM(require("lodash/debounce"));
var import_react = __toESM(require("react"));
var import_useEngineContext = __toESM(require("../../../../../hooks/useEngineContext"));
var import_TabProduct = __toESM(require("../../../components/TabProduct"));
var import_addButton = __toESM(require("../../../components/addButton"));
var import_drawer = __toESM(require("../../../components/drawer"));
var import_utils2 = require("../../../utils");
var import_dateRange = __toESM(require("../../dateRange"));
var import_model = require("../../model");
var import_status = require("../../service2/status");
var import_utils3 = require("../../service2/utils");
var import_utils4 = require("../../utils");
var import_serve = require("../serve");
var import_serviceManager = require("../serviceManager");
var import_index = require("./index.less");
var shopList = [
  2886,
  4422,
  5538,
  6930,
  6814,
  6813,
  6812,
  6087,
  6303,
  6080,
  6978,
  7386,
  6848,
  6305
];
var Info = (props) => {
  var _a, _b, _c, _d, _e, _f;
  const { onEdit, drawerProps, renderMode } = props;
  const [search, setSearch] = (0, import_react.useState)("");
  let { state, dispatch } = (0, import_react.useContext)(import_model.Context);
  const [loading, setLoading] = (0, import_react.useState)(false);
  const searchRef = (0, import_react.useRef)();
  const headerRef = (0, import_react.useRef)(null);
  const [headerHeight, setHeaderHeight] = (0, import_react.useState)(0);
  const context = (0, import_useEngineContext.default)();
  state = state || (props == null ? void 0 : props.state);
  dispatch = dispatch || (props == null ? void 0 : props.dispatch);
  import_utils2.request.setRequest(context.appHelper.utils.request);
  const { createBookingData, createBooking } = (0, import_serviceManager.useService)({
    renderMode,
    onEdit,
    state,
    dispatch
  });
  const isDay = (0, import_react.useMemo)(() => {
    return (0, import_utils3.isDayBooking)(state);
  }, [state.renderType]);
  const handleResize = () => {
    var _a2;
    if (headerRef == null ? void 0 : headerRef.current) {
      setHeaderHeight((_a2 = headerRef.current) == null ? void 0 : _a2.offsetHeight);
    }
  };
  const debouncedHandleResize = (0, import_debounce.default)(handleResize, 100);
  (0, import_react.useEffect)(() => {
    if (isDay && state.isTerminalDayBookingPage) {
      handleResize();
      window.addEventListener("resize", debouncedHandleResize);
    }
    return () => {
      window.removeEventListener("resize", debouncedHandleResize);
    };
  }, [debouncedHandleResize]);
  const customerId = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    return ((_b2 = (_a2 = state.client) == null ? void 0 : _a2.value) == null ? void 0 : _b2.id) || 1;
  }, [(_b = (_a = state.client) == null ? void 0 : _a.value) == null ? void 0 : _b.id]);
  const setDefaultService = async (list) => {
    if (state.renderType !== "eventBooking") {
      return;
    }
    if (state.bookingId) {
      return;
    }
    if (list.length !== 1) {
      return;
    }
    let _list = [...state.service.value];
    if (_list.length !== 0) {
      return;
    }
    setLoading(true);
    let product = list[0];
    const detail = await (0, import_serve.getProductDetail)(product.id, {
      schedule_date: state.date.value.format("YYYY-MM-DD"),
      customer_id: customerId
    });
    const isBundleOrCombination = (0, import_utils4.getIsBundleOrCombination)(detail.data);
    setLoading(false);
    if (isBundleOrCombination) return;
    let _item = {
      ...product,
      product_id: product.id,
      _id: (0, import_utils.getUniqueId)(),
      _extend: {
        start_date: state.date.value,
        startDate: state.date.value,
        endDate: isDay ? state.date.end_date : state.date.value,
        start_time: "00:00:00",
        duration: 10,
        quantity: 1,
        price: product.price,
        total: product.price,
        origin_total: product.price,
        product_name: product.title
      }
    };
    _list.push(_item);
    dispatch({
      type: "setService",
      payload: {
        value: _list,
        edit: true
      }
    });
  };
  const getServices = async (params) => {
    var _a2, _b2, _c2;
    setLoading(true);
    if (state.renderType === "eventBooking" && !((_b2 = (_a2 = state.eventOtherParams) == null ? void 0 : _a2.productIds) == null ? void 0 : _b2.length)) {
      dispatch({
        type: "setService",
        payload: {
          services: []
        }
      });
      setLoading(false);
      return;
    }
    let dayParams = {};
    if (isDay && !(0, import_utils3.isEventBooking)(state)) {
      dayParams.extension_type = ["normal", "product_appointment"];
    }
    let data = await state.apis.getServices({
      skip: 1,
      num: 500,
      extension_type: state.renderType === "eventBooking" ? void 0 : [
        "product_appointment",
        "appointment_ticket",
        "session_product",
        "session_ticket"
      ],
      with: ["category"],
      ids: state.renderType === "eventBooking" ? (_c2 = state.eventOtherParams) == null ? void 0 : _c2.productIds : void 0,
      open_quotation: 1,
      with_schedule: 1,
      with_count: ["bundleGroup", "optionGroup"],
      order_by_string: "sort:desc",
      status: "published",
      schedule_date: params == null ? void 0 : params.schedule_date,
      customer_id: customerId,
      ...dayParams
    });
    setLoading(false);
    let lists = (data == null ? void 0 : data.list) || [];
    if ((0, import_utils3.isDaysBooking)(state)) {
      const id = (0, import_utils3.holderId)(state);
      lists = (0, import_utils3.getDayProducts)(id, lists, state == null ? void 0 : state.isTerminalDayBookingPage);
    }
    if (!state.service.addModal) {
      setDefaultService(lists);
    }
    dispatch({
      type: "setService",
      payload: {
        services: lists
      }
    });
  };
  const handleSelectService = () => {
    dispatch({
      type: "setService",
      payload: {
        addModal: true
      }
    });
    if (!state.isTerminal) {
      setTimeout(() => {
        var _a2, _b2;
        (_b2 = (_a2 = searchRef.current) == null ? void 0 : _a2.focus) == null ? void 0 : _b2.call(_a2);
      }, 100);
    }
  };
  const handleSelectProduct = (0, import_ahooks.useMemoizedFn)(
    (item, type) => {
      const isSession = (0, import_utils2.isSessionProduct)(item);
      let isEject = (0, import_utils2.getIsEject)(item, type);
      const isOnlySession = (0, import_utils2.getIsOnlySession)(item);
      if (isDay) {
        isEject = type === "detail" || item.bundle_group_count > 0 || item.option_group_count > 0 || item.is_variant > 0;
      }
      state.action({
        type: "pisell1.handleOpenProductModal",
        data: {
          id: item.id,
          date: state.date.value.format("YYYY-MM-DD"),
          showConfig: {
            option: isDay ? true : false,
            session: isSession,
            variant: isDay ? true : false,
            package: true
          },
          is_eject: isEject ? 1 : 0,
          isOnlySession,
          customer_id: customerId,
          isOS: isSession
        },
        callback: async (e, extension_type, detail) => {
          const data = await createBookingData({
            product: { ...detail || item, _params: e }
          });
          createBooking({ booking: data });
        }
      });
    }
  );
  const renderList = (0, import_react.useMemo)(() => {
    var _a2;
    let _list = ((_a2 = state.service) == null ? void 0 : _a2.services) || [];
    if ((0, import_utils3.isDaysBooking)(state)) {
      if (!(0, import_utils3.holderId)(state)) {
        _list = _list.filter(
          (item) => (0, import_utils3.isNormalProductByDurationSchedule)(item)
        );
      }
    }
    const isIncludes = (str) => {
      return str.toLowerCase().indexOf(search.toLowerCase()) !== -1;
    };
    return (0, import_utils2.formatProductListByCategory)(
      _list,
      search ? (item) => isIncludes(item.title) : void 0
    );
  }, [search, (_c = state.service) == null ? void 0 : _c.services, state == null ? void 0 : state.activeCartId]);
  const isService = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    return ((_b2 = (_a2 = state.service) == null ? void 0 : _a2.value) == null ? void 0 : _b2.length) > 0;
  }, [state.service.value]);
  (0, import_react.useEffect)(() => {
    var _a2, _b2, _c2, _d2, _e2, _f2, _g, _h, _i, _j;
    if (shopList.includes(
      ((_c2 = (_b2 = (_a2 = context.appHelper) == null ? void 0 : _a2.utils) == null ? void 0 : _b2.getData) == null ? void 0 : _c2.call(_b2, "shop_id")) || ((_h = (_g = (_f2 = (_e2 = (_d2 = context.appHelper.utils.store) == null ? void 0 : _d2.getState) == null ? void 0 : _e2.call(_d2)) == null ? void 0 : _f2.global) == null ? void 0 : _g.globalConfig) == null ? void 0 : _h.id)
    ) || state.closeAutoOpenService) {
      return;
    }
    if (state.modalOpen && !state.bookingId && state.renderType !== "eventBooking" && ((_j = (_i = state.service) == null ? void 0 : _i.value) == null ? void 0 : _j.length) === 0) {
      setTimeout(() => {
        handleSelectService();
      }, 10);
    }
  }, [state.modalOpen, state.bookingId, (_d = state.service) == null ? void 0 : _d.value]);
  const showAddButton = (0, import_react.useMemo)(() => {
    return !state.disabledEdit && !state.channelDisabledEdit;
  }, [state.disabledEdit, state.channelDisabledEdit]);
  const currentDate = (0, import_react.useMemo)(() => {
    return state.date.value.format("YYYY-MM-DD");
  }, [state.date.value]);
  (0, import_ahooks.useUpdateEffect)(() => {
    if (state.service.addModal) {
      getServices({ schedule_date: currentDate });
      setSearch("");
    }
  }, [state.service.addModal, currentDate]);
  (0, import_react.useEffect)(() => {
    if (renderMode === "current") {
      getServices({ schedule_date: currentDate });
    }
  }, [renderMode, currentDate]);
  (0, import_react.useEffect)(() => {
    if (state.renderType === "eventBooking" && state.modalOpen) {
      getServices({ schedule_date: currentDate });
    }
  }, [state.renderType, state.modalOpen, currentDate]);
  const addButton = (0, import_react.useMemo)(() => {
    if (isDay) {
      return;
    }
    if (state.isBookingCreatePage) {
      return /* @__PURE__ */ import_react.default.createElement("div", { style: { height: 20 } });
    }
    if (state.renderType === "eventBooking") {
      return isService ? /* @__PURE__ */ import_react.default.createElement("div", { style: { height: 20 } }) : /* @__PURE__ */ import_react.default.createElement(
        import_addButton.default,
        {
          loading,
          showSub: false,
          title: import_utils.locales.getText("pisell2.text.add-a-service"),
          subTitle: import_utils.locales.getText("pisell2.text.add-another-service"),
          onClick: handleSelectService
        }
      );
    }
    return showAddButton ? /* @__PURE__ */ import_react.default.createElement(
      import_addButton.default,
      {
        showSub: isService,
        title: import_utils.locales.getText("pisell2.text.add-a-service"),
        subTitle: import_utils.locales.getText("pisell2.text.add-another-service"),
        onClick: handleSelectService
      }
    ) : /* @__PURE__ */ import_react.default.createElement("div", { style: { height: 20 } });
  }, [
    state.renderType,
    showAddButton,
    isService,
    state.service.value,
    loading
  ]);
  const isRenderCurrent = (0, import_react.useMemo)(() => {
    return renderMode === "current";
  }, [renderMode]);
  const colSpan = (0, import_react.useMemo)(() => {
    const isTerminal = state.isTerminalDayBookingPage;
    const showDate = !!(isDay && (0, import_utils3.holderId)(state) && !(0, import_utils3.isEventBooking)(state));
    return (0, import_status.inputDateCol)(showDate, isTerminal);
  }, [state.isTerminalDayBookingPage, isDay, (0, import_utils3.holderId)(state)]);
  return (0, import_react.useMemo)(() => {
    var _a2, _b2;
    const header = /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-service-header", ref: headerRef }, /* @__PURE__ */ import_react.default.createElement(import_antd.Row, { gutter: [16, 16] }, isDay && (0, import_utils3.holderId)(state) && !(0, import_utils3.isEventBooking)(state) ? /* @__PURE__ */ import_react.default.createElement(import_antd.Col, { ...colSpan.date }, /* @__PURE__ */ import_react.default.createElement(import_dateRange.default, { state, dispatch })) : null, /* @__PURE__ */ import_react.default.createElement(import_antd.Col, { ...colSpan.input }, /* @__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_utils.locales.getText("pisell2.text.search"),
        allowClear: true,
        value: search,
        onChange: (e) => {
          setSearch(e.target.value);
        }
      }
    ))));
    const content = /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: isDay && headerHeight > 76 ? "pisell-lowcode__booking-service-date-body" : "pisell-lowcode__booking-service-body"
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_TabProduct.default,
        {
          list: renderList,
          amountSymbol: state.amountSymbol,
          onChange: handleSelectProduct,
          scrollDom: isRenderCurrent ? ".pisell-lowcode__booking-vertical-add-service-wrap" : ".booking-server-wrap .pisell-lowcode-drawer-body "
        }
      )
    );
    if (renderMode === "current") {
      return /* @__PURE__ */ import_react.default.createElement(
        "div",
        {
          className: "pisell-lowcode__booking-vertical-add-service-wrap",
          style: { width: "100%", height: "100%", overflow: "auto" }
        },
        header,
        content
      );
    }
    return /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, ((_b2 = (_a2 = state.service) == null ? void 0 : _a2.cacheItem) == null ? void 0 : _b2.autoClose) && /* @__PURE__ */ import_react.default.createElement(import_antd.Skeleton, { loading: true, active: true, round: true }), addButton, /* @__PURE__ */ import_react.default.createElement(
      import_drawer.default,
      {
        titleNoWrap: true,
        open: state.service.addModal && !state.isBookingCreatePage && !state.isTerminalDayBookingPage,
        title: isDay ? import_utils.locales.getText("pisell2.text.select.items") : import_utils.locales.getText("pisell2.text.select-service"),
        rootClassName: "booking-server-wrap",
        onClose: () => {
          dispatch({
            type: "setService",
            payload: {
              addModal: false,
              changeService: false
            }
          });
        },
        header,
        ...drawerProps || {}
      },
      content
    ));
  }, [
    (_f = (_e = state.service) == null ? void 0 : _e.cacheItem) == null ? void 0 : _f.autoClose,
    addButton,
    state.service.addModal,
    import_utils.locales,
    search,
    renderList,
    state.amountSymbol,
    state.renderType,
    state == null ? void 0 : state.activeCartId,
    headerHeight,
    (0, import_utils3.holderId)(state)
  ]);
};
var addService_default = Info;
