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 _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
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 React from 'react';
import { getServeStartTime, getDuration, getEndDate, flexibleObj, sliceDayIntoFiveMinutes, getDiscountTime, getServiceTimes, getCacheParams } from "../../../utils";
import { getServiceStartTimeAndEndTime, formatResource, getErrorList } from "../../utilsByBooking";
import dayjs from 'dayjs';
import { locales } from '@pisell/utils';
import AlertTriangle from '@pisell/icon/es/AlertTriangle';
import { getAutoAllocationStorage } from "../editService/utils";
import { getNoResource2 } from "../../../mock";
import { cloneDeep } from 'lodash';
export var getUsableTime = function getUsableTime(cacheItem) {
  try {
    var items = [];
    var _loop = function _loop(form_id) {
      items = items.concat(cacheItem._extend.resource[form_id].map(function (d) {
        return cacheItem._data.resourceMaps[form_id].renderListMaps[d.relation_id];
      }));
    };
    for (var form_id in cacheItem._extend.resource) {
      _loop(form_id);
    }

    // 取最小的时间
    var minEndAt = items.reduce(function (pre, event) {
      var _event$_extend, _pre$_extend;
      var endAt = dayjs((_event$_extend = event._extend) === null || _event$_extend === void 0 || (_event$_extend = _event$_extend.usableTime) === null || _event$_extend === void 0 ? void 0 : _event$_extend.end_at);
      return endAt.isBefore((_pre$_extend = pre._extend) === null || _pre$_extend === void 0 || (_pre$_extend = _pre$_extend.usableTime) === null || _pre$_extend === void 0 ? void 0 : _pre$_extend.end_at) ? event : pre;
    }, items[0]);
    return minEndAt;
  } catch (err) {
    return null;
  }
};
export var getDurationProps = function getDurationProps(_ref) {
  var cacheItem = _ref.cacheItem,
    useStartTime = _ref.useStartTime,
    currentResource = _ref.currentResource,
    slice = _ref.slice;
  var _cacheItem = cacheItem;
  return {
    startDate: dayjs(dayjs(_cacheItem._extend.start_date).format('YYYY-MM-DD ') + (getServeStartTime(useStartTime) || '00:00')),
    usableTime: getUsableTime(cacheItem),
    duration: getDuration(_cacheItem === null || _cacheItem === void 0 ? void 0 : _cacheItem.duration),
    locale: locales.locale,
    slice: slice,
    selectProps: {
      size: 'large'
    }
  };
};

/**
 * @title: 灵活时长选项
 * @description:
 * @param {*} useMemo
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-02-23 10:10
 */
export var getFlexibleOption = function getFlexibleOption(_ref2) {
  var cacheItem = _ref2.cacheItem,
    useStartTime = _ref2.useStartTime,
    currentResource = _ref2.currentResource,
    slice = _ref2.slice,
    durationProps = _ref2.durationProps;
  var _durationProps = durationProps || getDurationProps({
    cacheItem: cacheItem,
    useStartTime: useStartTime,
    currentResource: currentResource,
    slice: slice
  });
  var _duration = _durationProps.duration;
  if (_duration === 'flexible') {
    var _durationProps$usable, _durationProps$usable2;
    // 获取结束时间
    var endDate = getEndDate(_durationProps.startDate, _duration, (_durationProps$usable = _durationProps.usableTime) !== null && _durationProps$usable !== void 0 && (_durationProps$usable = _durationProps$usable._extend) !== null && _durationProps$usable !== void 0 && (_durationProps$usable = _durationProps$usable.usableTime) !== null && _durationProps$usable !== void 0 && _durationProps$usable.end_at ? dayjs((_durationProps$usable2 = _durationProps.usableTime) === null || _durationProps$usable2 === void 0 || (_durationProps$usable2 = _durationProps$usable2._extend) === null || _durationProps$usable2 === void 0 || (_durationProps$usable2 = _durationProps$usable2.usableTime) === null || _durationProps$usable2 === void 0 ? void 0 : _durationProps$usable2.end_at) : null);
    // 转换为分钟
    var timeValue = endDate.diff(_durationProps.startDate, 'minute');
    return {
      label: locales.getText('pisell2.text.flexible'),
      value: flexibleObj.create(timeValue)
    };
  }
  return null;
};
export var getTimeSlices = function getTimeSlices(_ref3) {
  var _state$bookingConfig;
  var state = _ref3.state;
  var obj = sliceDayIntoFiveMinutes((_state$bookingConfig = state.bookingConfig) === null || _state$bookingConfig === void 0 || (_state$bookingConfig = _state$bookingConfig.config) === null || _state$bookingConfig === void 0 || (_state$bookingConfig = _state$bookingConfig.basic) === null || _state$bookingConfig === void 0 ? void 0 : _state$bookingConfig.service_time, locales.locale);
  var timeSlices = _toConsumableArray(obj.timeSlices);
  return {
    timeSlices: timeSlices
  };
};

/**
 * @title: 时间切片
 * @description:
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-01-09 13:37
 */
export var getTimeObj = function getTimeObj(_ref4) {
  var _state$bookingConfig2;
  var cacheItem = _ref4.cacheItem,
    useStartTime = _ref4.useStartTime,
    currentResource = _ref4.currentResource,
    state = _ref4.state,
    useDuration = _ref4.useDuration,
    durationProps = _ref4.durationProps;
  var flexibleOption = getFlexibleOption({
    cacheItem: cacheItem,
    useStartTime: useStartTime,
    currentResource: currentResource,
    // 没有使用该参数
    // state,
    durationProps: durationProps
  });
  var obj = sliceDayIntoFiveMinutes((_state$bookingConfig2 = state.bookingConfig) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.config) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.basic) === null || _state$bookingConfig2 === void 0 ? void 0 : _state$bookingConfig2.service_time, locales.locale);
  var timeSlices = _toConsumableArray(obj.timeSlices);
  var durationSlicesBasedOnTime = _toConsumableArray(obj.durationSlicesBasedOnTime);

  // 如果商品是灵活时长, 则增加灵活的选项
  if (flexibleOption) {
    durationSlicesBasedOnTime.unshift(flexibleOption);
  }

  // 如果当前设置的时长没有在列表内, 则在列表的最上面添加此项
  if (useDuration && !durationSlicesBasedOnTime.some(function (d) {
    return d.value === useDuration;
  })) {
    durationSlicesBasedOnTime.unshift({
      label: getDiscountTime(useDuration),
      value: useDuration,
      //@ts-ignore
      disabled: true
    });
  }
  return _objectSpread(_objectSpread({}, obj), {}, {
    timeSlices: timeSlices,
    durationSlicesBasedOnTime: durationSlicesBasedOnTime
  });
};

/**
 * @title: 获取资源列表
 * @description:
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-01-09 13:38
 */
export var formatResources = function formatResources(_ref5) {
  var cacheItem = _ref5.cacheItem,
    resourcesOrigin = _ref5.resourcesOrigin,
    id = _ref5.id;
  try {
    // 合并无资源
    var _list = [];
    var maps = {};
    var _cacheItem = cacheItem;
    _list = resourcesOrigin.map(function (item) {
      var renderListMaps = {};
      // 深拷贝item
      var _item = cloneDeep(item);
      _item.renderList = _item.renderList.map(function (d) {
        var res = formatResource(d, _cacheItem, function (newData) {
          var unbound = !item.optional_resource.includes(newData.id) && !item.default_resource.includes(newData.id) && newData.id !== 0;
          return /*#__PURE__*/React.createElement("div", {
            className: "resource-option"
          }, /*#__PURE__*/React.createElement("div", {
            className: "like-wrap"
          }), /*#__PURE__*/React.createElement("span", {
            className: "resource-option-label-text"
          }, newData.labelText), (!newData.usable || unbound) && /*#__PURE__*/React.createElement(AlertTriangle, {
            className: "resource-option-alert-icon"
          }));
        });
        // 平行资源日历拖拽需求
        // 当拖入为绑定的资源中时，为了展示，会临时创建目标资源对应的resourceItem
        // 但是在 item.optional_resource 中并不包含目标资源id
        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(function (a, b) {
        return b.usable ? 1 : -1;
      });
      maps[_item.form_id] = _objectSpread(_objectSpread({}, _item), {}, {
        renderListMaps: renderListMaps
      });
      return _item;
    });
    return {
      list: _list,
      maps: maps
    };
  } catch (err) {
    console.log('formatResourcesErr', err);
  }
  return {
    list: [],
    maps: []
  };
};

// 取可用资源空闲时长最大的
var getResourceMaxFreeTime = function getResourceMaxFreeTime(resource) {
  var renderList = resource.renderList,
    form_id = resource.form_id;
  if (!getAutoAllocationStorage(form_id)) {
    return [];
  }
  // 可用列表
  var usableList = renderList.filter(function (d) {
    return d.usable && d.id !== 0;
  });
  var defaultResource = [];
  var maxFreeTime = 0;
  usableList.forEach(function (d) {
    var times = d.times;
    var currentMaxFreeTime = times.reduce(function (pre, cur) {
      var _cur$event_list, _cur$event_list2;
      // 开始时间使用预约的最后时间或者资源开始时间
      var start = ((_cur$event_list = cur.event_list) === null || _cur$event_list === void 0 || (_cur$event_list = _cur$event_list[((_cur$event_list2 = cur.event_list) === null || _cur$event_list2 === void 0 ? void 0 : _cur$event_list2.length) - 1]) === null || _cur$event_list === void 0 ? void 0 : _cur$event_list.end_at) || cur.start_at;
      // 结束时间使用资源结束时间
      var end = cur.end_at;
      var diff = dayjs(end).diff(dayjs(start), 'minute');
      return diff > pre ? diff : pre;
    }, 0);
    if (currentMaxFreeTime > maxFreeTime) {
      maxFreeTime = currentMaxFreeTime;
      defaultResource = [d];
    }
  });
  return defaultResource;
};
export var setDefaultResource = function setDefaultResource(_ref6) {
  var cacheItem = _ref6.cacheItem,
    resources = _ref6.resources;
  // if (resourceId || resourceId === 0) {
  //   // 校验, 如果当前选择的资源 在列表里没找到, 则恢复成无资源, 防止数据错乱
  //   if (!resources.find((d: any) => d.form_record_id === resourceId)) {
  //     resourceId = undefined;
  //   }
  // } else {
  var obj = {};

  // const { relation_type, item_id, schedule_id } =
  // currentResource?._extend?.usableTime || {};
  // _extend.relation_type = relation_type || 'form';
  // _extend.relation_id = item_id || currentResource?.form_record_id || 0;
  // _extend.schedule_id = schedule_id || 0;

  var serviceParams = getCacheParams();

  // 从日历选中资源
  var resourceId = Number(serviceParams === null || serviceParams === void 0 ? void 0 : serviceParams.resource_id);
  var _iterator = _createForOfIteratorHelper(resources),
    _step;
  try {
    var _loop2 = function _loop2() {
      var item = _step.value;
      var _item$select_type = item.select_type,
        select_type = _item$select_type === void 0 ? {} : _item$select_type,
        _item$optional_resour = item.optional_resource,
        optional_resource = _item$optional_resour === void 0 ? [] : _item$optional_resour,
        _item$default_resourc = item.default_resource,
        default_resource = _item$default_resourc === void 0 ? [] : _item$default_resourc;
      var renderList = item.renderList.filter(function (d) {
        if ((select_type === null || select_type === void 0 ? 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;
        } else {
          // 多选
          return d.is_default === 1 || d.id === resourceId;
        }
      });
      var defaultOriginalResource = [];
      if (renderList.length === 0) {
        defaultOriginalResource = getResourceMaxFreeTime(item);
      } else {
        defaultOriginalResource = renderList;
      }
      var defaultResource = defaultOriginalResource.map(function (d) {
        return {
          // ...d,
          children: d.children,
          relation_type: d.relation_type,
          form_id: item.form_id,
          relation_id: d.id,
          like_status: 'common',
          // 新添加的数据补充错误信息
          errors: getErrorList(d, cacheItem),
          metadata: {
            form_name: item.title,
            resource_name: d.main_field
          }
        };
      });
      obj[item.form_id] = defaultResource;
    };
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      _loop2();
    }
    // }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return obj;
};

/**
 * @title: 设置默认容量
 * @description:
 * @param {any} param1
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-09-19 20:26
 */
export var setDefaultCapacitys = function setDefaultCapacitys(_ref7) {
  var capacitys = _ref7.capacitys,
    cacheItem = _ref7.cacheItem;
  if ((capacitys === null || capacitys === void 0 ? void 0 : capacitys.type) === 'package') {
    var _cacheItem$_extend;
    return ((cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend = cacheItem._extend) === null || _cacheItem$_extend === void 0 || (_cacheItem$_extend = _cacheItem$_extend.other) === null || _cacheItem$_extend === void 0 ? void 0 : _cacheItem$_extend.bundle) || []).map(function (d) {
      var id = d._bundle_product_id;
      var item = ((capacitys === null || capacitys === void 0 ? void 0 : capacitys.package) || []).find(function (item) {
        return item.product_id === id;
      });
      return {
        id: id,
        value: item ? d.quantity || 0 : 0,
        name: (item === null || item === void 0 ? void 0 : item.name) || (d === null || d === void 0 ? void 0 : d.title)
      };
    });
  }
  if ((capacitys === null || capacitys === void 0 ? void 0 : capacitys.type) === 'custom') {
    return ((capacitys === null || capacitys === void 0 ? void 0 : capacitys.custom) || []).map(function (d) {
      return {
        id: d.id,
        value: d.min,
        name: d.name
      };
    });
  }

  // 默认为1
  return [{
    id: 0,
    value: 1,
    name: ''
  }];
};

/**
 * @title: 将商品内关联的资源id还原成数据
 * @description:
 * @param {any} resourcesOriginMap
 * @param {any} cacheItem
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-09-19 20:23
 */
export var getResourceByIds = function getResourceByIds(resourcesOriginMap, cacheItem, extraParams) {
  var _cacheItem$product_re;
  var _resources = _toConsumableArray((cacheItem === null || cacheItem === void 0 || (_cacheItem$product_re = cacheItem.product_resource) === null || _cacheItem$product_re === void 0 ? void 0 : _cacheItem$product_re.resources) || []);
  var _ref8 = extraParams || {},
    _ref8$extraResources = _ref8.extraResources,
    extraResources = _ref8$extraResources === void 0 ? [] : _ref8$extraResources,
    _ref8$resourcesOrigin = _ref8.resourcesOrigin,
    resourcesOrigin = _ref8$resourcesOrigin === void 0 ? [] : _ref8$resourcesOrigin,
    _ref8$resourceTab = _ref8.resourceTab,
    resourceTab = _ref8$resourceTab === void 0 ? {} : _ref8$resourceTab;
  // 过滤出开启的资源
  _resources = _resources.filter(function (d) {
    return d.status == 1;
  });
  var _iterator2 = _createForOfIteratorHelper(_resources),
    _step2;
  try {
    var _loop3 = function _loop3() {
      var _resourceTab$item$cod;
      var item = _step2.value;
      var form_id = item.id;
      // resource_tab -> 每个资源类型 -> resource_display_scope  { only_linked: '仅显示已关联资源' ｜ all: '全部' } 默认值 ‘only_linked’
      var isAllResource = (resourceTab === null || resourceTab === void 0 || (_resourceTab$item$cod = resourceTab[item.code]) === null || _resourceTab$item$cod === void 0 ? void 0 : _resourceTab$item$cod.resource_display_scope) === 'all';

      // 将未绑定的资源，也放入 SelectOption 列表，避免出现仅展示id的情况
      var extraResourceIds = [];

      // 如果设置了全部资源 需要把未关联的资源进行补全
      if (isAllResource) {
        extraResourceIds = (resourcesOrigin || []).filter(function (d) {
          return d.form_code === item.code;
        }).map(function (d) {
          return d.id;
        });
      } else {
        extraResourceIds = extraResources.filter(function (_extraItem) {
          return _extraItem.form_id === form_id && !!_extraItem.id && !item.optional_resource.includes(_extraItem.id) && !item.default_resource.includes(_extraItem.id);
        }).map(function (_extraItem) {
          return _extraItem.id;
        });
      }
      extraResourceIds = Array.from(new Set(extraResourceIds));

      // 去重
      item.optional_resource = (item.optional_resource || []).filter(function (d) {
        return item.default_resource.indexOf(d) == -1;
      });
      var getChildrenMetadata = function getChildrenMetadata(d) {
        var combiningResources = [];
        if (resourcesOriginMap[d].combined_resource && resourcesOriginMap[d].combined_resource.status === 1) {
          resourcesOriginMap[d].combined_resource.resource_ids.forEach(function (id) {
            if (resourcesOriginMap[id]) {
              var _resourcesOriginMap$i, _resourcesOriginMap$i2;
              combiningResources.push(_objectSpread(_objectSpread({}, resourcesOriginMap[id]), {}, {
                relation_id: ((_resourcesOriginMap$i = resourcesOriginMap[id]) === null || _resourcesOriginMap$i === void 0 ? void 0 : _resourcesOriginMap$i.relation_id) || ((_resourcesOriginMap$i2 = resourcesOriginMap[id]) === null || _resourcesOriginMap$i2 === void 0 ? void 0 : _resourcesOriginMap$i2.id)
              }));
            }
          });
        }
        return {
          children: combiningResources,
          metadata: _objectSpread(_objectSpread({}, resourcesOriginMap[d].metadata), {}, {
            combined_resource: resourcesOriginMap[d].combined_resource
          })
        };
      };

      // 可选项
      var optional_resource = Array.from(new Set([].concat(_toConsumableArray(item.optional_resource), _toConsumableArray(extraResourceIds)))).map(function (d) {
        if (!resourcesOriginMap[d]) {
          return null;
        }
        return Object.assign({}, resourcesOriginMap[d], _objectSpread({
          form_id: form_id,
          resourceType: item.type
        }, getChildrenMetadata(d)));
      }).filter(function (d) {
        return d;
      }).concat(getNoResource2({
        form_id: form_id
      }));

      // 默认项
      var default_resource = item.default_resource.map(function (d) {
        var item = resourcesOriginMap[d];
        if (item) {
          item.is_default = 1;
          return Object.assign({}, item, _objectSpread({
            form_id: form_id,
            resourceType: item.type
          }, getChildrenMetadata(d)));
        } else {
          return null;
        }
      }).filter(function (d) {
        return d;
      });

      // 合并渲染
      item.renderList = optional_resource.concat(default_resource);

      // 统一字段 将id改为form_id
      item.form_id = form_id;
    };
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      _loop3();
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
  console.log('_resources', _resources);
  return _resources;
};
var getIsAutoClose = function getIsAutoClose(cacheItem) {
  var _cacheItem$_data;
  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;
    if ((cacheItem === null || cacheItem === void 0 || (_cacheItem$_data2 = cacheItem._data) === null || _cacheItem$_data2 === void 0 ? void 0 : _cacheItem$_data2.resources.length) === 1) {
      var _cacheItem$_data3, _first$select_type;
      var first = cacheItem === null || cacheItem === void 0 || (_cacheItem$_data3 = cacheItem._data) === null || _cacheItem$_data3 === void 0 ? void 0 : _cacheItem$_data3.resources[0];
      if (((_first$select_type = first.select_type) === null || _first$select_type === void 0 ? void 0 : _first$select_type.type) === 'single') {
        if (first.default_resource.length > 0) {
          return true;
        }
      }
    }
  }
  return Object.entries(cacheItem._extend.resource).every(function (_ref9) {
    var _ref10 = _slicedToArray(_ref9, 2),
      key = _ref10[0],
      value = _ref10[1];
    return getAutoAllocationStorage(key) && (value === null || value === void 0 ? void 0 : value.length);
  });
};

/**
 * @title: 预生成服务的 extend
 * @description:
 * @param {any} param1
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-06-01 13:25
 */
export var getProductExtend = function getProductExtend(_ref11) {
  var cacheItem = _ref11.cacheItem,
    state = _ref11.state,
    isDisabledTime = _ref11.isDisabledTime;
  // 有endDate 说明是在编辑已经保存过的商品, 没有则是编辑还没保存过的商品
  var isNew = cacheItem.new || !cacheItem._extend.endDate;
  var _cacheItem = _objectSpread({}, cacheItem);

  // 资源总列表
  var resourcesOriginMap = state.service.resourcesOriginMap || {};
  // const resourcesOrigin = state.s;

  _cacheItem._data = {};

  // 新商品
  if (isNew) {
    var _state$bookingConfig3;
    // 时间切片
    _cacheItem._data.timeObj = getTimeObj({
      cacheItem: cacheItem,
      currentResource: null,
      state: state
    });

    // 生成开始时间和时长
    _cacheItem._extend = getServiceStartTimeAndEndTime(state, cacheItem, _cacheItem._data.timeObj);

    // 容量
    _cacheItem._data.capacitys = cacheItem.capacity;

    // 将商品关联的资源id还原资源列表
    _cacheItem._data.resourcesOrigin = getResourceByIds(resourcesOriginMap, cacheItem, {
      //  此数据用来控制 该商品所展示的资源是自身关联的,  还是全部的
      resourceTab: state === null || state === void 0 || (_state$bookingConfig3 = state.bookingConfig) === null || _state$bookingConfig3 === void 0 || (_state$bookingConfig3 = _state$bookingConfig3.config) === null || _state$bookingConfig3 === void 0 ? void 0 : _state$bookingConfig3.resource_tab,
      resourcesOrigin: state.service.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
    });

    // let currentResource = _cacheItem._resources.find(
    //   (d: any) => d.form_record_id == cacheItem._extend.resource
    // );

    // 再次计算, 灵活时长
    if (getDuration(_cacheItem === null || _cacheItem === void 0 ? void 0 : _cacheItem.duration)) {
      _cacheItem._data.timeObj = getTimeObj({
        cacheItem: _cacheItem,
        useStartTime: _cacheItem._extend.start_time,
        currentResource: _cacheItem._extend.resource,
        state: state
      });
      if (getDuration(_cacheItem === null || _cacheItem === void 0 ? void 0 : _cacheItem.duration) === 'flexible') {
        var _cacheItem$_data$time;
        _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 _getServiceTimes = getServiceTimes({
            _extend: _cacheItem._extend
          }),
          startDate = _getServiceTimes.startDate,
          endDate = _getServiceTimes.endDate;
        _cacheItem._extend.endDate = endDate;
      }
    }

    // 如果只有一种类型的资源 & 单选，还按照之前的逻辑处理：自动选中，不会打开Edit service抽屉。
    // 或
    // 如果开启自动分派 并且 资源列表中每个资源都有默认值，自动关闭。
    _cacheItem.autoClose = getIsAutoClose(_cacheItem);
    if (_cacheItem._extend.bundle_edit !== undefined) {
      _cacheItem._extend.bundle_edit = 1;
    }
    if (!isDisabledTime) {
      _cacheItem._time = new Date().getTime();
    }
  } else {
    // if (!_cacheItem._data.timeObj) {
    // _cacheItem._data.timeObj = getTimeObj({
    //   cacheItem: _cacheItem,
    //   currentResource: _cacheItem._extend.resource,
    //   state,
    // });
    // }

    if (!_cacheItem._data.capacitys) {
      // 容量
      _cacheItem._data.capacitys = cacheItem.capacity;
    }
    if (!_cacheItem._data.resourcesOrigin) {
      var _state$bookingConfig4;
      var extraResources = [];
      // 日历中可以将预约拖入未绑定的资源中，需要兼容未绑定资源的 selectOption展示
      if (Array.isArray(_cacheItem._extend.event_resources)) {
        _cacheItem._extend.event_resources.forEach(function (_item) {
          extraResources.push({
            form_id: _item.form_id,
            id: _item.relation_id
          });
        });
      }
      _cacheItem._data.resourcesOrigin = getResourceByIds(resourcesOriginMap, cacheItem, {
        extraResources: extraResources,
        //  此数据用来控制 该商品所展示的资源是自身关联的,  还是全部的
        resourceTab: state === null || state === void 0 || (_state$bookingConfig4 = state.bookingConfig) === null || _state$bookingConfig4 === void 0 || (_state$bookingConfig4 = _state$bookingConfig4.config) === null || _state$bookingConfig4 === void 0 ? void 0 : _state$bookingConfig4.resource_tab,
        resourcesOrigin: state.service.resourcesOrigin
      });
    }
    if (!_cacheItem._data.resources) {
      // 资源
      var _formatResources2 = formatResources({
          cacheItem: _cacheItem,
          resourcesOrigin: _cacheItem._data.resourcesOrigin
        }),
        _list2 = _formatResources2.list,
        _maps = _formatResources2.maps;
      _cacheItem._data.resources = _list2;
      _cacheItem._data.resourceMaps = _maps;
    }

    // if (!_cacheItem._data.timeObj) {
    _cacheItem._data.timeObj = getTimeObj({
      cacheItem: _cacheItem,
      useStartTime: _cacheItem._extend.start_time,
      currentResource: _cacheItem._extend.resource,
      state: state
    });
    // }
  }
  console.log('_cacheItem_cacheItem', _cacheItem);
  return _cacheItem;
};

/**
 * @title: 格式化服务列表
 * @description: 后端列表返回的product_resource.resources 的optional_resource等不是最新数据
 * 使用with resourceRelation后 返回的resource_relation是实时数据
 * 这里做一次转换
 * @param list
 */
export var transServiceList = function transServiceList(list) {
  return list.map(function (item) {
    var _item$product_resourc;
    return _objectSpread(_objectSpread({}, item), {}, {
      product_resource: _objectSpread(_objectSpread({}, item.product_resource), {}, {
        resources: (item === null || item === void 0 ? void 0 : item.resource_relation) || (item === null || item === void 0 || (_item$product_resourc = item.product_resource) === null || _item$product_resourc === void 0 ? void 0 : _item$product_resourc.resources)
      })
    });
  });
};