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/modules/BookingContext/utils/resources.ts
var resources_exports = {};
__export(resources_exports, {
  formatResource: () => formatResource,
  formatResources: () => formatResources,
  formatTimes: () => formatTimes,
  getResourceByIds: () => getResourceByIds,
  getResourceTimeIsUsable: () => getResourceTimeIsUsable,
  getSumCapacity: () => getSumCapacity,
  getUsableTime: () => getUsableTime,
  setDefaultCapacitys: () => setDefaultCapacitys,
  setDefaultResource: () => setDefaultResource
});
module.exports = __toCommonJS(resources_exports);
var import_dayjs = __toESM(require("dayjs"));
var import_lodash_es = require("lodash-es");
var import_flexible = require("./flexible");
var import_noResource = require("./noResource");
var import_serviceTimes = require("./serviceTimes");
function getUsableTime(cacheItem) {
  var _a, _b, _c;
  try {
    const resourceByForm = ((_a = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _a.resource) || {};
    const resourceMaps = ((_b = cacheItem == null ? void 0 : cacheItem._data) == null ? void 0 : _b.resourceMaps) || {};
    let items = [];
    for (const formId of Object.keys(resourceByForm)) {
      const selected = resourceByForm[formId];
      const maps = (_c = resourceMaps[formId]) == null ? void 0 : _c.renderListMaps;
      if (!Array.isArray(selected) || !maps)
        continue;
      items = items.concat(
        selected.map((d) => maps[d.relation_id]).filter(Boolean)
      );
    }
    if (!items.length)
      return null;
    return items.reduce((pre, event) => {
      var _a2, _b2, _c2, _d;
      const endAt = (0, import_dayjs.default)((_b2 = (_a2 = event._extend) == null ? void 0 : _a2.usableTime) == null ? void 0 : _b2.end_at);
      const preEnd = (0, import_dayjs.default)((_d = (_c2 = pre._extend) == null ? void 0 : _c2.usableTime) == null ? void 0 : _d.end_at);
      return endAt.isBefore(preEnd) ? event : pre;
    }, items[0]);
  } catch {
    return null;
  }
}
function getSumCapacity(cacheItem, isCalcQuantity = true) {
  var _a, _b;
  const list = ((_a = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _a.capacity) || [];
  let sum = 0;
  for (const item of list) {
    sum += Number((item == null ? void 0 : item.value) || 0);
  }
  return sum * (isCalcQuantity ? ((_b = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _b.quantity) || 1 : 1);
}
function getUseableEventCount(eventList, current) {
  return (eventList || []).reduce((pre, event) => pre - ((event == null ? void 0 : event.pax) || 0), current || 0);
}
function 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;
}
function getResourceTimeIsUsable(item, cacheItem, resourceItem) {
  const startDate = (0, import_dayjs.default)(
    `${(0, import_dayjs.default)(cacheItem._extend.start_date).format("YYYY-MM-DD")} ${(0, import_serviceTimes.getServeStartTime)(cacheItem._extend.start_time)}`
  );
  const isFlexible = import_flexible.flexibleObj.isFlexible(cacheItem._extend.duration);
  let isMaxLimitRange = false;
  let isDateRange = false;
  let isCountRange = false;
  const time = { ...item };
  const timeStartDate = (0, import_dayjs.default)(`${time.start_date} ${time.start_time}`).subtract(1, "second");
  const timeEndDate = (0, import_dayjs.default)(`${time.end_date} ${time.end_time}`).add(1, "second");
  const 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.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_flexible.flexibleObj.getValue(cacheItem._extend.duration), "minute");
    const isTimeRange = startDate.isAfter(timeStartDate) && endDate.isBefore(timeEndDate);
    if (isTimeRange)
      isDateRange = true;
  }
  if (isCalcCount) {
    const conflict = (eventList || []).filter(
      (d) => isConflict({ start_at: d.start_at, end_at: d.end_at }, { start_at: startDate, end_at: endDate })
    );
    if (resourceItem.resourceType === "single") {
      isCountRange = conflict.length === 0;
    } else {
      const conflictCount = getUseableEventCount(conflict, resourceItem.capacity);
      isCountRange = currentCount <= conflictCount;
    }
  }
  const isUsable = isDateRange && isCountRange;
  time._extend = {
    isMaxLimitRange,
    isDateRange,
    isCountRange,
    isUsable
  };
  return time;
}
function formatTimes(resourceItem, cacheItem) {
  const usableTimes = [];
  const _resourceItem = { ...resourceItem };
  const sum = getSumCapacity(cacheItem);
  if (_resourceItem.capacity >= sum) {
    _resourceItem.times = (_resourceItem.times || []).map((time) => {
      var _a;
      const _time2 = getResourceTimeIsUsable(time, cacheItem, _resourceItem);
      if ((_a = _time2 == null ? void 0 : _time2._extend) == null ? void 0 : _a.isDateRange)
        usableTimes.push(_time2);
      return _time2;
    });
  }
  const _time = usableTimes.sort((a, b) => {
    const aEnd = (0, import_dayjs.default)(`${a.end_date} ${a.end_time}`).valueOf();
    const bEnd = (0, import_dayjs.default)(`${b.end_date} ${b.end_time}`).valueOf();
    return aEnd - bEnd;
  })[0];
  resourceItem._extend = {
    ...resourceItem._extend,
    usableTime: _time
  };
  return resourceItem;
}
function formatResource(resourceItem, cacheItem) {
  var _a, _b, _c;
  let _resourceItem = { ...resourceItem };
  _resourceItem = formatTimes(_resourceItem, cacheItem);
  _resourceItem.labelText = _resourceItem.main_field;
  const usable = (_c = (_b = (_a = _resourceItem._extend) == null ? void 0 : _a.usableTime) == null ? void 0 : _b._extend) == null ? void 0 : _c.isUsable;
  _resourceItem.usable = usable;
  return _resourceItem;
}
function formatResources(params) {
  const { cacheItem, resourcesOrigin } = params;
  try {
    const maps = {};
    const list = resourcesOrigin.map((item) => {
      const _item = (0, import_lodash_es.cloneDeep)(item);
      const renderListMaps = {};
      _item.renderList = _item.renderList.map((d) => {
        const res = formatResource(d, cacheItem);
        const unbound = !item.optional_resource.includes(res.id) && !item.default_resource.includes(res.id) && res.id !== 0;
        if (unbound)
          res.unbound = true;
        renderListMaps[res.id] = res;
        return res;
      }).sort((a, b) => b.usable ? 1 : -1);
      maps[_item.form_id] = { ..._item, renderListMaps };
      return _item;
    });
    return { list, maps };
  } catch (err) {
    console.warn("[BookingContext] formatResources error", err);
    return { list: [], maps: {} };
  }
}
function getResourceMaxFreeTime(resource, isAutoAllocationOn) {
  const { renderList, form_id } = resource;
  if (!isAutoAllocationOn(form_id))
    return [];
  const usableList = (renderList || []).filter((d) => d.usable && d.id !== 0);
  let defaultResource = [];
  let maxFreeTime = 0;
  usableList.forEach((d) => {
    const { times = [] } = d;
    const currentMaxFreeTime = times.reduce((pre, cur) => {
      var _a, _b, _c;
      const start = ((_c = (_b = cur.event_list) == null ? void 0 : _b[((_a = cur.event_list) == null ? void 0 : _a.length) - 1]) == null ? void 0 : _c.end_at) || cur.start_at;
      const end = cur.end_at;
      const diff = (0, import_dayjs.default)(end).diff((0, import_dayjs.default)(start), "minute");
      return diff > pre ? diff : pre;
    }, 0);
    if (currentMaxFreeTime > maxFreeTime) {
      maxFreeTime = currentMaxFreeTime;
      defaultResource = [d];
    }
  });
  return defaultResource;
}
function setDefaultResource(params) {
  const { cacheItem, resources, resourceIdFromCalendar, isAutoAllocationOn = () => true } = params;
  const obj = {};
  const resourceId = Number(resourceIdFromCalendar) || 0;
  for (const item of resources) {
    const {
      select_type = {},
      optional_resource = [],
      default_resource = []
    } = item;
    const renderList = item.renderList.filter((d) => {
      if ((select_type == null ? void 0 : select_type.type) === "single") {
        if (resourceId && (optional_resource.includes(resourceId) || default_resource.includes(resourceId))) {
          return d.id === resourceId;
        }
        return d.is_default === 1;
      }
      return d.is_default === 1 || d.id === resourceId;
    });
    let defaultOriginalResource = [];
    if (renderList.length === 0) {
      defaultOriginalResource = getResourceMaxFreeTime(item, isAutoAllocationOn);
    } else {
      defaultOriginalResource = renderList;
    }
    obj[item.form_id] = defaultOriginalResource.map((d) => ({
      children: d.children,
      relation_type: d.relation_type,
      form_id: item.form_id,
      relation_id: d.id,
      like_status: "common",
      metadata: {
        form_name: item.title,
        resource_name: d.main_field
      }
    }));
  }
  return obj;
}
function setDefaultCapacitys(params) {
  var _a, _b;
  const { capacitys, cacheItem } = params;
  if ((capacitys == null ? void 0 : capacitys.type) === "package") {
    return (((_b = (_a = cacheItem == null ? void 0 : cacheItem._extend) == null ? void 0 : _a.other) == null ? void 0 : _b.bundle) || []).map((d) => {
      const id = d._bundle_product_id;
      const item = ((capacitys == null ? void 0 : capacitys.package) || []).find((p) => p.product_id === id);
      return {
        id,
        value: item ? d.quantity || 0 : 0,
        name: (item == null ? void 0 : item.name) || (d == null ? void 0 : d.title)
      };
    });
  }
  if ((capacitys == null ? void 0 : capacitys.type) === "custom") {
    return ((capacitys == null ? void 0 : capacitys.custom) || []).map((d) => ({
      id: d.id,
      value: d.min,
      name: d.name
    }));
  }
  return [{ id: 0, value: 1, name: "" }];
}
function getResourceByIds(resourcesOriginMap, cacheItem, extraParams) {
  var _a, _b;
  const _resources = [...((_a = cacheItem == null ? void 0 : cacheItem.product_resource) == null ? void 0 : _a.resources) || []].filter((d) => Number(d == null ? void 0 : d.status) === 1).map((item) => ({ ...item }));
  const {
    extraResources = [],
    resourcesOrigin = [],
    resourceTab = {}
  } = extraParams || {};
  for (const item of _resources) {
    const form_id = item.id;
    const isAllResource = ((_b = resourceTab == null ? void 0 : resourceTab[item.code]) == null ? void 0 : _b.resource_display_scope) === "all";
    let extraResourceIds = [];
    if (isAllResource) {
      extraResourceIds = (resourcesOrigin || []).filter((d) => d.form_code === item.code).map((d) => d.id);
    } else {
      extraResourceIds = extraResources.filter(
        (_extraItem) => _extraItem.form_id === form_id && !!_extraItem.id && !item.optional_resource.includes(_extraItem.id) && !item.default_resource.includes(_extraItem.id)
      ).map((_extraItem) => _extraItem.id);
    }
    extraResourceIds = Array.from(new Set(extraResourceIds));
    item.optional_resource = (item.optional_resource || []).filter(
      (d) => item.default_resource.indexOf(d) === -1
    );
    const getChildrenMetadata = (id) => {
      const combiningResources = [];
      const origin = resourcesOriginMap[id];
      if ((origin == null ? void 0 : origin.combined_resource) && origin.combined_resource.status === 1) {
        (origin.combined_resource.resource_ids || []).forEach((cid) => {
          var _a2, _b2;
          if (resourcesOriginMap[cid]) {
            combiningResources.push({
              ...resourcesOriginMap[cid],
              relation_id: ((_a2 = resourcesOriginMap[cid]) == null ? void 0 : _a2.relation_id) || ((_b2 = resourcesOriginMap[cid]) == null ? void 0 : _b2.id)
            });
          }
        });
      }
      return {
        children: combiningResources,
        metadata: {
          ...(origin == null ? void 0 : origin.metadata) || {},
          combined_resource: origin == null ? void 0 : origin.combined_resource
        }
      };
    };
    const optional_resource = Array.from(
      /* @__PURE__ */ new Set([...item.optional_resource, ...extraResourceIds])
    ).map((d) => {
      if (!resourcesOriginMap[d])
        return null;
      return Object.assign({}, resourcesOriginMap[d], {
        form_id,
        resourceType: item.type,
        ...getChildrenMetadata(d)
      });
    }).filter((d) => d).concat((0, import_noResource.getNoResource2)({ form_id }));
    const default_resource = (item.default_resource || []).map((d) => {
      const origin = resourcesOriginMap[d];
      if (origin) {
        origin.is_default = 1;
        return Object.assign({}, origin, {
          form_id,
          resourceType: item.type,
          ...getChildrenMetadata(d)
        });
      }
      return null;
    }).filter((d) => d);
    item.renderList = optional_resource.concat(default_resource);
    item.form_id = form_id;
  }
  return _resources;
}
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  formatResource,
  formatResources,
  formatTimes,
  getResourceByIds,
  getResourceTimeIsUsable,
  getSumCapacity,
  getUsableTime,
  setDefaultCapacitys,
  setDefaultResource
});
