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 _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
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 _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); }
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; }
import dayjs from 'dayjs';
import { formatResources, getResourceByIds, getSumCapacity, getUsableTime, setDefaultCapacitys, setDefaultResource } from "./resources";
import { hasActualResourceSelection, productNeedsResourceExtend } from "./resourceSelection";
import { isMultiDayProduct, isSessionProduct, getDays, getServiceTimes } from "./serviceTimes";
import { sliceDayIntoFiveMinutes, findNextDuration, getEndDate } from "./timeSlices";
import { flexibleObj, getDurationValue, isProductFlexibleDuration } from "./flexible";

/**
 * 上下文（与 info2 state.bookingConfig / state.service / state.date 一一对应）。
 *
 * 设计原则：所有助手函数都通过 context 显式拿数据，**不读 mini-redux**，
 * 让 OS 这层完全可在 Node 单测下运行（dayjs 在 Node 也是纯函数）。
 */

/** 从 BookingContext.date 提取 HH:mm（仅当日期带有效时分时）。 */
export function derivePresetStartTimeFromDate(date) {
  if (date == null) return undefined;
  var d = dayjs(date);
  if (!d.isValid()) return undefined;
  var hhmm = d.format('HH:mm');
  if (hhmm === '00:00') return undefined;
  return hhmm;
}

/**
 * 取预约时间偏好（sequential / parallel）；默认 sequential。
 */
function getAppointmentTimingPreference(ctx) {
  var _ctx$bookingConfig;
  return (ctx === null || ctx === void 0 || (_ctx$bookingConfig = ctx.bookingConfig) === null || _ctx$bookingConfig === void 0 || (_ctx$bookingConfig = _ctx$bookingConfig.config) === null || _ctx$bookingConfig === void 0 || (_ctx$bookingConfig = _ctx$bookingConfig.information_tab) === null || _ctx$bookingConfig === void 0 ? void 0 : _ctx$bookingConfig.appointment_timing_preference) || 'sequential';
}

/**
 * 灵活时长选项（cacheItem.duration.type === 'flexible' 时）。
 */
function getFlexibleOption(params) {
  var _cacheItem$_extend, _cacheItem$_extend2, _usable$_extend, _params$ctx;
  var cacheItem = params.cacheItem,
    useStartTime = params.useStartTime;
  var duration = getDurationValue(cacheItem === null || cacheItem === void 0 ? void 0 : cacheItem.duration);
  if (duration !== 'flexible') return null;
  var startDate = dayjs("".concat(dayjs(cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend = cacheItem._extend) === null || _cacheItem$_extend === void 0 ? void 0 : _cacheItem$_extend.start_date).format('YYYY-MM-DD'), " ").concat(useStartTime || (cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend2 = cacheItem._extend) === null || _cacheItem$_extend2 === void 0 ? void 0 : _cacheItem$_extend2.start_time) || '00:00'));
  var usable = getUsableTime(cacheItem);
  var usableEndAt = usable !== null && usable !== void 0 && (_usable$_extend = usable._extend) !== null && _usable$_extend !== void 0 && (_usable$_extend = _usable$_extend.usableTime) !== null && _usable$_extend !== void 0 && _usable$_extend.end_at ? dayjs(usable._extend.usableTime.end_at) : null;
  var endDate = getEndDate(startDate, 'flexible', usableEndAt, (_params$ctx = params.ctx) === null || _params$ctx === void 0 ? void 0 : _params$ctx.shopOpeningHours);
  var timeValue = endDate.diff(startDate, 'minute');
  return {
    label: String(timeValue),
    value: flexibleObj.create(timeValue)
  };
}

/**
 * 时间切片对象（含灵活时长选项）。与 info2 `getTimeObj` 等价。
 */
export function getTimeObj(params) {
  var _ctx$bookingConfig2;
  var cacheItem = params.cacheItem,
    useStartTime = params.useStartTime,
    useDuration = params.useDuration,
    ctx = params.ctx;
  var isMultiDay = isMultiDayProduct(cacheItem);
  var flexibleOption = getFlexibleOption({
    cacheItem: cacheItem,
    useStartTime: useStartTime,
    ctx: ctx
  });
  var baseSlices = sliceDayIntoFiveMinutes(ctx === null || ctx === void 0 || (_ctx$bookingConfig2 = ctx.bookingConfig) === null || _ctx$bookingConfig2 === void 0 || (_ctx$bookingConfig2 = _ctx$bookingConfig2.config) === null || _ctx$bookingConfig2 === void 0 || (_ctx$bookingConfig2 = _ctx$bookingConfig2.basic) === null || _ctx$bookingConfig2 === void 0 ? void 0 : _ctx$bookingConfig2.service_time, isMultiDay);
  var timeSlices = _toConsumableArray(baseSlices.timeSlices);
  var durationSlicesBasedOnTime = _toConsumableArray(baseSlices.durationSlicesBasedOnTime);
  if (flexibleOption) {
    durationSlicesBasedOnTime.unshift(flexibleOption);
  }
  if (useDuration && !durationSlicesBasedOnTime.some(function (d) {
    return d.value === useDuration;
  })) {
    durationSlicesBasedOnTime.unshift({
      label: String(useDuration),
      value: useDuration
    });
  }
  return {
    timeSlices: timeSlices,
    durationSlicesBasedOnTime: durationSlicesBasedOnTime
  };
}

/**
 * 计算商品行 _extend（包含 start_time / endDate / duration / start_date / end_date / sub_type 等）。
 * 与 info2 `utilsByBooking.ts#getServiceStartTimeAndEndTime` 等价；显著差异：
 *   - 不读 `state.service.value` / `mini-redux`，由 ctx.previousService 显式注入。
 *   - 不读 `sessionStorage.serviceParams`，由 ctx.presetStartTime / ctx.resourceIdFromCalendar 注入。
 *   - cacheItem.isCustomItem → 直接返回 `{ duration: null }`。
 */
export function getServiceStartTimeAndEndTime(params) {
  var _cacheItem$_extend3;
  var cacheItem = params.cacheItem,
    timeObj = params.timeObj,
    ctx = params.ctx;
  if (cacheItem !== null && cacheItem !== void 0 && cacheItem.isCustomItem) {
    return {
      duration: null
    };
  }
  var appointmentTimingPreference = getAppointmentTimingPreference(ctx);
  var lastServer = ctx.previousService || null;
  var resolveDuration = function resolveDuration() {
    var _cacheItem$duration;
    if (isMultiDayProduct(cacheItem)) return getDays(cacheItem, 'days');
    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 _extend = {
    duration: resolveDuration()
  };
  if (lastServer) {
    var _lastServer$_extend, _lastServer$_extend2;
    var lastStart = (_lastServer$_extend = lastServer._extend) === null || _lastServer$_extend === void 0 ? void 0 : _lastServer$_extend.startDate;
    var lastEnd = (_lastServer$_extend2 = lastServer._extend) === null || _lastServer$_extend2 === void 0 ? void 0 : _lastServer$_extend2.endDate;
    if (appointmentTimingPreference === 'parallel') {
      _extend.start_time = dayjs(lastStart).format('HH:mm');
    } else if (dayjs(lastEnd).isAfter(dayjs(lastStart), 'day')) {
      var _timeObj$timeSlices;
      _extend.start_time = (_timeObj$timeSlices = timeObj.timeSlices[timeObj.timeSlices.length - 1]) === null || _timeObj$timeSlices === void 0 ? void 0 : _timeObj$timeSlices.value;
    } else {
      _extend.start_time = lastEnd ? dayjs(lastEnd).format('HH:mm') : dayjs().format('HH:mm');
    }
  } else {
    var presetStartTime = ctx.presetStartTime;
    // 与 info2 getServiceStartTimeAndEndTime 一致：日历/顶部日期带 HH:mm 时原样使用，
    // 不做 findNextSlice 栅格对齐（否则 01:47 会被抬到 01:50）。
    if (presetStartTime && presetStartTime !== '00:00') {
      _extend.start_time = presetStartTime;
    } else if (cacheItem.currentDefaultTime) {
      _extend.start_time = cacheItem.currentDefaultTime;
    } else {
      _extend.start_time = dayjs().format('HH:mm');
    }
  }
  _extend = _objectSpread(_objectSpread({}, _extend), cacheItem._extend);
  var _getServiceTimes = getServiceTimes(_objectSpread(_objectSpread({}, cacheItem), {}, {
      _extend: _extend
    })),
    startDate = _getServiceTimes.startDate,
    endDate = _getServiceTimes.endDate;
  _extend.startDate = startDate;
  _extend.endDate = endDate;
  if (isMultiDayProduct(cacheItem)) {
    var _extend$start_date, _extend$end_date;
    _extend.start_time = _extend.start_time || startDate.format('HH:mm');
    _extend.end_time = _extend.end_time || endDate.format('HH:mm');
    _extend.start_date = (_extend$start_date = _extend.start_date) !== null && _extend$start_date !== void 0 ? _extend$start_date : startDate;
    _extend.end_date = (_extend$end_date = _extend.end_date) !== null && _extend$end_date !== void 0 ? _extend$end_date : endDate;
  }
  var session = cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend3 = cacheItem._extend) === null || _cacheItem$_extend3 === void 0 || (_cacheItem$_extend3 = _cacheItem$_extend3.other) === null || _cacheItem$_extend3 === void 0 ? void 0 : _cacheItem$_extend3.session;
  if (isSessionProduct(cacheItem) && session) {
    var baseDate = ctx.date ? dayjs(ctx.date) : dayjs();
    var startAt = dayjs("".concat(baseDate.format('YYYY-MM-DD'), " ").concat(dayjs(session.start_at).format('HH:mm:ss')));
    var endAt = dayjs("".concat(baseDate.format('YYYY-MM-DD'), " ").concat(dayjs(session.end_at).format('HH:mm:ss')));
    _extend.start_date = startAt;
    _extend.startDate = startAt;
    _extend.start_time = session.start_time;
    _extend.end_date = endAt;
    _extend.endDate = endAt;
    _extend.end_time = session.end_time;
    _extend.duration = getDays({
      _extend: _extend
    }, 'minutes');
  }
  return _extend;
}

/**
 * 综合：把 cacheItem 拼装出完整的 _extend / _data（资源 / 容量 / timeObj），并标记 autoClose。
 * 与 info2 `service/addService/utils.tsx#getProductExtend` 等价；剥 React `console.time` / JSX。
 *
 * 入参 ctx 必须至少给：bookingConfig / resourcesOriginMap / resourcesOrigin / date。
 */
export function getProductExtend(params) {
  var _cacheItem$_extend4;
  var cacheItem = params.cacheItem,
    ctx = params.ctx,
    isDisabledTime = params.isDisabledTime;
  var isNew = cacheItem.new || !((_cacheItem$_extend4 = cacheItem._extend) !== null && _cacheItem$_extend4 !== void 0 && _cacheItem$_extend4.endDate);
  var _cacheItem = _objectSpread({}, cacheItem);
  var resourcesOriginMap = ctx.resourcesOriginMap || {};
  _cacheItem._data = {};
  if (isMultiDayProduct(cacheItem)) {
    var _cacheItem$_extend5;
    _cacheItem._extend = _cacheItem._extend || {};
    _cacheItem._extend.holder_id = (cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend5 = cacheItem._extend) === null || _cacheItem$_extend5 === void 0 ? void 0 : _cacheItem$_extend5.holder_id) || [];
    _cacheItem._extend.sub_type = 'days';
  }
  if (isNew) {
    var _ctx$bookingConfig3;
    _cacheItem._data.timeObj = getTimeObj({
      cacheItem: cacheItem,
      ctx: ctx
    });
    _cacheItem._extend = getServiceStartTimeAndEndTime({
      cacheItem: cacheItem,
      timeObj: _cacheItem._data.timeObj,
      ctx: ctx
    });
    _cacheItem._data.capacitys = cacheItem.capacity;
    _cacheItem._data.resourcesOrigin = getResourceByIds(resourcesOriginMap, cacheItem, {
      resourceTab: ctx === null || ctx === void 0 || (_ctx$bookingConfig3 = ctx.bookingConfig) === null || _ctx$bookingConfig3 === void 0 || (_ctx$bookingConfig3 = _ctx$bookingConfig3.config) === null || _ctx$bookingConfig3 === void 0 ? void 0 : _ctx$bookingConfig3.resource_tab,
      resourcesOrigin: ctx.resourcesOrigin || []
    });
    _cacheItem._extend.capacity = setDefaultCapacitys({
      capacitys: _cacheItem._data.capacitys,
      cacheItem: _cacheItem
    });
    var _formatResources = formatResources({
        cacheItem: _cacheItem,
        resourcesOrigin: _cacheItem._data.resourcesOrigin
      }),
      list = _formatResources.list,
      maps = _formatResources.maps;
    _cacheItem._data.resources = list;
    _cacheItem._data.resourceMaps = maps;
    _cacheItem._extend.resource = setDefaultResource({
      cacheItem: _cacheItem,
      resources: _cacheItem._data.resources,
      resourceIdFromCalendar: ctx.resourceIdFromCalendar,
      isAutoAllocationOn: ctx.isAutoAllocationOn
    });

    // 灵活时长二次计算（资源默认选中后，按 usableTime 重算 flexible 分钟数）
    if (isProductFlexibleDuration(_cacheItem === null || _cacheItem === void 0 ? void 0 : _cacheItem.duration)) {
      var _cacheItem$_data$time;
      _cacheItem._data.timeObj = getTimeObj({
        cacheItem: _cacheItem,
        useStartTime: _cacheItem._extend.start_time,
        ctx: ctx
      });
      _cacheItem._extend.duration = (_cacheItem$_data$time = _cacheItem._data.timeObj) === null || _cacheItem$_data$time === void 0 || (_cacheItem$_data$time = _cacheItem$_data$time.durationSlicesBasedOnTime) === null || _cacheItem$_data$time === void 0 || (_cacheItem$_data$time = _cacheItem$_data$time[0]) === null || _cacheItem$_data$time === void 0 ? void 0 : _cacheItem$_data$time.value;
      var _getServiceTimes2 = getServiceTimes(_cacheItem),
        endDate = _getServiceTimes2.endDate;
      _cacheItem._extend.endDate = endDate;
    }
    _cacheItem.autoClose = getIsAutoClose(_cacheItem, ctx.isAutoAllocationOn || function () {
      return true;
    });
    if (_cacheItem._extend.bundle_edit !== undefined) {
      _cacheItem._extend.bundle_edit = 1;
    }
    if (!isDisabledTime) {
      _cacheItem._time = new Date().getTime();
    }
  } else {
    var _cacheItem$_extend7;
    if (!_cacheItem._data.capacitys) {
      _cacheItem._data.capacitys = cacheItem.capacity;
    }
    if (!_cacheItem._data.resourcesOrigin) {
      var _cacheItem$_extend6, _ctx$bookingConfig4;
      var extraResources = [];
      if (Array.isArray((_cacheItem$_extend6 = _cacheItem._extend) === null || _cacheItem$_extend6 === void 0 ? void 0 : _cacheItem$_extend6.event_resources)) {
        _cacheItem._extend.event_resources.forEach(function (er) {
          extraResources.push({
            form_id: er.form_id,
            id: er.relation_id
          });
        });
      }
      _cacheItem._data.resourcesOrigin = getResourceByIds(resourcesOriginMap, cacheItem, {
        extraResources: extraResources,
        resourceTab: ctx === null || ctx === void 0 || (_ctx$bookingConfig4 = ctx.bookingConfig) === null || _ctx$bookingConfig4 === void 0 || (_ctx$bookingConfig4 = _ctx$bookingConfig4.config) === null || _ctx$bookingConfig4 === void 0 ? void 0 : _ctx$bookingConfig4.resource_tab,
        resourcesOrigin: ctx.resourcesOrigin || []
      });
    }
    if (!_cacheItem._data.resources) {
      var _formatResources2 = formatResources({
          cacheItem: _cacheItem,
          resourcesOrigin: _cacheItem._data.resourcesOrigin
        }),
        _list = _formatResources2.list,
        _maps = _formatResources2.maps;
      _cacheItem._data.resources = _list;
      _cacheItem._data.resourceMaps = _maps;
    }
    _cacheItem._data.timeObj = getTimeObj({
      cacheItem: _cacheItem,
      useStartTime: (_cacheItem$_extend7 = _cacheItem._extend) === null || _cacheItem$_extend7 === void 0 ? void 0 : _cacheItem$_extend7.start_time,
      ctx: ctx
    });
  }
  return _cacheItem;
}

/**
 * 是否可自动关闭弹窗（不需要用户进 EditService 抽屉）。
 * 与 info2 `service/addService/utils.tsx#getIsAutoClose` 等价；
 * `getAutoAllocationStorage` 抽象为入参 `isAutoAllocationOn(formId)`。
 */
export function getIsAutoClose(cacheItem, isAutoAllocationOn) {
  var _cacheItem$_data, _cacheItem$_extend8;
  if (productNeedsResourceExtend(cacheItem) && !hasActualResourceSelection(cacheItem)) {
    return false;
  }
  if (((_cacheItem$_data = cacheItem._data) === null || _cacheItem$_data === void 0 || (_cacheItem$_data = _cacheItem$_data.capacitys) === null || _cacheItem$_data === void 0 ? void 0 : _cacheItem$_data.type) !== 'custom') {
    var _cacheItem$_data2;
    var resources = (cacheItem === null || cacheItem === void 0 || (_cacheItem$_data2 = cacheItem._data) === null || _cacheItem$_data2 === void 0 ? void 0 : _cacheItem$_data2.resources) || [];
    if (resources.length === 1) {
      var _first$select_type;
      var first = resources[0];
      if (((_first$select_type = first.select_type) === null || _first$select_type === void 0 ? void 0 : _first$select_type.type) === 'single' && (first.default_resource || []).length > 0) {
        return true;
      }
    }
  }
  var entries = Object.entries(((_cacheItem$_extend8 = cacheItem._extend) === null || _cacheItem$_extend8 === void 0 ? void 0 : _cacheItem$_extend8.resource) || {});
  if (entries.length === 0) {
    return !productNeedsResourceExtend(cacheItem);
  }
  return entries.every(function (_ref) {
    var _ref2 = _slicedToArray(_ref, 2),
      key = _ref2[0],
      value = _ref2[1];
    return isAutoAllocationOn(key) && Array.isArray(value) && value.length > 0;
  });
}
export { getSumCapacity };