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/info2/service/addService/index.tsx
var addService_exports = {};
__export(addService_exports, {
  default: () => addService_default
});
module.exports = __toCommonJS(addService_exports);
var import_react = __toESM(require("react"));
var import_SearchLg = __toESM(require("@pisell/icon/es/SearchLg"));
var import_drawer = __toESM(require("../../../components/drawer"));
var import_TabProduct = __toESM(require("../../../components/TabProduct"));
var import_model = require("../../../info/model");
var import_addButton = __toESM(require("../../../components/addButton"));
var import_antd = require("antd");
var import_addService = require("../../../info/service/addService/index.less");
var import_useEngineContext = __toESM(require("../../../../../hooks/useEngineContext"));
var import_serve = require("../../../info/service/serve");
var import_utils = require("../../../info/utils");
var import_utils2 = require("./utils");
var import_utils3 = require("../../../utils");
var import_utils4 = require("@pisell/utils");
var import_ahooks = require("ahooks");
var import_utils5 = require("../../../info/service2/utils");
var import_utils6 = require("../../../../ticketBooking/utils");
var import_utils7 = require("../../../info/service2/Group/utils");
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 context = (0, import_useEngineContext.default)();
  state = state || (props == null ? void 0 : props.state);
  dispatch = dispatch || (props == null ? void 0 : props.dispatch);
  import_utils3.request.setRequest(context.appHelper.utils.request);
  const customerId = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    return ((_b2 = (_a2 = state.client) == null ? void 0 : _a2.value) == null ? void 0 : _b2.id) || void 0;
  }, [(_b = (_a = state.client) == null ? void 0 : _a.value) == null ? void 0 : _b.id]);
  console.log(customerId, "customerIdcustomerId");
  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"),
      open_deposit: 1
    });
    const isBundleOrCombination = (0, import_utils.getIsBundleOrCombination)(detail.data);
    setLoading(false);
    if (isBundleOrCombination) return;
    let _item = {
      ...product,
      product_id: product.id,
      _id: (0, import_utils4.getUniqueId)(),
      _extend: {
        start_date: state.date.value,
        startDate: state.date.value,
        endDate: 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 data = await state.apis.getServices({
      skip: 1,
      num: 500,
      extension_type: state.renderType === "eventBooking" ? void 0 : [
        "product_appointment",
        "appointment_ticket",
        "service_product",
        "session_product",
        "session_ticket"
      ],
      with: ["category", "resourceRelation"],
      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: params == null ? void 0 : params.customer_id
    });
    setLoading(false);
    if (!state.service.addModal) {
      setDefaultService(data == null ? void 0 : data.list);
    }
    dispatch({
      type: "setService",
      payload: {
        services: (data == null ? void 0 : data.list) || []
      }
    });
  };
  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 = (item, type) => {
    var _a2, _b2, _c2;
    if (!(0, import_utils5.isNormalProductByDurationSchedule)(item)) {
      if (!Array.isArray((_a2 = state.service) == null ? void 0 : _a2.resourcesOrigin) || !state.service.resourcesOrigin.length) {
        dispatch({
          type: "setService",
          payload: {
            ...state.service,
            reloadResourceModal: true
          }
        });
        return;
      }
    }
    const isSession = (0, import_utils3.isSessionProduct)(item);
    const isEject = (0, import_utils3.getIsEject)(item, type);
    const isOnlySession = (0, import_utils3.getIsOnlySession)(item);
    let lock = false;
    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: (0, import_utils6.getIsShowNumber)(item, state)
        },
        is_eject: isEject ? 1 : 0,
        isOnlySession,
        isOS: isSession,
        customer_id: (_c2 = (_b2 = state.client) == null ? void 0 : _b2.value) == null ? void 0 : _c2.id
      },
      callback: async (e, extension_type, detail) => {
        var _a3, _b3;
        if (lock) {
          return;
        }
        lock = true;
        setTimeout(() => {
          lock = false;
        }, 2e3);
        const _detail = detail || item;
        const other = JSON.parse(JSON.stringify(e));
        other.session = e.session;
        let cacheItem = {
          ..._detail,
          product_id: item.id,
          _id: (0, import_utils4.getUniqueId)(),
          _key: e.key,
          _extend: {
            start_date: state.date.value,
            quantity: (e == null ? void 0 : e.quantity) || 1,
            product_name: item.title,
            other
          },
          new: 1
        };
        const isMultiDay = (0, import_utils2.isMultiDayProduct)(cacheItem);
        if (isMultiDay) {
          cacheItem._extend.end_date = state.date.value.add(1, "day");
        }
        cacheItem._extend.price = (0, import_utils3.getMainPrice)(cacheItem, _detail.price);
        let _total = (0, import_utils3.getProductTotalPrice)(cacheItem);
        cacheItem._extend.total = _total;
        cacheItem._extend.origin_total = _total;
        const _isEdit = !!state.service.cacheItem;
        if (_isEdit) {
          cacheItem._id = (_a3 = state.service.cacheItem) == null ? void 0 : _a3._id;
          cacheItem.new = 0;
        }
        if (renderMode === "current") {
          cacheItem.currentDefaultTime = state.date.value.format("HH:mm");
        }
        cacheItem = (0, import_utils2.getProductExtend)({ cacheItem, state });
        const getMultiDayCacheItem = async (isConcatBookings) => {
          cacheItem = await (0, import_utils2.getMultiDay)({
            start_date: cacheItem._extend.start_date,
            end_date: cacheItem._extend.end_date,
            state,
            cacheItem
          });
          cacheItem = (0, import_utils7.createBookingItemsByGroup)(cacheItem);
          if (isConcatBookings) {
            cacheItem = (0, import_utils7.concatBookings)(cacheItem);
          }
        };
        if (state.renderType === "eventBooking" || isMultiDay) {
          cacheItem.autoClose = false;
        }
        if (cacheItem.autoClose) {
          cacheItem.autoClose = false;
          let newValue = [...state.service.value];
          if (!newValue.some((item2) => item2._id === cacheItem._id)) {
            newValue.push(cacheItem);
          } else {
            newValue = newValue.map((item2) => {
              if (item2._id === cacheItem._id) {
                return { ...cacheItem, new: 0 };
              }
              return item2;
            });
          }
          dispatch({
            type: "setService",
            payload: {
              addModal: false,
              value: newValue,
              edit: true,
              changeService: false
            }
          });
        } else {
          (_b3 = window.openBookingEditModal) == null ? void 0 : _b3.call(window);
          if (isMultiDay) {
            await getMultiDayCacheItem(true);
          }
          dispatch({
            type: "setService",
            payload: {
              editModal: true,
              cacheItem,
              addModal: !cacheItem.autoClose,
              changeService: false
            }
          });
          onEdit == null ? void 0 : onEdit(cacheItem);
        }
      }
    });
  };
  const renderList = (0, import_react.useMemo)(() => {
    var _a2;
    let _list = ((_a2 = state.service) == null ? void 0 : _a2.services) || [];
    const isIncludes = (str) => {
      return str.toLowerCase().indexOf(search.toLowerCase()) !== -1;
    };
    return (0, import_utils3.formatProductListByCategory)(
      _list,
      search ? (item) => isIncludes(item.title) : void 0
    );
  }, [search, (_c = state.service) == null ? void 0 : _c.services]);
  const isService = (0, import_react.useMemo)(() => {
    return state.service.value.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, customer_id: customerId });
      setSearch("");
    }
  }, [state.service.addModal, currentDate, customerId]);
  (0, import_react.useEffect)(() => {
    if (renderMode === "current") {
      getServices({ schedule_date: currentDate, customer_id: customerId });
    }
  }, [renderMode, currentDate, customerId]);
  (0, import_react.useEffect)(() => {
    if (state.renderType === "eventBooking" && state.modalOpen) {
      getServices({ schedule_date: currentDate, customer_id: customerId });
    }
  }, [state.renderType, state.modalOpen, currentDate, customerId]);
  const addButton = (0, import_react.useMemo)(() => {
    if (state.isBookingCreatePage) {
      return /* @__PURE__ */ import_react.default.createElement("div", { style: { height: 20 } });
    }
    return null;
    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_utils4.locales.getText("pisell2.text.add-a-service"),
          subTitle: import_utils4.locales.getText("pisell2.text.add-another-service"),
          onClick: handleSelectService
        }
      );
    }
    return showAddButton ? /* @__PURE__ */ import_react.default.createElement(
      import_addButton.default,
      {
        showSub: isService,
        title: import_utils4.locales.getText("pisell2.text.add-a-service"),
        subTitle: import_utils4.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 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_utils4.locales.getText("pisell2.text.search"),
      allowClear: true,
      value: search,
      onChange: (e) => {
        setSearch(e.target.value);
      }
    }
  ));
  const content = /* @__PURE__ */ import_react.default.createElement("div", { className: "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 (isRenderCurrent) {
    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, ((_f = (_e = state.service) == null ? void 0 : _e.cacheItem) == null ? void 0 : _f.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,
      title: import_utils4.locales.getText("pisell2.text.select-service"),
      rootClassName: "booking-server-wrap",
      onClose: () => {
        dispatch({
          type: "setService",
          payload: {
            addModal: false,
            changeService: false
          }
        });
      },
      header,
      ...drawerProps || {}
    },
    content
  ));
};
var addService_default = Info;
