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/utils.tsx
var utils_exports = {};
__export(utils_exports, {
  formatResources: () => formatResources,
  getDurationProps: () => getDurationProps,
  getFlexibleOption: () => getFlexibleOption,
  getProductExtend: () => getProductExtend,
  getResourceByIds: () => getResourceByIds,
  getTimeObj: () => getTimeObj,
  getTimeSlices: () => getTimeSlices,
  getUsableTime: () => getUsableTime,
  setDefaultCapacitys: () => setDefaultCapacitys,
  setDefaultResource: () => setDefaultResource,
  transServiceList: () => transServiceList
});
module.exports = __toCommonJS(utils_exports);
var import_react = __toESM(require("react"));
var import_utils = require("../../../utils");
var import_utilsByBooking = require("../../utilsByBooking");
var import_dayjs = __toESM(require("dayjs"));
var import_utils2 = require("@pisell/utils");
var import_AlertTriangle = __toESM(require("@pisell/icon/es/AlertTriangle"));
var import_utils3 = require("../editService/utils");
var import_mock = require("../../../mock");
var import_lodash = require("lodash");
var getUsableTime = (cacheItem) => {
  try {
    let items = [];
    for (let form_id in cacheItem._extend.resource) {
      items = items.concat(
        cacheItem._extend.resource[form_id].map((d) => {
          return cacheItem._data.resourceMaps[form_id].renderListMaps[d.relation_id];
        })
      );
    }
    const minEndAt = items.reduce((pre, event) => {
      var _a, _b, _c, _d;
      const endAt = (0, import_dayjs.default)((_b = (_a = event._extend) == null ? void 0 : _a.usableTime) == null ? void 0 : _b.end_at);
      return endAt.isBefore((_d = (_c = pre._extend) == null ? void 0 : _c.usableTime) == null ? void 0 : _d.end_at) ? event : pre;
    }, items[0]);
    return minEndAt;
  } catch (err) {
    return null;
  }
};
var getDurationProps = ({
  cacheItem,
  useStartTime,
  currentResource,
  slice
}) => {
  let _cacheItem = cacheItem;
  return {
    startDate: (0, import_dayjs.default)(
      (0, import_dayjs.default)(_cacheItem._extend.start_date).format("YYYY-MM-DD ") + ((0, import_utils.getServeStartTime)(useStartTime) || "00:00")
    ),
    usableTime: getUsableTime(cacheItem),
    duration: (0, import_utils.getDuration)(_cacheItem == null ? void 0 : _cacheItem.duration),
    locale: import_utils2.locales.locale,
    slice,
    selectProps: { size: "large" }
  };
};
var getFlexibleOption = ({
  cacheItem,
  useStartTime,
  currentResource,
  slice,
  durationProps
}) => {
  var _a, _b, _c, _d, _e, _f;
  const _durationProps = durationProps || getDurationProps({
    cacheItem,
    useStartTime,
    currentResource,
    slice
  });
  let _duration = _durationProps.duration;
  if (_duration === "flexible") {
    let endDate = (0, import_utils.getEndDate)(
      _durationProps.startDate,
      _duration,
      ((_c = (_b = (_a = _durationProps.usableTime) == null ? void 0 : _a._extend) == null ? void 0 : _b.usableTime) == null ? void 0 : _c.end_at) ? (0, import_dayjs.default)((_f = (_e = (_d = _durationProps.usableTime) == null ? void 0 : _d._extend) == null ? void 0 : _e.usableTime) == null ? void 0 : _f.end_at) : null
    );
    let timeValue = endDate.diff(_durationProps.startDate, "minute");
    return {
      label: import_utils2.locales.getText("pisell2.text.flexible"),
      value: import_utils.flexibleObj.create(timeValue)
    };
  }
  return null;
};
var getTimeSlices = ({ state }) => {
  var _a, _b, _c;
  let obj = (0, import_utils.sliceDayIntoFiveMinutes)(
    (_c = (_b = (_a = state.bookingConfig) == null ? void 0 : _a.config) == null ? void 0 : _b.basic) == null ? void 0 : _c.service_time,
    import_utils2.locales.locale
  );
  let timeSlices = [...obj.timeSlices];
  return {
    timeSlices
  };
};
var getTimeObj = ({
  cacheItem,
  useStartTime,
  currentResource,
  state,
  useDuration,
  durationProps
}) => {
  var _a, _b, _c;
  const flexibleOption = getFlexibleOption({
    cacheItem,
    useStartTime,
    currentResource,
    state,
    durationProps
  });
  let obj = (0, import_utils.sliceDayIntoFiveMinutes)(
    (_c = (_b = (_a = state.bookingConfig) == null ? void 0 : _a.config) == null ? void 0 : _b.basic) == null ? void 0 : _c.service_time,
    import_utils2.locales.locale
  );
  let timeSlices = [...obj.timeSlices];
  let durationSlicesBasedOnTime = [...obj.durationSlicesBasedOnTime];
  if (flexibleOption) {
    durationSlicesBasedOnTime.unshift(flexibleOption);
  }
  if (useDuration && !durationSlicesBasedOnTime.some((d) => d.value === useDuration)) {
    durationSlicesBasedOnTime.unshift({
      label: (0, import_utils.getDiscountTime)(useDuration),
      value: useDuration,
      //@ts-ignore
      disabled: true
    });
  }
  return {
    ...obj,
    timeSlices,
    durationSlicesBasedOnTime
  };
};
var formatResources = ({ cacheItem, resourcesOrigin, id }) => {
  try {
    let _list = [];
    let maps = {};
    const _cacheItem = cacheItem;
    _list = resourcesOrigin.map((item) => {
      let renderListMaps = {};
      let _item = (0, import_lodash.cloneDeep)(item);
      _item.renderList = _item.renderList.map((d) => {
        let res = (0, import_utilsByBooking.formatResource)(d, _cacheItem, (newData) => {
          let unbound = !item.optional_resource.includes(newData.id) && !item.default_resource.includes(newData.id) && newData.id !== 0;
          return /* @__PURE__ */ import_react.default.createElement("div", { className: "resource-option" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "like-wrap" }), /* @__PURE__ */ import_react.default.createElement("span", { className: "resource-option-label-text" }, newData.labelText), (!newData.usable || unbound) && /* @__PURE__ */ import_react.default.createElement(import_AlertTriangle.default, { className: "resource-option-alert-icon" }));
        });
        if (!item.optional_resource.includes(d.id) && !item.default_resource.includes(d.id) && d.id !== 0) {
          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: _list, maps };
  } catch (err) {
    console.log("formatResourcesErr", err);
  }
  return {
    list: [],
    maps: []
  };
};
var getResourceMaxFreeTime = (resource) => {
  const { renderList, form_id } = resource;
  if (!(0, import_utils3.getAutoAllocationStorage)(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;
};
var setDefaultResource = ({ cacheItem, resources }) => {
  let obj = {};
  const serviceParams = (0, import_utils.getCacheParams)();
  let resourceId = Number(serviceParams == null ? void 0 : serviceParams.resource_id);
  for (let item of resources) {
    const renderList = item.renderList.filter(
      (d) => d.is_default == 1 || d.id === resourceId
    );
    let defaultOriginalResource = [];
    if (renderList.length === 0) {
      defaultOriginalResource = getResourceMaxFreeTime(item);
    } else {
      defaultOriginalResource = renderList;
    }
    const defaultResource = defaultOriginalResource.map((d) => {
      return {
        ...d,
        relation_type: d.relation_type,
        form_id: item.form_id,
        relation_id: d.id,
        like_status: "common",
        // 新添加的数据补充错误信息
        errors: (0, import_utilsByBooking.getErrorList)(d, cacheItem),
        metadata: {
          form_name: item.title,
          resource_name: d.main_field
        }
      };
    });
    obj[item.form_id] = defaultResource;
  }
  return obj;
};
var setDefaultCapacitys = ({ capacitys, cacheItem }) => {
  var _a, _b;
  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(
        (item2) => item2.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) => {
      return {
        id: d.id,
        value: d.min,
        name: d.name
      };
    });
  }
  return [{ id: 0, value: 1, name: "" }];
};
var getResourceByIds = (resourcesOriginMap, cacheItem, extraParams) => {
  var _a, _b;
  let _resources = [...((_a = cacheItem == null ? void 0 : cacheItem.product_resource) == null ? void 0 : _a.resources) || []];
  const {
    extraResources = [],
    resourcesOrigin = [],
    resourceTab = {}
  } = extraParams || {};
  _resources = _resources.filter((d) => d.status == 1);
  for (let 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) => {
        return _extraItem.form_id === form_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 = (d) => {
      const combiningResources = [];
      if (resourcesOriginMap[d].combined_resource && resourcesOriginMap[d].combined_resource.status === 1) {
        resourcesOriginMap[d].combined_resource.resource_ids.forEach(
          (id) => {
            var _a2, _b2;
            if (resourcesOriginMap[id]) {
              combiningResources.push({
                ...resourcesOriginMap[id],
                relation_id: ((_a2 = resourcesOriginMap[id]) == null ? void 0 : _a2.relation_id) || ((_b2 = resourcesOriginMap[id]) == null ? void 0 : _b2.id)
              });
            }
          }
        );
      }
      return {
        children: combiningResources,
        metadata: {
          ...resourcesOriginMap[d].metadata,
          combined_resource: resourcesOriginMap[d].combined_resource
        }
      };
    };
    let 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_mock.getNoResource2)({ form_id }));
    let default_resource = item.default_resource.map((d) => {
      let item2 = resourcesOriginMap[d];
      if (item2) {
        item2.is_default = 1;
        return Object.assign({}, item2, {
          form_id,
          resourceType: item2.type,
          ...getChildrenMetadata(d)
        });
      } else {
        return null;
      }
    }).filter((d) => d);
    item.renderList = optional_resource.concat(default_resource);
    item.form_id = form_id;
  }
  console.log("_resources", _resources);
  return _resources;
};
var getIsAutoClose = (cacheItem) => {
  var _a, _b, _c, _d, _e;
  if (((_b = (_a = cacheItem._data) == null ? void 0 : _a.capacitys) == null ? void 0 : _b.type) !== "custom") {
    if (((_c = cacheItem == null ? void 0 : cacheItem._data) == null ? void 0 : _c.resources.length) === 1) {
      const first = (_d = cacheItem == null ? void 0 : cacheItem._data) == null ? void 0 : _d.resources[0];
      if (((_e = first.select_type) == null ? void 0 : _e.type) === "single") {
        if (first.default_resource.length > 0) {
          return true;
        }
      }
    }
  }
  return Object.entries(cacheItem._extend.resource).every(
    ([key, value]) => {
      return (0, import_utils3.getAutoAllocationStorage)(key) && (value == null ? void 0 : value.length);
    }
  );
};
var getProductExtend = ({ cacheItem, state, isDisabledTime }) => {
  var _a, _b, _c, _d;
  const isNew = cacheItem.new || !cacheItem._extend.endDate;
  let _cacheItem = { ...cacheItem };
  const resourcesOriginMap = state.service.resourcesOriginMap || {};
  _cacheItem._data = {};
  if (isNew) {
    _cacheItem._data.timeObj = getTimeObj({
      cacheItem,
      currentResource: null,
      state
    });
    _cacheItem._extend = (0, import_utilsByBooking.getServiceStartTimeAndEndTime)(
      state,
      cacheItem,
      _cacheItem._data.timeObj
    );
    _cacheItem._data.capacitys = cacheItem.capacity;
    _cacheItem._data.resourcesOrigin = getResourceByIds(
      resourcesOriginMap,
      cacheItem,
      {
        //  此数据用来控制 该商品所展示的资源是自身关联的,  还是全部的
        resourceTab: (_b = (_a = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _a.config) == null ? void 0 : _b.resource_tab,
        resourcesOrigin: state.service.resourcesOrigin
      }
    );
    _cacheItem._extend.capacity = setDefaultCapacitys({
      capacitys: _cacheItem._data.capacitys,
      cacheItem: _cacheItem
    });
    const { list, maps } = formatResources({
      cacheItem: _cacheItem,
      resourcesOrigin: _cacheItem._data.resourcesOrigin
    });
    _cacheItem._data.resources = list;
    _cacheItem._data.resourceMaps = maps;
    _cacheItem._extend.resource = setDefaultResource({
      cacheItem: _cacheItem,
      resources: _cacheItem._data.resources
    });
    if ((0, import_utils.getDuration)(_cacheItem == null ? void 0 : _cacheItem.duration)) {
      _cacheItem._data.timeObj = getTimeObj({
        cacheItem: _cacheItem,
        useStartTime: _cacheItem._extend.start_time,
        currentResource: _cacheItem._extend.resource,
        state
      });
      if ((0, import_utils.getDuration)(_cacheItem == null ? void 0 : _cacheItem.duration) === "flexible") {
        _cacheItem._extend.duration = _cacheItem._data.timeObj.durationSlicesBasedOnTime[0].value;
        const { startDate, endDate } = (0, import_utils.getServiceTimes)({
          _extend: _cacheItem._extend
        });
        _cacheItem._extend.endDate = endDate;
      }
    }
    _cacheItem.autoClose = getIsAutoClose(_cacheItem);
    if (_cacheItem._extend.bundle_edit !== void 0) {
      _cacheItem._extend.bundle_edit = 1;
    }
    if (!isDisabledTime) {
      _cacheItem._time = (/* @__PURE__ */ new Date()).getTime();
    }
  } else {
    if (!_cacheItem._data.capacitys) {
      _cacheItem._data.capacitys = cacheItem.capacity;
    }
    if (!_cacheItem._data.resourcesOrigin) {
      const extraResources = [];
      if (Array.isArray(_cacheItem._extend.event_resources)) {
        _cacheItem._extend.event_resources.forEach((_item) => {
          extraResources.push({
            form_id: _item.form_id,
            id: _item.relation_id
          });
        });
      }
      _cacheItem._data.resourcesOrigin = getResourceByIds(
        resourcesOriginMap,
        cacheItem,
        {
          extraResources,
          //  此数据用来控制 该商品所展示的资源是自身关联的,  还是全部的
          resourceTab: (_d = (_c = state == null ? void 0 : state.bookingConfig) == null ? void 0 : _c.config) == null ? void 0 : _d.resource_tab,
          resourcesOrigin: state.service.resourcesOrigin
        }
      );
    }
    if (!_cacheItem._data.resources) {
      const { list, maps } = formatResources({
        cacheItem: _cacheItem,
        resourcesOrigin: _cacheItem._data.resourcesOrigin
      });
      _cacheItem._data.resources = list;
      _cacheItem._data.resourceMaps = maps;
    }
    _cacheItem._data.timeObj = getTimeObj({
      cacheItem: _cacheItem,
      useStartTime: _cacheItem._extend.start_time,
      currentResource: _cacheItem._extend.resource,
      state
    });
  }
  console.log("_cacheItem_cacheItem", _cacheItem);
  return _cacheItem;
};
var transServiceList = (list) => {
  return list.map((item) => {
    var _a;
    return {
      ...item,
      product_resource: {
        ...item.product_resource,
        resources: (item == null ? void 0 : item.resource_relation) || ((_a = item == null ? void 0 : item.product_resource) == null ? void 0 : _a.resources)
      }
    };
  });
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  formatResources,
  getDurationProps,
  getFlexibleOption,
  getProductExtend,
  getResourceByIds,
  getTimeObj,
  getTimeSlices,
  getUsableTime,
  setDefaultCapacitys,
  setDefaultResource,
  transServiceList
});
