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/plus/salesSdk/bookingEditService/BookingEditServiceDrawer.tsx
var BookingEditServiceDrawer_exports = {};
__export(BookingEditServiceDrawer_exports, {
  BookingEditServiceDrawer: () => BookingEditServiceDrawer
});
module.exports = __toCommonJS(BookingEditServiceDrawer_exports);
var import_utils = require("@pisell/utils");
var import_ArrowLeft = __toESM(require("@pisell/icon/es/ArrowLeft"));
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_ahooks = require("ahooks");
var import_materials = require("@pisell/materials");
var import_dayjs = __toESM(require("dayjs"));
var import_classnames = __toESM(require("classnames"));
var import_duration = __toESM(require("../../../components/booking/materiels/duration"));
var import_Capacity = __toESM(require("../../../components/booking/info2/service/editService/Capacity"));
var import_Resources = __toESM(require("../../../components/booking/info2/service/editService/Resources"));
var import_Holder = __toESM(require("../../../components/booking/info2/service/editService/Holder"));
var import_collapsibleList = __toESM(require("../../../components/booking/components/collapsibleList"));
var import_utils2 = require("../../../components/booking/components/collapsibleList/utils");
var import_noteModal = __toESM(require("../../noteModal"));
var import_priceKeyboard = require("../../../pro/priceKeyboard");
var import_EditTabs = __toESM(require("../../../components/booking/info/service/editService/EditTabs"));
var import_SalesSdkBookingList = require("./SalesSdkBookingList");
var import_compensatedPisellContainer = __toESM(require("../../../pro/compensatedPisellContainer"));
var import_responsive = require("../../../responsive");
var import_utils3 = require("../../../components/booking/info/service2/utils");
var import_utils4 = require("../../../components/booking/utils");
var import_utilsByBooking = require("../../../components/booking/info2/utilsByBooking");
var import_utils5 = require("../../../components/booking/info2/service/addService/utils");
var import_resolveMultiDayQuotation = require("../utils/resolveMultiDayQuotation");
var import_multiDayPriceCache = require("../utils/multiDayPriceCache");
var import_utils6 = require("../../../components/booking/info/service2/Group/utils");
var import_useEngineContext = __toESM(require("../../../hooks/useEngineContext"));
var import_buildEditedCacheItem = require("./buildEditedCacheItem");
var import_formatHolderOptions = require("../utils/formatHolderOptions");
var import_holderOptionsSyncBridge = require("../utils/holderOptionsSyncBridge");
var import_formatHolderOptions2 = require("../utils/formatHolderOptions");
var import_SalesSdkHolderContext = require("../context/SalesSdkHolderContext");
var import_normalizeResourceDisplay = require("./normalizeResourceDisplay");
var import_useBookingEditPetState = require("./useBookingEditPetState");
var import_resolveCacheItemForResourceCheck = require("./resolveCacheItemForResourceCheck");
var import_useBookingEditProduct = require("./useBookingEditProduct");
var import_editService = require("../../../components/booking/info2/service/editService/index.less");
var import_drawer = require("../../../components/booking/components/drawer/index.less");
var submitLock = false;
function hasChangedField(changedValues, field) {
  return Object.prototype.hasOwnProperty.call(changedValues || {}, field);
}
function syncNormalBookingTimeFields(cacheItem) {
  if (!(cacheItem == null ? void 0 : cacheItem._extend)) return cacheItem;
  const { startDate, endDate } = (0, import_utils4.getServiceTimes)(cacheItem);
  return {
    ...cacheItem,
    _extend: {
      ...cacheItem._extend,
      startDate,
      endDate,
      start_date: startDate,
      end_date: endDate,
      start_time: startDate.format("HH:mm"),
      end_time: endDate.format("HH:mm")
    }
  };
}
var BookingEditServiceDrawerInner = (props) => {
  var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _A, _B, _C, _D, _E, _F, _G, _H, _I, _J, _K, _L;
  const {
    open,
    cacheItem: cacheItemProp,
    onConfirm,
    onCancel,
    bookingState: baseBookingState,
    onCacheItemChange,
    showNoteButton = true,
    multiDayExpanding = false,
    variant
  } = props;
  const [form] = import_antd.Form.useForm();
  const useTotal = import_antd.Form.useWatch("total", form);
  const useResource = import_antd.Form.useWatch("resource", form);
  const useStartTime = import_antd.Form.useWatch("start_time", form);
  const useDuration = import_antd.Form.useWatch("duration", form);
  const useHolderId = import_antd.Form.useWatch("holder_id", form);
  const useNote = import_antd.Form.useWatch("note", form);
  const useStartDate = import_antd.Form.useWatch("start_date", form);
  const useEndDate = import_antd.Form.useWatch("end_date", form);
  const resourcesRef = (0, import_react.useRef)(null);
  const isChangeTotal = (0, import_react.useRef)(false);
  const isRefreshingResourcesRef = (0, import_react.useRef)(false);
  const prevDrawerOpenRef = (0, import_react.useRef)(false);
  const prevMultiDayExpandingRef = (0, import_react.useRef)(false);
  const [noteModalOpen, setNoteModalOpen] = (0, import_react.useState)(false);
  const [currentTab, setCurrentTab] = (0, import_react.useState)("batch_edit");
  const [maskClosable, setMaskClosable] = (0, import_react.useState)(false);
  const [val, setVal] = (0, import_react.useState)(false);
  const context = (0, import_useEngineContext.default)();
  const getData = (_b = (_a = context.appHelper) == null ? void 0 : _a.utils) == null ? void 0 : _b.getData;
  const action = (_d = (_c = context == null ? void 0 : context.appHelper) == null ? void 0 : _c.utils) == null ? void 0 : _d.action;
  const engineRequest = (_f = (_e = context == null ? void 0 : context.appHelper) == null ? void 0 : _e.utils) == null ? void 0 : _f.request;
  const translationOriginal = (_h = (_g = context == null ? void 0 : context.appHelper) == null ? void 0 : _g.utils) == null ? void 0 : _h.translationOriginal;
  const isPhoneVariant = variant === "phone";
  const { holderOptions, holderOptionsRequestKey } = (0, import_SalesSdkHolderContext.useSalesSdkHolderOptional)();
  const { pet, dispatch: petDispatch, apis } = (0, import_useBookingEditPetState.useBookingEditPetState)(
    open,
    baseBookingState,
    engineRequest,
    holderOptions,
    holderOptionsRequestKey
  );
  const bookingState = (0, import_react.useMemo)(
    () => ({
      ...baseBookingState,
      action,
      apis,
      pet,
      service: {
        ...baseBookingState.service,
        cacheItem: cacheItemProp
      }
    }),
    [baseBookingState, cacheItemProp, action, apis, pet]
  );
  const cacheItem = cacheItemProp;
  const isNormalProduct = (0, import_react.useMemo)(() => {
    if (!cacheItem) return true;
    return (0, import_utils3.isNormalProductByDurationSchedule)(cacheItem);
  }, [cacheItem]);
  const isFormSubject = (0, import_react.useMemo)(
    () => {
      var _a2, _b2, _c2, _d2;
      return ((_d2 = (_c2 = (_b2 = (_a2 = bookingState == null ? void 0 : bookingState.bookingConfig) == null ? void 0 : _a2.config) == null ? void 0 : _b2.basic) == null ? void 0 : _c2.appointment_subject) == null ? void 0 : _d2.type) === "form";
    },
    [(_l = (_k = (_j = (_i = bookingState == null ? void 0 : bookingState.bookingConfig) == null ? void 0 : _i.config) == null ? void 0 : _j.basic) == null ? void 0 : _k.appointment_subject) == null ? void 0 : _l.type]
  );
  const getCurrentCacheItem = (0, import_ahooks.useMemoizedFn)((_cacheItem) => {
    const values = form.getFieldsValue();
    const item = _cacheItem || cacheItem;
    return (0, import_resolveCacheItemForResourceCheck.resolveCacheItemForResourceCheck)(item, values);
  });
  const durationProps = (0, import_react.useMemo)(() => {
    var _a2, _b2, _c2;
    return (0, import_utils5.getDurationProps)({
      cacheItem: getCurrentCacheItem(),
      useStartTime,
      slice: (_c2 = (_b2 = (_a2 = bookingState.bookingConfig) == null ? void 0 : _a2.config) == null ? void 0 : _b2.basic) == null ? void 0 : _c2.service_time
    });
  }, [
    cacheItem,
    useStartTime,
    useResource,
    (_o = (_n = (_m = bookingState.bookingConfig) == null ? void 0 : _m.config) == null ? void 0 : _n.basic) == null ? void 0 : _o.service_time
  ]);
  const flexibleOption = (0, import_react.useMemo)(() => {
    return (0, import_utils5.getFlexibleOption)({ durationProps });
  }, [durationProps, import_utils.locales.locale]);
  const timeObj = (0, import_react.useMemo)(() => {
    return (0, import_utils5.getTimeObj)({
      cacheItem: getCurrentCacheItem(),
      durationProps,
      useStartTime,
      currentResource: null,
      state: bookingState,
      useDuration
    });
  }, [
    durationProps,
    useStartTime,
    useDuration,
    (_r = (_q = (_p = bookingState.bookingConfig) == null ? void 0 : _p.config) == null ? void 0 : _q.basic) == null ? void 0 : _r.service_time,
    cacheItem
  ]);
  (0, import_react.useEffect)(() => {
    var _a2;
    try {
      if (((_a2 = useDuration == null ? void 0 : useDuration.indexOf) == null ? void 0 : _a2.call(useDuration, "flexible_")) === 0 && flexibleOption) {
        form.setFieldsValue({ duration: flexibleOption.value });
      }
    } catch {
    }
  }, [useDuration, flexibleOption, form]);
  const getDiscount = (0, import_ahooks.useMemoizedFn)(() => {
    var _a2;
    const oPrice = Number(((_a2 = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _a2.origin_total) || 0);
    const cPrice = Number(useTotal || 0);
    let discount = "";
    if (cPrice === oPrice) {
      discount = import_utils.locales.getText("pisell2.text.status.no-discount");
    } else {
      discount = `${import_utils.locales.getText("pisell2.text.status.manual")} `;
      if (cPrice < oPrice) {
        discount += (0, import_utils.formatAmount)(cPrice - oPrice, 2, bookingState.amountSymbol) + "";
      } else {
        discount += "+" + (0, import_utils.formatAmount)(cPrice - oPrice, 2, bookingState.amountSymbol);
      }
    }
    form.setFieldsValue({ discount });
  });
  const updateCacheItem = (0, import_ahooks.useMemoizedFn)((next) => {
    onCacheItemChange(next);
  });
  const hasBookingTimeForResources = (0, import_ahooks.useMemoizedFn)((item) => {
    var _a2;
    const current = item || getCurrentCacheItem();
    const ext = (current == null ? void 0 : current._extend) || {};
    if (ext.start_time || ext.end_time) return true;
    if ((_a2 = ext.other) == null ? void 0 : _a2.session) return true;
    if (ext.duration != null && ext.duration !== "") return true;
    if (ext.endDate || ext.end_date) return true;
    return false;
  });
  const resolveResourceMapsForErrors = (0, import_ahooks.useMemoizedFn)(() => {
    var _a2, _b2, _c2, _d2, _e2;
    const current = getCurrentCacheItem();
    const origin = ((_a2 = current == null ? void 0 : current._data) == null ? void 0 : _a2.resourcesOrigin) ?? ((_b2 = cacheItem == null ? void 0 : cacheItem._data) == null ? void 0 : _b2.resourcesOrigin);
    if (!Array.isArray(origin) || !origin.length) {
      return (_c2 = current == null ? void 0 : current._data) == null ? void 0 : _c2.resourceMaps;
    }
    try {
      const res = (0, import_utils5.formatResources)({
        cacheItem: current,
        resourcesOrigin: origin
      });
      return (res == null ? void 0 : res.maps) ?? ((_d2 = current == null ? void 0 : current._data) == null ? void 0 : _d2.resourceMaps);
    } catch (err) {
      console.warn("[SalesSdk] resolveResourceMapsForErrors formatResources 失败", err);
      return (_e2 = current == null ? void 0 : current._data) == null ? void 0 : _e2.resourceMaps;
    }
  });
  const getResources = (0, import_ahooks.useMemoizedFn)((overrideItem) => {
    var _a2, _b2;
    const baseItem = overrideItem || cacheItem;
    if (!((_b2 = (_a2 = baseItem == null ? void 0 : baseItem._data) == null ? void 0 : _a2.resourcesOrigin) == null ? void 0 : _b2.length) || isRefreshingResourcesRef.current) {
      return;
    }
    isRefreshingResourcesRef.current = true;
    try {
      const current = overrideItem ? (0, import_resolveCacheItemForResourceCheck.resolveCacheItemForResourceCheck)(overrideItem, form.getFieldsValue()) : getCurrentCacheItem();
      const res = (0, import_utils5.formatResources)({
        cacheItem: current,
        resourcesOrigin: baseItem._data.resourcesOrigin
      });
      const next = {
        ...baseItem,
        _data: {
          ...baseItem._data,
          resources: (0, import_normalizeResourceDisplay.normalizeResourceDisplayList)(res == null ? void 0 : res.list),
          resourceMaps: (0, import_normalizeResourceDisplay.normalizeResourceDisplayMaps)(res == null ? void 0 : res.maps)
        }
      };
      updateCacheItem(next);
      updateResourceErrors();
    } finally {
      queueMicrotask(() => {
        isRefreshingResourcesRef.current = false;
      });
    }
  });
  const updateResourceErrors = (0, import_ahooks.useMemoizedFn)(() => {
    const { resource: resource2 } = form.getFieldsValue();
    if (!resource2) return;
    const maps = resolveResourceMapsForErrors();
    const cacheForErrors = getCurrentCacheItem();
    const nextResource = { ...resource2 };
    let changed = false;
    for (const formId in nextResource) {
      nextResource[formId] = nextResource[formId].map((d) => {
        var _a2, _b2;
        const resourceRow = (_b2 = (_a2 = maps == null ? void 0 : maps[formId]) == null ? void 0 : _a2.renderListMaps) == null ? void 0 : _b2[d == null ? void 0 : d.relation_id];
        const errors = (0, import_utilsByBooking.getErrorList)(resourceRow, cacheForErrors);
        const prevErrors = d == null ? void 0 : d.errors;
        if ((prevErrors == null ? void 0 : prevErrors.length) !== (errors == null ? void 0 : errors.length) || (prevErrors == null ? void 0 : prevErrors.some((item, index) => {
          var _a3;
          return (item == null ? void 0 : item.type) !== ((_a3 = errors == null ? void 0 : errors[index]) == null ? void 0 : _a3.type);
        }))) {
          changed = true;
        }
        return { ...d, errors };
      });
    }
    if (changed) {
      form.setFieldsValue({ resource: nextResource });
    }
  });
  const resourceSelectionKey = (0, import_react.useMemo)(() => {
    if (!useResource || typeof useResource !== "object") return "";
    return Object.keys(useResource).sort().map((formId) => {
      const rows = useResource[formId];
      if (!Array.isArray(rows)) return `${formId}:`;
      return `${formId}:${rows.map((r) => r == null ? void 0 : r.relation_id).join(",")}`;
    }).join("|");
  }, [useResource]);
  (0, import_ahooks.useUpdateEffect)(() => {
    if (!open || !cacheItem || bookingState.renderType === "eventBooking") return;
    if (!hasBookingTimeForResources()) return;
    getResources();
  }, [
    useStartTime,
    useDuration,
    useEndDate,
    bookingState.renderType,
    bookingState.service.resourcesOrigin
  ]);
  (0, import_ahooks.useUpdateEffect)(() => {
    var _a2;
    if (!open || !((_a2 = cacheItem == null ? void 0 : cacheItem._data) == null ? void 0 : _a2.resourceMaps) || !resourceSelectionKey) return;
    updateResourceErrors();
  }, [resourceSelectionKey]);
  (0, import_react.useEffect)(() => {
    getDiscount();
  }, [useTotal, (_s = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _s.origin_total, getDiscount]);
  const bundles = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    return ((_b2 = (_a2 = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _a2.other) == null ? void 0 : _b2.bundle) || [];
  }, [(_u = (_t = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _t.other) == null ? void 0 : _u.bundle]);
  const { run: setEditDataRun } = (0, import_ahooks.useDebounceFn)(
    (item) => setEditData(item),
    { wait: 50, leading: true, trailing: false }
  );
  const setEditData = (0, import_ahooks.useMemoizedFn)((item) => {
    var _a2, _b2, _c2;
    setCurrentTab("batch_edit");
    isChangeTotal.current = false;
    const target = item || cacheItem;
    if (!(target == null ? void 0 : target._extend)) return;
    const values = target._extend;
    form.resetFields();
    form.setFieldsValue({
      capacity: values.capacity,
      discount_reason: values.discount_reason,
      duration: values.duration,
      endDate: values.endDate,
      end_date: values.end_date,
      origin_total: values.origin_total,
      price: values.price,
      product_name: values.product_name,
      quantity: values.quantity,
      resource: values.resource,
      startDate: values.startDate,
      start_time: values.start_time,
      start_date: values.start_date,
      total: values.total,
      holder_id: values.holder_id,
      note: values.note
    });
    if ((_b2 = (_a2 = target == null ? void 0 : target._data) == null ? void 0 : _a2.resourcesOrigin) == null ? void 0 : _b2.length) {
      queueMicrotask(() => getResources());
    } else if ((_c2 = target == null ? void 0 : target._data) == null ? void 0 : _c2.resourceMaps) {
      updateResourceErrors();
    }
  });
  (0, import_react.useEffect)(() => {
    const justOpened = open && !prevDrawerOpenRef.current;
    prevDrawerOpenRef.current = open;
    if (justOpened && cacheItem) {
      setEditDataRun(cacheItem);
    }
  }, [open, cacheItem, setEditDataRun]);
  (0, import_react.useEffect)(() => {
    var _a2, _b2;
    const expandJustFinished = prevMultiDayExpandingRef.current && !multiDayExpanding;
    prevMultiDayExpandingRef.current = multiDayExpanding;
    if (!open || !expandJustFinished || !((_b2 = (_a2 = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _a2.items) == null ? void 0 : _b2.length)) {
      return;
    }
    setEditDataRun(cacheItem);
  }, [open, multiDayExpanding, cacheItem, setEditDataRun]);
  const isReason = (0, import_react.useMemo)(() => {
    var _a2;
    const oPrice = Number(((_a2 = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _a2.origin_total) || 0);
    const cPrice = Number(useTotal || 0);
    return cPrice !== oPrice;
  }, [useTotal, (_v = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _v.origin_total]);
  const onFinish = (0, import_ahooks.useMemoizedFn)((values) => {
    var _a2, _b2, _c2, _d2, _e2, _f2;
    if (multiDayExpanding) {
      return;
    }
    const isSuccess = (_b2 = (_a2 = resourcesRef.current) == null ? void 0 : _a2.check) == null ? void 0 : _b2.call(_a2);
    if (isShowTimeAndResource && !isSuccess) {
      return;
    }
    if (submitLock) return;
    submitLock = true;
    setTimeout(() => {
      submitLock = false;
    }, 1500);
    const currentCacheItemForSubmit = getCurrentCacheItem();
    const cacheItemForSubmit = isEditGroup ? currentCacheItemForSubmit : syncNormalBookingTimeFields(currentCacheItemForSubmit);
    const holderOptionsForSubmit = (0, import_formatHolderOptions2.formatHolderOptions)(((_c2 = bookingState.pet) == null ? void 0 : _c2.holders) || []);
    const edited = (0, import_buildEditedCacheItem.buildEditedCacheItem)({
      values,
      cacheItem: cacheItemForSubmit,
      isEditGroup: !!items.length,
      isChangeTotal: isChangeTotal.current,
      isPriceIncludeTax: getData == null ? void 0 : getData("is_price_include_tax"),
      bookingConfig: bookingState.bookingConfig,
      customerId: (_e2 = (_d2 = bookingState.client) == null ? void 0 : _d2.value) == null ? void 0 : _e2.id,
      isFranchisee: bookingState.isFranchisee,
      holderOptions: holderOptionsForSubmit
    });
    edited._holderOptionsSnapshot = holderOptionsForSubmit;
    const holderIds = (0, import_formatHolderOptions.normalizeHolderIds)(values.holder_id);
    if (holderIds.length) {
      (0, import_holderOptionsSyncBridge.syncHolderOptionsByIds)(holderIds, (_f2 = bookingState.pet) == null ? void 0 : _f2.holders);
      (0, import_holderOptionsSyncBridge.reloadGlobalHolderOptions)();
    }
    form.resetFields();
    onConfirm(edited);
  });
  const isShowTimeAndResource = (0, import_react.useMemo)(() => {
    if (bookingState.renderType !== "eventBooking" && !isNormalProduct) {
      return true;
    }
    return false;
  }, [bookingState.renderType, isNormalProduct]);
  const SelectTime = (_w = window.BaseMaterials) == null ? void 0 : _w.SelectTime;
  const items = (0, import_react.useMemo)(() => {
    var _a2, _b2;
    return ((_b2 = (_a2 = getCurrentCacheItem()) == null ? void 0 : _a2._extend) == null ? void 0 : _b2.items) || [];
  }, [getCurrentCacheItem, cacheItem, useTotal]);
  const isEditGroup = (0, import_react.useMemo)(() => !!items.length, [items]);
  const updateMultiDay = (0, import_ahooks.useMemoizedFn)(async ({ start_date, end_date, duration }) => {
    var _a2, _b2;
    const current = getCurrentCacheItem();
    let draft = {
      ...current,
      _extend: {
        ...current._extend,
        start_date,
        end_date,
        startDate: start_date,
        endDate: end_date,
        ...duration !== void 0 ? { duration } : {}
      }
    };
    let nextItem = draft;
    if (!(0, import_multiDayPriceCache.hasMatchingMultiDayQuotationOnCacheItem)(draft)) {
      const quotation = await (0, import_resolveMultiDayQuotation.resolveMultiDayQuotation)({
        cacheItem: draft,
        bookingState,
        customerId: (_b2 = (_a2 = bookingState.client) == null ? void 0 : _a2.value) == null ? void 0 : _b2.id
      });
      nextItem = (0, import_resolveMultiDayQuotation.applyMultiDayQuotationToCacheItem)(draft, quotation);
    }
    if (duration !== void 0) {
      nextItem._extend.duration = duration;
    }
    nextItem._extend.items = (0, import_utils6.createBookingItemsByGroup)(nextItem);
    nextItem._extend = {
      ...nextItem._extend,
      ...(0, import_utils6.getGroupTotalPrice)(nextItem._extend.items)
    };
    updateCacheItem(nextItem);
    form.setFieldsValue({ total: nextItem._extend.total });
  });
  const onValuesChange = (0, import_ahooks.useMemoizedFn)((changedValues) => {
    var _a2, _b2;
    if (!isEditGroup) {
      const shouldSyncNormalTime = hasChangedField(changedValues, "duration") || hasChangedField(changedValues, "start_time") || hasChangedField(changedValues, "start_date");
      if (!shouldSyncNormalTime) return;
      const nextItem = syncNormalBookingTimeFields(getCurrentCacheItem());
      updateCacheItem(nextItem);
      form.setFieldsValue({
        end_date: (_a2 = nextItem._extend) == null ? void 0 : _a2.endDate,
        end_time: (_b2 = nextItem._extend) == null ? void 0 : _b2.end_time
      });
      return;
    }
    if (changedValues == null ? void 0 : changedValues.duration) {
      const end_date = (0, import_dayjs.default)(useStartDate).add(changedValues.duration, "day");
      form.setFieldsValue({ end_date });
      return updateMultiDay({
        start_date: useStartDate,
        end_date,
        duration: changedValues.duration
      });
    }
    if (changedValues == null ? void 0 : changedValues.start_date) {
      const startDate = (0, import_dayjs.default)(changedValues.start_date);
      const endDate = (0, import_dayjs.default)(useEndDate);
      if (startDate.isAfter(endDate)) {
        form.setFieldsValue({ duration: void 0, end_date: void 0 });
        return;
      }
    }
    if ((changedValues == null ? void 0 : changedValues.start_date) || (changedValues == null ? void 0 : changedValues.end_date)) {
      const current = getCurrentCacheItem();
      const duration = (0, import_utils4.getDays)(current, "days");
      const start_date = (changedValues == null ? void 0 : changedValues.start_date) || useStartDate;
      const end_date = (changedValues == null ? void 0 : changedValues.end_date) || useEndDate;
      updateMultiDay({ start_date, end_date, duration });
      form.setFieldsValue({ duration });
    }
  });
  (0, import_react.useEffect)(() => {
    if (isShowTimeAndResource) {
      setVal(true);
      return;
    }
    setVal(false);
  }, [isShowTimeAndResource]);
  const handleTotalChange = () => {
    isChangeTotal.current = true;
  };
  const handleNoteConfirm = (noteValue) => {
    form.setFieldsValue({ note: noteValue });
    setNoteModalOpen(false);
  };
  const { canEditProduct, handleEditProduct, editingProduct } = (0, import_useBookingEditProduct.useBookingEditProduct)({
    cacheItem,
    bookingState,
    form,
    onCacheItemChange: updateCacheItem,
    onAfterProductEdit: getResources,
    resetManualPriceChange: () => {
      isChangeTotal.current = false;
    }
  });
  const drawerOpen = open && !(cacheItem == null ? void 0 : cacheItem.autoClose);
  (0, import_react.useEffect)(() => {
    let timer = null;
    if (drawerOpen) {
      timer = setTimeout(() => setMaskClosable(true), 200);
    } else {
      setMaskClosable(false);
    }
    return () => {
      if (timer) clearTimeout(timer);
    };
  }, [drawerOpen]);
  const productName = (0, import_react.useMemo)(
    () => {
      var _a2;
      return /* @__PURE__ */ import_react.default.createElement(import_antd.Col, { span: 24 }, /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { name: "product_name" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "current-service-info" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "current-service-info-name-wrap" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "current-service-info-name" }, ((_a2 = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _a2.product_name) || "-"), canEditProduct && /* @__PURE__ */ import_react.default.createElement(
        import_antd.Button,
        {
          loading: editingProduct,
          disabled: bookingState.channelDisabledEdit,
          onClick: handleEditProduct
        },
        import_utils.locales.getText("pisell2.text.edit")
      )), /* @__PURE__ */ import_react.default.createElement(
        import_collapsibleList.default,
        {
          style: { marginTop: bundles.length ? "8px" : 0 },
          list: bundles,
          renderItem: (item) => {
            let title = item.title || item.bundle_title;
            const formattedItem = {
              ...item,
              title: typeof title === "string" ? title : translationOriginal == null ? void 0 : translationOriginal(title),
              option: (item.option || []).map((option) => {
                return {
                  ...option,
                  name: typeof option.name === "string" ? option.name : translationOriginal == null ? void 0 : translationOriginal(option.name)
                };
              })
            };
            return (0, import_utils2.renderBundles)(formattedItem, bookingState.amountSymbol);
          }
        }
      ))));
    },
    [
      bundles,
      bookingState.amountSymbol,
      bookingState.channelDisabledEdit,
      (_x = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _x.product_name,
      canEditProduct,
      editingProduct,
      handleEditProduct,
      translationOriginal
    ]
  );
  const price = /* @__PURE__ */ import_react.default.createElement(import_antd.Col, { span: 24 }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Form.Item,
    {
      label: import_utils.locales.getText("pisell2.text.price"),
      name: "total",
      rules: [{ required: true }],
      extra: useTotal !== ((_y = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _y.origin_total) && import_utils.locales.getText("page.booking.text.price-extra")(
        (0, import_utils.formatAmount)((_z = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _z.origin_total, 2, bookingState.amountSymbol),
        (0, import_utils.formatAmount)(useTotal, 2, bookingState.amountSymbol)
      )
    },
    /* @__PURE__ */ import_react.default.createElement(
      import_priceKeyboard.DiscountKeyboard.InputNumber,
      {
        style: { width: "100%" },
        min: 0,
        precision: 2,
        prefix: bookingState.amountSymbol,
        onChange: handleTotalChange,
        disabled: bookingState.channelDisabledEdit,
        originalValue: ((_A = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _A.origin_total) || 0,
        placeholder: ((_B = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _B.origin_total) || "0",
        size: "large",
        keyboardProps: {
          containerProps: { renderType: "modal" },
          selectType: "dark"
        }
      }
    )
  ));
  const reason = isReason ? /* @__PURE__ */ import_react.default.createElement(import_antd.Col, { span: 24 }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Form.Item,
    {
      label: import_utils.locales.getText("pisell2.text.discount-reason"),
      name: "discount_reason"
    },
    /* @__PURE__ */ import_react.default.createElement(import_antd.Input.TextArea, { size: "large" })
  )) : null;
  const DateCom = (position) => /* @__PURE__ */ import_react.default.createElement(
    import_antd.DatePicker,
    {
      className: "pisell-lowcode__booking-service-select-date",
      disabledDate: (current) => (0, import_utils3.disabledDate)(current, position, bookingState.date.value),
      size: "large",
      style: { width: "100%" },
      format: bookingState.locale === "en" ? "DD/MM/YYYY" : "YYYY-MM-DD"
    }
  );
  const startTime = /* @__PURE__ */ import_react.default.createElement(import_antd.Col, { span: 12 }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Form.Item,
    {
      label: import_utils.locales.getText(
        isEditGroup ? "pisell2.text.start_date" : "pisell2.text.start_time"
      ),
      name: isEditGroup ? "start_date" : "start_time",
      rules: [{ required: true }]
    },
    isEditGroup ? DateCom("start") : SelectTime ? /* @__PURE__ */ import_react.default.createElement(
      SelectTime,
      {
        slice: (_F = (_E = (_D = (_C = bookingState.bookingConfig) == null ? void 0 : _C.config) == null ? void 0 : _D.basic) == null ? void 0 : _E.service_time) == null ? void 0 : _F.value,
        timePickerProps: { style: { width: "100%" } },
        timeProps: { style: { zoom: 0.8 } }
      }
    ) : null
  ));
  const endTime = isEditGroup ? /* @__PURE__ */ import_react.default.createElement(import_antd.Col, { span: 12 }, /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { label: import_utils.locales.getText("pisell2.text.end_date"), name: "end_date" }, DateCom("end"))) : null;
  const durationField = /* @__PURE__ */ import_react.default.createElement(import_antd.Col, { span: isEditGroup ? 24 : 12 }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Form.Item,
    {
      label: import_utils.locales.getText("pisell2.text.duration"),
      name: "duration",
      rules: [{ required: true }]
    },
    /* @__PURE__ */ import_react.default.createElement(import_duration.default, { ...durationProps, timeObj })
  ));
  const resource = /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { noStyle: true, name: "resource" }, /* @__PURE__ */ import_react.default.createElement(
    import_Resources.default,
    {
      ref: resourcesRef,
      state: bookingState,
      cacheItem,
      getCurrentCacheItem,
      config: {
        autoAllocation: true,
        /** 使用 label 列展示不可用三角标（normalizeResourceDisplay / Info2 formatResources） */
        resourceErrorIcon: true,
        disabled: bookingState.channelDisabledEdit ?? false
      }
    }
  ));
  const holder = /* @__PURE__ */ import_react.default.createElement(
    import_antd.Form.Item,
    {
      name: "holder_id",
      style: { width: "100%" },
      rules: [
        {
          required: ((_I = (_H = (_G = bookingState == null ? void 0 : bookingState.bookingConfig) == null ? void 0 : _G.config) == null ? void 0 : _H.basic) == null ? void 0 : _I.subject_require) === "require",
          validator: (_rule, value, callback) => {
            var _a2, _b2, _c2, _d2;
            const showExtra = ((_c2 = (_b2 = (_a2 = bookingState == null ? void 0 : bookingState.bookingConfig) == null ? void 0 : _a2.config) == null ? void 0 : _b2.basic) == null ? void 0 : _c2.subject_require) === "require" && (!value || (value == null ? void 0 : value.length) < (((_d2 = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _d2.quantity) || 1));
            if (showExtra) {
              callback(import_utils.locales.getText("page.booking.text.holder.length-error"));
            } else {
              callback();
            }
          }
        }
      ]
    },
    /* @__PURE__ */ import_react.default.createElement(import_Holder.default, { state: bookingState, cacheItem, dispatch: petDispatch })
  );
  const capacity = /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { noStyle: true, name: "capacity" }, /* @__PURE__ */ import_react.default.createElement(import_Capacity.default, { state: bookingState, cacheItem }));
  const quantity = /* @__PURE__ */ import_react.default.createElement(import_antd.Col, { span: 24 }, /* @__PURE__ */ import_react.default.createElement(
    import_antd.Form.Item,
    {
      label: import_utils.locales.getText("pisell2.text.quantity"),
      name: "quantity",
      rules: [{ required: true }]
    },
    /* @__PURE__ */ import_react.default.createElement(
      import_antd.InputNumber,
      {
        size: "large",
        style: { width: "100%" },
        min: 1,
        max: 999999,
        formatter: (value) => value !== void 0 ? Math.floor(value) : value
      }
    )
  ));
  const groupDom = /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, !!isEditGroup && /* @__PURE__ */ import_react.default.createElement(import_EditTabs.default, { value: currentTab, onChange: setCurrentTab }), /* @__PURE__ */ import_react.default.createElement("div", { style: { display: currentTab === "booking_list" ? "block" : "none" } }, /* @__PURE__ */ import_react.default.createElement(import_SalesSdkBookingList.SalesSdkBookingList, { items, bookingState })));
  const footer = /* @__PURE__ */ import_react.default.createElement(
    "div",
    {
      className: "pisell-lowcode__booking-service-body-edit-footer",
      style: (bookingState == null ? void 0 : bookingState.isBookingTicket2) ? { justifyContent: "space-between" } : void 0
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-service-body-edit-footer-left" }, showNoteButton && (bookingState == null ? void 0 : bookingState.isBookingTicket2) && /* @__PURE__ */ import_react.default.createElement(
      import_materials.ConfigProvider,
      {
        theme: {
          token: { colorPrimary: "#0d7fa9" }
        }
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Button,
        {
          className: "pisell-lowcode__booking-service-buttons-item note-button",
          type: "primary",
          size: "large",
          onClick: () => setNoteModalOpen(true),
          style: { height: "48px", width: "140px" }
        },
        import_utils.locales.getText("pisell2.ticket-booking.note"),
        useNote && /* @__PURE__ */ import_react.default.createElement("span", { className: "note-indicator" }, /* @__PURE__ */ import_react.default.createElement(import_materials.Iconfont, { type: "pisell2-info-circle2" }))
      )
    )),
    /* @__PURE__ */ import_react.default.createElement(
      import_antd.Button,
      {
        type: "primary",
        className: "pisell-lowcode__booking-service-body-edit-footer-apple",
        disabled: multiDayExpanding || !isNormalProduct && !((_J = bookingState.service.resourcesOrigin) == null ? void 0 : _J.length),
        loading: multiDayExpanding,
        onClick: () => form.submit()
      },
      import_utils.locales.getText("pisell2.text.apply")
    )
  );
  return /* @__PURE__ */ import_react.default.createElement(
    import_compensatedPisellContainer.default,
    {
      renderType: "drawer",
      props: {
        maskClosable,
        title: false,
        closable: false,
        forceRender: true,
        mask: bookingState.drawerMask,
        open: drawerOpen,
        placement: isPhoneVariant ? "bottom" : "right",
        width: isPhoneVariant ? "100%" : "600px",
        height: isPhoneVariant ? "95vh" : void 0,
        rootClassName: "booking-server-wrap",
        className: (0, import_classnames.default)(
          "pisell-lowcode__booking-drawer",
          "pisell-lowcode__booking-drawer-hide-scrollbar"
        ),
        push: false,
        bodyStyle: { padding: 0 },
        onClose: onCancel
      }
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-drawer-title-wrap" }, /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        className: "pisell-lowcode__booking-drawer-title-line",
        onClick: onCancel
      },
      /* @__PURE__ */ import_react.default.createElement("span", { className: "pisell-lowcode__booking-drawer-back" }, /* @__PURE__ */ import_react.default.createElement(import_ArrowLeft.default, null)),
      /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-drawer-title pisell-lowcode__booking-drawer-title-no-wrap" }, import_utils.locales.getText("pisell2.text.edit-service"))
    )),
    /* @__PURE__ */ import_react.default.createElement("div", { className: "pisell-lowcode__booking-service-body-edit" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Spin, { spinning: multiDayExpanding }, groupDom, /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form,
      {
        layout: "vertical",
        form,
        onFinish,
        onValuesChange,
        style: { display: currentTab === "batch_edit" ? "block" : "none" }
      },
      /* @__PURE__ */ import_react.default.createElement(import_antd.Row, { style: { width: "100%" }, gutter: [16, 0] }, productName, price, reason, val && isShowTimeAndResource && /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, startTime, endTime, durationField, resource, capacity, /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { hidden: true, name: "quantity" }, /* @__PURE__ */ import_react.default.createElement(import_antd.InputNumber, null))), isNormalProduct && quantity, !(0, import_utils3.isNormalProductByDurationSchedule)(cacheItem) && !(0, import_utils4.isWalkIn)((_L = (_K = bookingState.client) == null ? void 0 : _K.value) == null ? void 0 : _L.id) && isFormSubject && holder),
      /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { noStyle: true, name: "note" }, noteModalOpen && /* @__PURE__ */ import_react.default.createElement(
        import_noteModal.default,
        {
          open: noteModalOpen,
          value: form.getFieldValue("note"),
          onConfirm: handleNoteConfirm,
          onDelete: () => {
            form.setFieldsValue({ note: "" });
            setNoteModalOpen(false);
          },
          onCancel: () => setNoteModalOpen(false)
        }
      ))
    )), footer)
  );
};
BookingEditServiceDrawerInner.displayName = "BookingEditServiceDrawer";
var BookingEditServiceDrawer = (0, import_responsive.withResponsive)(BookingEditServiceDrawerInner);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  BookingEditServiceDrawer
});
