function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); }
function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); }
function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import dayjs from 'dayjs';
import { locales } from '@pisell/utils';
import { isDayBooking, formatDayDate } from "./info/service2/utils";
import { intersectionBy } from 'lodash';
import { getAppointmentTimingPreference } from "./info2/utilsByBooking";
var Request = /*#__PURE__*/function () {
  function Request() {
    _classCallCheck(this, Request);
    _defineProperty(this, "request", {});
  }
  _createClass(Request, [{
    key: "setRequest",
    value: function setRequest(val) {
      this.request = val;
    }
  }, {
    key: "getRequest",
    value: function getRequest() {
      return this.request;
    }
  }]);
  return Request;
}();
export var request = new Request();

/**
 * @title: 格式化持续时长用于展示
 * @description:
 * @param {number} service_times
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-04-26 14:00
 */
export var getDiscountTime = function getDiscountTime(service_times, isDay) {
  if (!service_times || service_times < 0) {
    return '';
  }

  // 跨日预约
  if (isDay) {
    return "".concat(service_times, " ").concat(locales.getText('pisell2.text.day')(service_times));
  }
  if (service_times < 60) {
    return "".concat(service_times, " ").concat(locales.getText('pisell2.text.min'));
  } else {
    var str = '';
    var hours = Math.floor(service_times / 60);
    var minutes = service_times % 60;
    str += "".concat(hours).concat(locales.getText('pisell2.text.h'));
    if (minutes > 0) {
      str += " ".concat(minutes).concat(locales.getText('pisell2.text.min'));
    }
    return str;
  }
};

/**
 * @title: 时间切片
 * @description:
 * @param {any} config
 * @param {string} locale
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-04-26 13:59
 */
export var sliceDayIntoFiveMinutes = function sliceDayIntoFiveMinutes(config, locale, isDay) {
  var _locale = locale;
  var dayjsLocale = _locale === 'en-US' || _locale === 'en' ? 'en' : 'zh-cn';
  dayjs.locale(dayjsLocale);
  var startTime = dayjs().startOf('day');
  var endTime = dayjs().endOf('day');
  var timeSlice = (config === null || config === void 0 ? void 0 : config.value) || 5; // 切片时间间隔（分钟）

  var timeSlices = [];
  var durationSlicesBasedOnTime = [];
  var currentTime = startTime;

  // 跨日预约
  if (isDay) {
    var currentDay = 1;
    while (currentDay <= 30) {
      var timeLabel = currentTime.format('hh:mm A');
      var timeValue = currentTime.format('HH:mm');
      timeSlices.push({
        label: timeLabel,
        value: timeValue
      });
      durationSlicesBasedOnTime.push({
        label: "".concat(currentDay, " ").concat(locales.getText('pisell2.text.day')(currentDay)),
        value: currentDay
      });
      currentDay++;
    }
    return {
      timeSlices: timeSlices,
      durationSlicesBasedOnTime: durationSlicesBasedOnTime
    };
  }
  while (currentTime.isBefore(endTime)) {
    var _timeLabel = currentTime.format('hh:mm A');
    var _timeValue = currentTime.format('HH:mm');
    timeSlices.push({
      label: _timeLabel,
      value: _timeValue
    });
    var nextTime = currentTime.add(timeSlice, 'minute');
    var durationValue = nextTime.diff(startTime, 'minute');
    if (durationValue > 60) {
      var durationLabel = getDiscountTime(durationValue);
      durationSlicesBasedOnTime.push({
        label: durationLabel,
        value: durationValue
      });
    } else {
      var _durationLabel = "".concat(durationValue, " ").concat(locales.getText('pisell2.text.min'));
      durationSlicesBasedOnTime.push({
        label: _durationLabel,
        value: durationValue
      });
    }
    currentTime = nextTime;
  }
  return {
    timeSlices: timeSlices,
    durationSlicesBasedOnTime: durationSlicesBasedOnTime
  };
};

//  获取当前时间
export var getNowTime = function getNowTime() {
  return dayjs().format('HH:mm');
};
export var isNowTime = function isNowTime(time) {
  return time === 'now';
};

/**
 * @title: 获取服务的开始时间, 如果是now 转换为当前的时间
 * @description:
 * @param {string} start_time
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-04-26 14:03
 */
export var getServeStartTime = function getServeStartTime(start_time) {
  if (isNowTime(start_time)) {
    return getNowTime();
  }
  return start_time;
};

/**
 * @title: 格式化服务的 开始时间-结束时间-时长, 用于展示
 * @description:
 * @param {any} item
 * @param {any} currentDate
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-04-26 14:04
 */
export var getServiceTime = function getServiceTime(item, currentDate) {
  var startDate = dayjs(currentDate.format('YYYY-MM-DD') + ' ' + getServeStartTime(item._extend.start_time));
  var startTime = startDate.format('HH:mm');
  var endTime = startDate.add(flexibleObj.getValue(item._extend.duration), 'minute').format('HH:mm');
  var duration = getDiscountTime(flexibleObj.getValue(item._extend.duration));
  return "".concat(startTime, " - ").concat(endTime, " ( ").concat(duration, " )");
};
export var findNextSlice = function findNextSlice(_ref) {
  var _ref$timeSlices = _ref.timeSlices,
    timeSlices = _ref$timeSlices === void 0 ? [] : _ref$timeSlices,
    _ref$index = _ref.index,
    index = _ref$index === void 0 ? 0 : _ref$index,
    _ref$date = _ref.date,
    date = _ref$date === void 0 ? '' : _ref$date;
  var currentTimeValue = date || dayjs().format('HH:mm');

  // 遍历时间切片数组，找到最接近的下一个切片时间
  for (var i = 0; i < timeSlices.length; i++) {
    // 排除掉当前时间
    if (timeSlices[i].value !== 'now') {
      if (timeSlices[i].value >= currentTimeValue) {
        return timeSlices[i].value;
      }
    }
  }

  // 如果没有找到比当前时间大的切片时间，则返回第一个切片时间作为下一个切片时间
  return timeSlices[index].value;
};
export var findNextDuration = function findNextDuration(current, array, defaultValue) {
  for (var i = 0; i < array.length; i++) {
    if (array[i].value == (current === null || current === void 0 ? void 0 : current.value)) {
      return array[i].value;
    }
  }
  return defaultValue || array[0].value;
};
export var formatProductListByCategory = function formatProductListByCategory(list, filterItem) {
  var _list = list || [];
  if (filterItem) {
    _list = _list.filter(filterItem);
  }
  var categoryObject = {};
  for (var i = 0; i < _list.length; i++) {
    var productItem = _list[i];
    if ((productItem.category || []).length) {
      for (var j = 0; j < productItem.category.length; j++) {
        var categoryItem = productItem.category[j];
        // categoryItem.name = categoryItem.title;
        if (!categoryObject[categoryItem.id]) {
          categoryObject[categoryItem.id] = _objectSpread(_objectSpread({}, categoryItem), {}, {
            products: []
          });
        }
        categoryObject[categoryItem.id] = _objectSpread(_objectSpread({}, categoryItem), {}, {
          products: [].concat(_toConsumableArray(categoryObject[categoryItem.id].products), [productItem])
        });
      }
    } else {
      if (!categoryObject['other']) {
        categoryObject['other'] = {
          id: 0,
          title: locales.getText('pisell2.text.other'),
          name: locales.getText('pisell2.text.other'),
          cover: '',
          products: []
        };
      }
      categoryObject['other'] = _objectSpread(_objectSpread({}, categoryObject['other']), {}, {
        products: [].concat(_toConsumableArray(categoryObject['other'].products), [productItem])
      });
    }
  }
  return Object.values(categoryObject).sort(function (a, b) {
    return b.sort - a.sort;
  });
};
export var getResourceTimeIsUsable = function getResourceTimeIsUsable(item, cacheItem) {
  var _cacheItem$_extend;
  // 是编辑的商品
  var isEdit = !!cacheItem.booking_id;

  // 是当前绑定的资源
  var isCurrentRelation = item.item_id === (cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend = cacheItem._extend) === null || _cacheItem$_extend === void 0 ? void 0 : _cacheItem$_extend.relation_id);
  var startDate = dayjs(cacheItem._extend.start_date.format('YYYY-MM-DD') + ' ' + getServeStartTime(cacheItem._extend.start_time));
  var isFlexible = flexibleObj.isFlexible(cacheItem._extend.duration);

  // 是否在最大预约数量的区间内
  var isMaxLimitRange = false;

  // 是否在日期范围内
  var isDateRange = false;
  var time = _objectSpread({}, item);
  // 已预约的数量 + 当前数量 <= 最大可预约数量    为可预约
  if (time.max_participants_limit == 0) {
    isMaxLimitRange = true;
  } else {
    // 编辑当前选择资源，当前资源已预约数量 - 1
    var orderEventCount = isEdit && isCurrentRelation ? time.order_event_count - 1 : time.order_event_count;
    isMaxLimitRange = orderEventCount < time.max_participants_limit;
  }
  var timeStartDate = dayjs(time.start_date + ' ' + time.start_time).subtract(1, 'second');
  var timeEndDate = dayjs(time.end_date + ' ' + time.end_time).add(1, 'second');
  var bol;

  // 灵活时长的 只判断开始时间是否在范围内
  if (isFlexible) {
    bol = startDate.isAfter(timeStartDate) && startDate.isBefore(timeEndDate);
  } else {
    // 其余判断 开始时间 和 结束时间 是否都在范围内
    var endDate = startDate.add(flexibleObj.getValue(cacheItem._extend.duration), 'minute');
    bol = startDate.isAfter(timeStartDate) && endDate.isBefore(timeEndDate);
  }

  // 是否在时间范围内
  if (bol) {
    isDateRange = true;
  }
  // 是否可用
  var isUsable = isDateRange;

  // 储存到拓展数据内
  time._extend = {
    isMaxLimitRange: isMaxLimitRange,
    isDateRange: isDateRange,
    isUsable: isUsable
  };
  return time;
};

/**
 * @title: 查找是否有可用的time
 * @description:
 * @param {any} resourceItem
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-01-09 13:57
 */
export var formatTimes = function formatTimes(resourceItem, cacheItem) {
  var _cacheItem$_extend2;
  if ((cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend2 = cacheItem._extend) === null || _cacheItem$_extend2 === void 0 ? void 0 : _cacheItem$_extend2.sub_type) === 'days') {
    var isResourceItem = (resourceItem === null || resourceItem === void 0 ? void 0 : resourceItem.form_record_id) > 0;

    // 是否在最大预约数量的区间内
    var isMaxLimitRange = (resourceItem === null || resourceItem === void 0 ? void 0 : resourceItem.sold_out) === 1;

    // 是否在日期范围内
    var isDateRange = (resourceItem === null || resourceItem === void 0 ? void 0 : resourceItem.available_status) === 1;

    // 是否可用
    var isUsable = isDateRange && !isMaxLimitRange;
    var usableTime = {
      isMaxLimitRange: isMaxLimitRange,
      isDateRange: isDateRange,
      isUsable: isResourceItem ? isUsable : true
    };
    resourceItem._extend = _objectSpread(_objectSpread({}, resourceItem._extend), {}, {
      usableTime: usableTime
    });
    return resourceItem;
  }

  // 可用的time列表
  var usableTimes = [];
  var _resourceItem = _objectSpread({}, resourceItem);
  // 循环times  区分可用和不可用的 并打上标记
  _resourceItem.times = _resourceItem.times.map(function (time) {
    var _time = getResourceTimeIsUsable(time, cacheItem);
    // 取出可用的列表
    if (_time !== null && _time !== void 0 && _time._extend.isUsable) {
      usableTimes.push(_time);
    }
    return _time;
  });

  // 获取第一个最佳的time
  var _time = (usableTimes || []).sort(function (a, b) {
    var aEndDate = dayjs(a.end_date + ' ' + a.end_time).valueOf();
    var bEndDate = dayjs(b.end_date + ' ' + b.end_time).valueOf();
    return aEndDate - bEndDate;
  })[0];
  resourceItem._extend = _objectSpread(_objectSpread({}, resourceItem._extend), {}, {
    usableTime: _time
  });
  return resourceItem;
};

/**
 * @title:
 * @description: 查找是否有可用的商品
 * @param {any} resourceItem
 * @param {any} currentItem
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-01-09 13:59
 */
var formatResourceProducts = function formatResourceProducts(resourceItem, currentItem) {
  var usableProduct = false;
  var _resourceItem = _objectSpread({}, resourceItem);
  // 商品类型
  var type = _resourceItem.partyroom_package.type;

  // 全部商品
  if (type === 'product_all') {
    usableProduct = true;
  } else {
    if (type === 'product_collection') {
      var _resourceItem$partyro;
      // 取交集  intersectionBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); // => [{ 'x': 2 }]
      usableProduct = !!intersectionBy(((_resourceItem$partyro = _resourceItem.partyroom_package) === null || _resourceItem$partyro === void 0 ? void 0 : _resourceItem$partyro.products.map(function (item) {
        return _objectSpread(_objectSpread({}, item), {}, {
          id: item.product_collection_id
        });
      })) || [], currentItem.collection || [], 'id').length;
    } else {
      usableProduct = _resourceItem.partyroom_package.products.some(function (item) {
        // 判断商品
        if (type === 'products') {
          if (item.product_id == currentItem.product_id) {
            return true;
          }
        }
      });
    }
  }
  resourceItem._extend = _objectSpread(_objectSpread({}, resourceItem._extend), {}, {
    // 是否可用
    usableProduct: usableProduct
  });
  return resourceItem;
};

/**
 * @title: 获取店铺的营业结束时间
 * @description:
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-02-23 10:00
 */
export var getShopOpeningHours = function getShopOpeningHours() {
  return localStorage.getItem('shopOpeningHours') || '23:59';
};

/**
 * @title: 对灵活时长进行处理
 * @description:
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-02-23 10:00
 */
export var flexibleObj = {
  // 创建, 增加前缀
  create: function create(num) {
    return "flexible_".concat(num);
  },
  // 格式化, 去除前缀
  getValue: function getValue(str) {
    if (typeof str === 'string' && flexibleObj.isFlexible(str)) {
      return Number(str.replace('flexible_', ''));
    }
    return str;
  },
  // 判断当前时长是否为灵活时长
  isFlexible: function isFlexible(str) {
    if (typeof str !== 'string') {
      return false;
    }
    return str.indexOf('flexible_') > -1;
  },
  add: function add(current, duration) {
    if (flexibleObj.isFlexible(current)) {
      return flexibleObj.create(flexibleObj.getValue(current) + duration);
    } else {
      return Number(current) + duration;
    }
  }
};

/**
 * @title: 获取结束时间
 * @description: 取 endDate | 店铺营业时间 最小的那一个
 * @param {any} startDate
 * @param {string} duration
 * @param {any} endDate
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-02-23 10:01
 */
export var getEndDate = function getEndDate(startDate, duration, endDate) {
  if (duration === 'flexible') {
    // 店铺营业结束时间
    var openingDate = dayjs(startDate.format('YYYY-MM-DD') + ' ' + getShopOpeningHours());

    // 如果选择的开始时间 > 店铺的营业时间, 店铺营业时间向后推一天
    if (dayjs(startDate).isAfter(openingDate)) {
      openingDate = openingDate.add(1, 'day');
    }
    if (!endDate) {
      return openingDate;
    }
    endDate = dayjs(endDate);

    // 如果最佳time时间 大于 店铺营业结束时间,  则 取店铺营业时间, 否则为time的结束时间
    if (endDate.isAfter(openingDate)) {
      return openingDate;
    }
    return endDate;
  }
  return startDate.add(duration, 'minute');
};

// export const get

export var getServiceTimes = function getServiceTimes(service) {
  var _service$_extend;
  var startDate = dayjs(dayjs(service._extend.start_date).format('YYYY-MM-DD ') + getServeStartTime(service._extend.start_time));
  var endDate = startDate.add(flexibleObj.getValue(service._extend.duration), 'minute');
  var session = service === null || service === void 0 || (_service$_extend = service._extend) === null || _service$_extend === void 0 || (_service$_extend = _service$_extend.other) === null || _service$_extend === void 0 ? void 0 : _service$_extend.session;
  if (isSessionProduct(service) && session) {
    return {
      startDate: dayjs(session.start_at),
      endDate: dayjs(session.end_at)
    };
  }
  return {
    startDate: startDate,
    endDate: endDate
  };
};
export var getErrorList = function getErrorList(resource, cacheItem, isDay) {
  if (!(cacheItem !== null && cacheItem !== void 0 && cacheItem.id)) {
    return [{
      label: locales.getText('pisell2.text.no-product-added'),
      type: 'products'
    }];
  }
  if (!resource || !resource._extend || !cacheItem) {
    return [];
  }
  var list = [];
  // 当前资源不可用
  if (!resource.usable) {
    var _resource$_extend, _resource$_extend2, _resource$_extend3;
    // 挂接的商品不可用
    if (!(resource !== null && resource !== void 0 && (_resource$_extend = resource._extend) !== null && _resource$_extend !== void 0 && _resource$_extend.usableProduct)) {
      list.push({
        label: locales.getText('pisell1.text.resource-error-message-1')(resource.labelText, cacheItem === null || cacheItem === void 0 ? void 0 : cacheItem.title),
        type: 'product'
      });
    }
    var startText = '';
    var endText = '';

    // 跨日预约
    if (isDay) {
      var _cacheItem$_extend3 = cacheItem === null || cacheItem === void 0 ? void 0 : cacheItem._extend,
        start_date = _cacheItem$_extend3.start_date,
        end_date = _cacheItem$_extend3.end_date;
      startText = start_date === null || start_date === void 0 ? void 0 : start_date.format('YYYY-MM-DD');
      endText = end_date ? end_date === null || end_date === void 0 ? void 0 : end_date.format('YYYY-MM-DD') : '';
    } else {
      var _getServiceTimes = getServiceTimes(cacheItem),
        startDate = _getServiceTimes.startDate,
        endDate = _getServiceTimes.endDate;
      // 如果跨天  结束时间前面加一个明天
      startText = startDate.format('hh:mm A');
      endText = endDate.format('hh:mm A');
      if (dayjs(endDate).isAfter(startDate, 'day')) {
        endText = locales.getText('pisell1.text.tomorrow') + endText;
      }
    }
    if (isDay ? !((_resource$_extend2 = resource._extend) !== null && _resource$_extend2 !== void 0 && (_resource$_extend2 = _resource$_extend2.usableTime) !== null && _resource$_extend2 !== void 0 && _resource$_extend2.isDateRange) : !((_resource$_extend3 = resource._extend) !== null && _resource$_extend3 !== void 0 && _resource$_extend3.usableTime)) {
      list.push({
        label: locales.getText('pisell1.text.resource-error-message-2')(resource.labelText, startText, endText),
        type: 'time'
      });
    } else {
      var _resource$_extend4, _resource$_extend5;
      if (isDay ? (_resource$_extend4 = resource._extend) === null || _resource$_extend4 === void 0 || (_resource$_extend4 = _resource$_extend4.usableTime) === null || _resource$_extend4 === void 0 ? void 0 : _resource$_extend4.isMaxLimitRange : !((_resource$_extend5 = resource._extend) !== null && _resource$_extend5 !== void 0 && (_resource$_extend5 = _resource$_extend5.usableTime) !== null && _resource$_extend5 !== void 0 && (_resource$_extend5 = _resource$_extend5._extend) !== null && _resource$_extend5 !== void 0 && _resource$_extend5.isMaxLimitRange)) {
        list.push({
          label: locales.getText('pisell1.text.resource-error-message-3')(resource.labelText, startText, endText),
          type: 'limit'
        });
      }
    }
  }
  return list;
};

/**
 * @title: 格式化资源, 添加自定义参数
 * @description:
 * @param {any} resourceItem
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-01-09 13:40
 */
export var formatResource = function formatResource(resourceItem, cacheItem, formatLabel) {
  var _resourceItem$_extend, _cacheItem$_extend4;
  // 当前资源
  var _resourceItem = _objectSpread({}, resourceItem);

  // 格式化times里面的数据
  _resourceItem = formatTimes(_resourceItem, cacheItem);

  // 格式化partyroom_package 里面的数据
  _resourceItem = formatResourceProducts(_resourceItem, cacheItem);

  // 格式化label
  _resourceItem.labelText = _resourceItem.room_name || _resourceItem.name;
  var usable = _resourceItem._extend.usableTime && ((_resourceItem$_extend = _resourceItem._extend.usableTime._extend) === null || _resourceItem$_extend === void 0 ? void 0 : _resourceItem$_extend.isMaxLimitRange) && _resourceItem._extend.usableProduct;

  // 跨日预约
  if ((cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend4 = cacheItem._extend) === null || _cacheItem$_extend4 === void 0 ? void 0 : _cacheItem$_extend4.sub_type) === 'days') {
    var _resourceItem$_extend2, _resourceItem$_extend3;
    usable = ((_resourceItem$_extend2 = _resourceItem._extend) === null || _resourceItem$_extend2 === void 0 || (_resourceItem$_extend2 = _resourceItem$_extend2.usableTime) === null || _resourceItem$_extend2 === void 0 ? void 0 : _resourceItem$_extend2.isUsable) && ((_resourceItem$_extend3 = _resourceItem._extend) === null || _resourceItem$_extend3 === void 0 ? void 0 : _resourceItem$_extend3.usableProduct);
  }
  _resourceItem.usable = usable;
  if (formatLabel) {
    _resourceItem.label = formatLabel(_resourceItem);
  }
  return _resourceItem;
};

// 获取最后一个服务商品
export var getLastServer = function getLastServer(list) {
  return list[list.length - 1];
};
export var getCacheParams = function getCacheParams() {
  // 从缓存里读默认参数,  如果有 则需要默认选中某些参数,  添加完商品后则删除
  var sessionData = sessionStorage.getItem('pisell2.booking.serviceParams');
  var data = sessionData ? JSON.parse(sessionData) : null;
  return data === null || data === void 0 ? void 0 : data.serviceParams;
};
export var deleteCacheParams = function deleteCacheParams() {
  sessionStorage.removeItem('pisell2.booking.serviceParams');
};

/**
 * @title: 获取跨日预约的时长
 * @description: 
 * @param {any} cacheItem
 * @return {*}
 * @Author: WangHan
 * @Date: 2024-12-01 22:43
 */
export var getDays = function getDays(cacheItem, type) {
  var _cacheItem$_extend5, _cacheItem$_extend6;
  // 计算天数
  if (type === 'days') {
    var _formatDayDate = formatDayDate(cacheItem._extend),
      start_date = _formatDayDate.start_date,
      end_date = _formatDayDate.end_date;
    return end_date.diff(start_date, 'day');
  }
  var startDate = dayjs((_cacheItem$_extend5 = cacheItem._extend) === null || _cacheItem$_extend5 === void 0 ? void 0 : _cacheItem$_extend5.start_date);
  var endDate = dayjs((_cacheItem$_extend6 = cacheItem._extend) === null || _cacheItem$_extend6 === void 0 ? void 0 : _cacheItem$_extend6.end_date);
  return endDate.diff(startDate, type);
};
export var isSessionProduct = function isSessionProduct(cacheItem) {
  return ['session_product', 'session_ticket'].includes(cacheItem.extension_type);
};
export var getIsEject = function getIsEject(item, type) {
  var isSession = isSessionProduct(item);
  // 是否有单规格 组合规格 套餐, 或者session商品 如果没有不需要打开弹窗
  return type === 'detail' || item.bundle_group_count > 0 || item.option_group_count > 0 || item.is_variant > 0 || isSession;
};
export var getIsOnlySession = function getIsOnlySession(item) {
  var isSession = isSessionProduct(item);
  return !(item.bundle_group_count > 0 || item.option_group_count > 0 || item.is_variant > 0) && isSession;
};

/**
 * @title: 创建一个服务商品
 * @description:
 * @param {any} state
 * @param {any} item
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-01-26 14:09
 */
export var getServerItemExtend = function getServerItemExtend(state, cacheItem, timeObj) {
  // 编辑直接返回原数据
  if (!cacheItem.new && cacheItem._extend.endDate) {
    return cacheItem._extend;
  }
  var appointmentTimingPreference = getAppointmentTimingPreference(state);
  var isSession = isSessionProduct(cacheItem);
  var isDay = isDayBooking(state);
  var setDuration = function setDuration() {
    var _cacheItem$duration;
    if (isDay) {
      return getDays(cacheItem, 'days');
    }
    if (isSession) {
      return getDays(cacheItem, 'minutes');
    }
    return findNextDuration(cacheItem.duration, timeObj.durationSlicesBasedOnTime, cacheItem === null || cacheItem === void 0 || (_cacheItem$duration = cacheItem.duration) === null || _cacheItem$duration === void 0 ? void 0 : _cacheItem$duration.value);
  };

  // 获取上一个服务商品
  var lastServer = isDay ? false : getLastServer(state.service.value);

  // 下一个商品的扩展参数
  var _extend = {
    duration: setDuration()
  };

  // 如果有上一个商品, 将上一个商品的某些参数 设置到新商品上
  if (lastServer) {
    // 选中上一个商品的资源
    _extend.resource = lastServer._extend.resource;
    var lastServerStartDate = lastServer._extend.startDate;
    var lastServerEndDate = lastServer._extend.endDate;

    // 同时预约模式
    if (appointmentTimingPreference === 'parallel') {
      _extend.start_time = lastServerStartDate.format('HH:mm');
    } else {
      // 如果上个服务商品的结束时间跨天, 那么设置为最后一个时间段,  不跨天则取上一个的结束时间
      if (dayjs(lastServerEndDate).isAfter(lastServerStartDate, 'day')) {
        _extend.start_time = timeObj.timeSlices[timeObj.timeSlices.length - 1].value;
      } else {
        _extend.start_time = lastServerEndDate.format("HH:mm");
      }
    }
  } else {
    // 没有上一个商品  资源为 0
    // _extend.resource = 0;

    var findNextSliceProps = {
      timeSlices: timeObj.timeSlices,
      index: 0,
      date: ''
    };

    // 从缓存里读默认参数,  如果有 则需要默认选中某些参数,  添加完商品后则删除
    var serviceParams = getCacheParams();
    if (serviceParams) {
      var str = serviceParams.start_date;
      if (str) {
        // 选中开始时间
        findNextSliceProps.date = dayjs(str).format('HH:mm');
      }
      // 选中资源
      var resourceId = Number(serviceParams.resource_id);
      if (resourceId || resourceId === 0) {
        _extend.resource = resourceId;
      }
    }

    // 只有选择了带 HH:mm的日期才选中, 否则使用当前日期
    if (findNextSliceProps.date && findNextSliceProps.date !== '00:00') {
      _extend.start_time = findNextSlice(findNextSliceProps);
    } else {
      if (cacheItem.currentDefaultTime) {
        _extend.start_time = cacheItem.currentDefaultTime;
      } else {
        // 没有预设日期, 则使用当前 https://www.yuque.com/feg4xm/manual/tzvrnt05ifihkndg
        _extend.start_time = dayjs().format('HH:mm');
      }
    }
  }
  _extend = _objectSpread(_objectSpread({}, _extend), cacheItem._extend);

  // 跨日预约
  if (isDay) {
    _extend.end_date = dayjs(_extend.start_date).add(_extend.duration, 'day');
    var _formatDayDate2 = formatDayDate(_extend),
      start_date = _formatDayDate2.start_date,
      end_date = _formatDayDate2.end_date;
    _extend = _objectSpread(_objectSpread({}, _extend), {}, {
      start_date: start_date,
      startDate: start_date,
      end_date: end_date,
      endDate: end_date
    });
  }
  return _extend;
};

// 商品价格:   (商品价格 + (套餐价格 + 单规格价格 * 单规格数量) * 套餐数量 + 单规格价格 * 单规格数量)  * 商品数量
export var getProductTotalPrice = function getProductTotalPrice(item) {
  var _item$_extend;
  var price = Number(item._extend.price);
  var other = (_item$_extend = item._extend) === null || _item$_extend === void 0 ? void 0 : _item$_extend.other;

  // 多规格
  if (other !== null && other !== void 0 && other.product_variant_id) {
    price = Number(other === null || other === void 0 ? void 0 : other.price);
  }
  if (other !== null && other !== void 0 && other.bundle) {
    // bundle
    price = other === null || other === void 0 ? void 0 : other.bundle.reduce(function (accumulator, currentValue) {
      return accumulator + Number(currentValue.price) * Number(currentValue.num);
    }, price);
  }

  // 单规格
  if (other !== null && other !== void 0 && other.option) {
    price = other === null || other === void 0 ? void 0 : other.option.reduce(function (accumulator, currentValue) {
      return accumulator + Number(currentValue.price) * Number(currentValue.num);
    }, price);
  }
  return price;
};
/**
 * @title: 判断 duration
 * @description: 用于处理不同格式的duration
 * @param {number} duration
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-02-23 10:02
 */
export var getDuration = function getDuration(duration) {
  // number  为 minutes
  if (typeof duration === 'number') {
    return duration;
  }

  // 对象结构 判断是分钟还是灵活时长
  if (_typeof(duration) === 'object') {
    if (duration.type === 'minutes') {
      return duration.value;
    }
    if (duration.type === 'flexible') {
      return 'flexible';
    }
  }
  return duration;
};
export var isWalkIn = function isWalkIn(customer_id) {
  if (customer_id === undefined) {
    return true;
  }
  if (typeof customer_id === 'string') {
    return ['', '0', '1'].includes(customer_id);
  }
  return [0, 1].includes(customer_id);
};
export var getIsEdit = function getIsEdit(state) {
  var _state$addons, _state$client, _state$date, _state$pet, _state$service, _state$notes, _state$contacts;
  if ((_state$addons = state.addons) !== null && _state$addons !== void 0 && _state$addons.edit) {
    return true;
  }

  // info 是否有编辑
  if (!state.bookingId) {
    return true;
  }
  if ((_state$client = state.client) !== null && _state$client !== void 0 && _state$client.edit) {
    return true;
  }
  if ((_state$date = state.date) !== null && _state$date !== void 0 && _state$date.edit) {
    return true;
  }
  if ((_state$pet = state.pet) !== null && _state$pet !== void 0 && _state$pet.edit) {
    return true;
  }
  if ((_state$service = state.service) !== null && _state$service !== void 0 && _state$service.edit) {
    return true;
  }
  if ((_state$notes = state.notes) !== null && _state$notes !== void 0 && _state$notes.edit) {
    return true;
  }
  if ((_state$contacts = state.contacts) !== null && _state$contacts !== void 0 && _state$contacts.edit) {
    return true;
  }
  return false;
};