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/utilsByBooking.ts
var utilsByBooking_exports = {};
__export(utilsByBooking_exports, {
  formatResource: () => formatResource,
  formatTimes: () => formatTimes,
  getAppointmentTimingPreference: () => getAppointmentTimingPreference,
  getErrorList: () => getErrorList,
  getResourceTimeIsUsable: () => getResourceTimeIsUsable,
  getServiceStartTimeAndEndTime: () => getServiceStartTimeAndEndTime,
  getSumCapacity: () => getSumCapacity
});
module.exports = __toCommonJS(utilsByBooking_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_utils = require("@pisell/utils");
var import_utils2 = require("../utils");
var getUseableEventCount = (eventList, current) => {
  return (eventList || []).reduce((pre, event) => {
    return pre - event.pax;
  }, current || 0);
};
var isConflict = (event, current) => {
  const eventStart = (0, import_dayjs.default)(event.start_at);
  const eventEnd = (0, import_dayjs.default)(event.end_at);
  const currentStart = (0, import_dayjs.default)(current.start_at);
  const _isBefore = currentStart.isBefore(eventEnd);
  let _isAfter = true;
  if (current.end_at) {
    const currentEnd = (0, import_dayjs.default)(current.end_at);
    _isAfter = currentEnd.isAfter(eventStart);
  }
  return _isBefore && _isAfter;
};
var getResourceTimeIsUsable = (item, cacheItem, resourceItem) => {
  const startDate = (0, import_dayjs.default)((0, import_dayjs.default)(cacheItem._extend.start_date).format("YYYY-MM-DD") + " " + (0, import_utils2.getServeStartTime)(cacheItem._extend.start_time));
  const isFlexible = import_utils2.flexibleObj.isFlexible(cacheItem._extend.duration);
  let isMaxLimitRange = false;
  let isDateRange = false;
  let isCountRange = false;
  let time = { ...item };
  let timeStartDate = (0, import_dayjs.default)(time.start_date + " " + time.start_time).subtract(1, "second");
  let timeEndDate = (0, import_dayjs.default)(time.end_date + " " + time.end_time).add(1, "second");
  let totalCount = getUseableEventCount(time.event_list, resourceItem.capacity);
  const currentCount = getSumCapacity({ cacheItem });
  let eventList = time.event_list || [];
  if (cacheItem == null ? void 0 : cacheItem.booking_id) {
    eventList = eventList.filter((event) => event.id !== (cacheItem == null ? void 0 : cacheItem.booking_id));
  }
  let endDate = null;
  let isCalcCount = true;
  if (isFlexible) {
    isDateRange = startDate.isAfter(timeStartDate) && startDate.isBefore(timeEndDate);
    if (!isDateRange && eventList.length) {
      isCalcCount = false;
      isDateRange = true;
      isCountRange = false;
    }
  } else {
    endDate = startDate.add(import_utils2.flexibleObj.getValue(cacheItem._extend.duration), "minute");
    const isTimeRange = startDate.isAfter(timeStartDate) && endDate.isBefore(timeEndDate);
    if (isTimeRange) {
      isDateRange = true;
    }
  }
  if (isCalcCount) {
    let conflict = (eventList || []).filter((d) => {
      return isConflict({ start_at: d.start_at, end_at: d.end_at }, { start_at: startDate, end_at: endDate });
    });
    if (resourceItem.resourceType === "single") {
      if (conflict.length === 0) {
        isCountRange = true;
      } else {
        isCountRange = false;
      }
    } else {
      let conflictCount = getUseableEventCount(conflict, resourceItem.capacity);
      if (currentCount <= conflictCount) {
        isCountRange = true;
      } else {
        isCountRange = false;
      }
    }
  }
  const isUsable = isDateRange && isCountRange;
  time._extend = {
    isMaxLimitRange,
    isDateRange,
    isCountRange,
    isUsable
  };
  return time;
};
var getSumCapacity = ({ cacheItem }, isCalcQuantity = true) => {
  var _a;
  let sum = 0;
  for (let item of cacheItem._extend.capacity || []) {
    sum += item.value;
  }
  return sum * (isCalcQuantity ? ((_a = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _a.quantity) || 1 : 1);
};
var formatTimes = (resourceItem, cacheItem) => {
  let usableTimes = [];
  let _resourceItem = { ...resourceItem };
  let sum = getSumCapacity({ cacheItem });
  if (_resourceItem.capacity >= sum) {
    _resourceItem.times = _resourceItem.times.map((time) => {
      let _time2 = getResourceTimeIsUsable(time, cacheItem, _resourceItem);
      if (_time2 == null ? void 0 : _time2._extend.isDateRange) {
        usableTimes.push(_time2);
      }
      return _time2;
    });
  }
  let _time = (usableTimes || []).sort((a, b) => {
    const aEndDate = (0, import_dayjs.default)(a.end_date + " " + a.end_time).valueOf();
    const bEndDate = (0, import_dayjs.default)(b.end_date + " " + b.end_time).valueOf();
    return aEndDate - bEndDate;
  })[0];
  resourceItem._extend = {
    ...resourceItem._extend,
    usableTime: _time
  };
  return resourceItem;
};
var getErrorList = (resource, cacheItem) => {
  var _a, _b, _c, _d, _e, _f, _g;
  if (!(cacheItem == null ? void 0 : cacheItem.id)) {
    return [{
      label: import_utils.locales.getText("pisell2.text.no-product-added"),
      type: "products"
    }];
  }
  if (!resource) {
    return [];
  }
  let list = [];
  if (!resource.usable) {
    const { startDate, endDate } = (0, import_utils2.getServiceTimes)(cacheItem);
    const startText = startDate.format("hh:mm A");
    let endText = endDate.format("hh:mm A");
    if ((0, import_dayjs.default)(endDate).isAfter(startDate, "day")) {
      endText = import_utils.locales.getText("pisell1.text.tomorrow") + endText;
    }
    const isSingle = ((_c = (_b = (_a = cacheItem == null ? void 0 : cacheItem._data) == null ? void 0 : _a.resourceMaps) == null ? void 0 : _b[resource == null ? void 0 : resource.form_id]) == null ? void 0 : _c.type) === "single";
    if (!((_d = resource._extend) == null ? void 0 : _d.usableTime)) {
      list.push({
        label: import_utils.locales.getText("pisell1.text.resource-error-message-2")(resource.labelText, startText, endText),
        type: "time"
      });
    } else {
      if (!((_g = (_f = (_e = resource._extend) == null ? void 0 : _e.usableTime) == null ? void 0 : _f._extend) == null ? void 0 : _g.isCountRange)) {
        list.push({
          label: import_utils.locales.getText("pisell1.text.resource-error-message-3")(resource.labelText, startText, endText),
          type: "limit"
        });
      }
    }
  }
  if (resource.unbound) {
    list.push({
      label: import_utils.locales.getText("pisell1.text.resource-error-message-unbound"),
      type: "time"
    });
  }
  return list;
};
var formatResource = (resourceItem, cacheItem, formatLabel) => {
  var _a, _b;
  let _resourceItem = { ...resourceItem };
  _resourceItem = formatTimes(_resourceItem, cacheItem);
  _resourceItem.labelText = _resourceItem.main_field;
  const usable = (_b = (_a = _resourceItem._extend.usableTime) == null ? void 0 : _a._extend) == null ? void 0 : _b.isUsable;
  _resourceItem.usable = usable;
  if (formatLabel) {
    _resourceItem.label = formatLabel(_resourceItem);
  }
  return _resourceItem;
};
var getAppointmentTimingPreference = (state) => {
  var _a, _b, _c;
  return ((_c = (_b = (_a = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a.config) == null ? void 0 : _b.information_tab) == null ? void 0 : _c.appointment_timing_preference) || "sequential";
};
var getServiceStartTimeAndEndTime = (state, cacheItem, timeObj) => {
  var _a, _b, _c, _d;
  const appointmentTimingPreference = getAppointmentTimingPreference(state);
  let lastServer = (0, import_utils2.getLastServer)(state.service.value);
  let _extend = {
    // 时长: 当前商品时长 > 第一个时长
    duration: (0, import_utils2.findNextDuration)(
      cacheItem.duration,
      timeObj == null ? void 0 : timeObj.durationSlicesBasedOnTime,
      (_a = cacheItem == null ? void 0 : cacheItem.duration) == null ? void 0 : _a.value
    )
  };
  if (lastServer) {
    let lastServerStartDate = lastServer._extend.startDate;
    let lastServerEndDate = lastServer._extend.endDate;
    if (appointmentTimingPreference === "parallel") {
      _extend.start_time = lastServerStartDate.format("HH:mm");
    } else {
      if ((0, import_dayjs.default)(lastServerEndDate).isAfter(lastServerStartDate, "day")) {
        _extend.start_time = timeObj == null ? void 0 : timeObj.timeSlices[((_b = timeObj == null ? void 0 : timeObj.timeSlices) == null ? void 0 : _b.length) - 1].value;
      } else {
        _extend.start_time = lastServerEndDate.format("HH:mm");
      }
    }
  } else {
    let findNextSliceProps = {
      date: ""
    };
    const serviceParams = (0, import_utils2.getCacheParams)();
    if (serviceParams) {
      let str = serviceParams.start_date;
      if (str) {
        findNextSliceProps.date = (0, import_dayjs.default)(str).format("HH:mm");
      }
    }
    if (findNextSliceProps.date && findNextSliceProps.date !== "00:00") {
      _extend.start_time = findNextSliceProps.date;
    } else {
      if (cacheItem.currentDefaultTime) {
        _extend.start_time = cacheItem.currentDefaultTime;
      } else {
        _extend.start_time = (0, import_dayjs.default)().format("HH:mm");
      }
    }
  }
  _extend = {
    ..._extend,
    ...cacheItem._extend
  };
  const { startDate, endDate } = (0, import_utils2.getServiceTimes)({ _extend });
  _extend.startDate = startDate;
  _extend.endDate = endDate;
  const session = (_d = (_c = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _c.other) == null ? void 0 : _d.session;
  if ((0, import_utils2.isSessionProduct)(cacheItem) && session) {
    _extend.start_date = session.start_at;
    _extend.startDate = session.start_at;
    _extend.start_time = session.start_time;
    _extend.end_date = session.end_at;
    _extend.endDate = session.end_at;
    _extend.duration = (0, import_utils2.getDays)({ _extend }, "minutes");
  }
  return _extend;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  formatResource,
  formatTimes,
  getAppointmentTimingPreference,
  getErrorList,
  getResourceTimeIsUsable,
  getServiceStartTimeAndEndTime,
  getSumCapacity
});
