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 _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 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 _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 _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 _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 { cloneDeep } from 'lodash-es';
import { flexibleObj } from "./flexible";
import { getNoResource2 } from "./noResource";
import { getServeStartTime } from "./serviceTimes";

/**
 * 资源运行态计算 helper（搬自 info2 `utilsByBooking.ts` + `service/addService/utils.tsx`）。
 *
 * 本文件输入输出全部为 plain object，不依赖 React / locales / @pisell/icon / mini-redux。
 * 调用方传入：resource origin map（`/form/schedule` 返回） / cacheItem（含 `_extend.duration / _extend.start_date / _extend.start_time` 等）。
 *
 * 三个 info2 独有特性保留：
 *   1. `resource_display_scope='all'`：取全部资源
 *   2. `extraResources`：拖入未绑定资源时兼容渲染
 *   3. `getNoResource2()`：占位"无资源"行
 */

/**
 * 从已选资源中取「最早结束」的 usableTime，供灵活时长计算上限。
 * 与 info2 `service/addService/utils.tsx#getUsableTime` 等价。
 */
export function getUsableTime(cacheItem) {
  try {
    var _cacheItem$_extend, _cacheItem$_data;
    var resourceByForm = (cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend = cacheItem._extend) === null || _cacheItem$_extend === void 0 ? void 0 : _cacheItem$_extend.resource) || {};
    var resourceMaps = (cacheItem === null || cacheItem === void 0 || (_cacheItem$_data = cacheItem._data) === null || _cacheItem$_data === void 0 ? void 0 : _cacheItem$_data.resourceMaps) || {};
    var items = [];
    var _loop = function _loop() {
      var _resourceMaps$formId;
      var formId = _Object$keys[_i];
      var selected = resourceByForm[formId];
      var maps = (_resourceMaps$formId = resourceMaps[formId]) === null || _resourceMaps$formId === void 0 ? void 0 : _resourceMaps$formId.renderListMaps;
      if (!Array.isArray(selected) || !maps) return 1; // continue
      items = items.concat(selected.map(function (d) {
        return maps[d.relation_id];
      }).filter(Boolean));
    };
    for (var _i = 0, _Object$keys = Object.keys(resourceByForm); _i < _Object$keys.length; _i++) {
      if (_loop()) continue;
    }
    if (!items.length) return null;
    return 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);
      var preEnd = dayjs((_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);
      return endAt.isBefore(preEnd) ? event : pre;
    }, items[0]);
  } catch (_unused) {
    return null;
  }
}

/** Σ cacheItem._extend.capacity[].value × _extend.quantity。 */
export function getSumCapacity(cacheItem) {
  var _cacheItem$_extend2, _cacheItem$_extend3;
  var isCalcQuantity = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : true;
  var list = (cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend2 = cacheItem._extend) === null || _cacheItem$_extend2 === void 0 ? void 0 : _cacheItem$_extend2.capacity) || [];
  var sum = 0;
  var _iterator = _createForOfIteratorHelper(list),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var item = _step.value;
      sum += Number((item === null || item === void 0 ? void 0 : item.value) || 0);
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return sum * (isCalcQuantity ? (cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend3 = cacheItem._extend) === null || _cacheItem$_extend3 === void 0 ? void 0 : _cacheItem$_extend3.quantity) || 1 : 1);
}

/** 当前 time 剩余容量 = totalCapacity - Σ event.pax。 */
function getUseableEventCount(eventList, current) {
  return (eventList || []).reduce(function (pre, event) {
    return pre - ((event === null || event === void 0 ? void 0 : event.pax) || 0);
  }, current || 0);
}

/** 判断两个时间段是否有冲突。 */
function isConflict(event, current) {
  var eventStart = dayjs(event.start_at);
  var eventEnd = dayjs(event.end_at);
  var currentStart = dayjs(current.start_at);
  var isBefore = currentStart.isBefore(eventEnd);
  var isAfter = true;
  if (current.end_at) {
    var currentEnd = dayjs(current.end_at);
    isAfter = currentEnd.isAfter(eventStart);
  }
  return isBefore && isAfter;
}

/**
 * 判断单个 time 是否可用，写回 `_extend` 标记位（isDateRange / isCountRange / isUsable / isMaxLimitRange）。
 * 与 info2 `utilsByBooking.ts#getResourceTimeIsUsable` 等价。
 */
export function getResourceTimeIsUsable(item, cacheItem, resourceItem) {
  var startDate = dayjs("".concat(dayjs(cacheItem._extend.start_date).format('YYYY-MM-DD'), " ").concat(getServeStartTime(cacheItem._extend.start_time)));
  var isFlexible = flexibleObj.isFlexible(cacheItem._extend.duration);
  var isMaxLimitRange = false;
  var isDateRange = false;
  var isCountRange = false;
  var time = _objectSpread({}, item);
  var timeStartDate = dayjs("".concat(time.start_date, " ").concat(time.start_time)).subtract(1, 'second');
  var timeEndDate = dayjs("".concat(time.end_date, " ").concat(time.end_time)).add(1, 'second');
  var totalCount = getUseableEventCount(time.event_list, resourceItem.capacity);
  var currentCount = getSumCapacity(cacheItem);
  var eventList = time.event_list || [];
  if (cacheItem !== null && cacheItem !== void 0 && cacheItem.booking_id) {
    eventList = eventList.filter(function (event) {
      return event.id !== cacheItem.booking_id;
    });
  }
  var endDate = null;
  var isCalcCount = true;
  if (isFlexible) {
    isDateRange = startDate.isAfter(timeStartDate) && startDate.isBefore(timeEndDate);
    if (!isDateRange && eventList.length) {
      isCalcCount = false;
      isDateRange = true;
      isCountRange = false;
    }
  } else {
    endDate = startDate.add(flexibleObj.getValue(cacheItem._extend.duration), 'minute');
    var isTimeRange = startDate.isAfter(timeStartDate) && endDate.isBefore(timeEndDate);
    if (isTimeRange) isDateRange = true;
  }
  if (isCalcCount) {
    var conflict = (eventList || []).filter(function (d) {
      return isConflict({
        start_at: d.start_at,
        end_at: d.end_at
      }, {
        start_at: startDate,
        end_at: endDate
      });
    });
    if (resourceItem.resourceType === 'single') {
      isCountRange = conflict.length === 0;
    } else {
      var conflictCount = getUseableEventCount(conflict, resourceItem.capacity);
      isCountRange = currentCount <= conflictCount;
      // totalCount 当前未直接参与判定，保留 reference 以与原版接近。
      void totalCount;
    }
  }
  var isUsable = isDateRange && isCountRange;
  time._extend = {
    isMaxLimitRange: isMaxLimitRange,
    isDateRange: isDateRange,
    isCountRange: isCountRange,
    isUsable: isUsable
  };
  return time;
}

/**
 * 在 resource.times 中找到最佳可用 time，并写回 `_extend.usableTime`。
 * 与 info2 `utilsByBooking.ts#formatTimes` 等价。
 */
export function formatTimes(resourceItem, cacheItem) {
  var usableTimes = [];
  var _resourceItem = _objectSpread({}, resourceItem);
  var sum = getSumCapacity(cacheItem);
  if (_resourceItem.capacity >= sum) {
    _resourceItem.times = (_resourceItem.times || []).map(function (time) {
      var _time$_extend;
      var _time = getResourceTimeIsUsable(time, cacheItem, _resourceItem);
      if (_time !== null && _time !== void 0 && (_time$_extend = _time._extend) !== null && _time$_extend !== void 0 && _time$_extend.isDateRange) usableTimes.push(_time);
      return _time;
    });
  }
  var _time = usableTimes.sort(function (a, b) {
    var aEnd = dayjs("".concat(a.end_date, " ").concat(a.end_time)).valueOf();
    var bEnd = dayjs("".concat(b.end_date, " ").concat(b.end_time)).valueOf();
    return aEnd - bEnd;
  })[0];
  resourceItem._extend = _objectSpread(_objectSpread({}, resourceItem._extend), {}, {
    usableTime: _time
  });
  return resourceItem;
}

/**
 * 单个 resource 的整体可用性 + labelText 填充。
 * 与 info2 `utilsByBooking.ts#formatResource` 等价；不再接收 formatLabel 回调（OS 不渲染 JSX）。
 */
export function formatResource(resourceItem, cacheItem) {
  var _resourceItem$_extend;
  var _resourceItem = _objectSpread({}, resourceItem);
  _resourceItem = formatTimes(_resourceItem, cacheItem);
  _resourceItem.labelText = _resourceItem.main_field;
  var usable = (_resourceItem$_extend = _resourceItem._extend) === null || _resourceItem$_extend === void 0 || (_resourceItem$_extend = _resourceItem$_extend.usableTime) === null || _resourceItem$_extend === void 0 || (_resourceItem$_extend = _resourceItem$_extend._extend) === null || _resourceItem$_extend === void 0 ? void 0 : _resourceItem$_extend.isUsable;
  _resourceItem.usable = usable;
  return _resourceItem;
}

/**
 * 把单个 resource origin 类型（如「技师」）的 renderList 中每个资源跑一遍 formatResource，
 * 并维护 unbound 标记（拖入未绑定资源时 UI 用）。
 * 与 info2 `service/addService/utils.tsx#formatResources` 等价（剥 JSX）。
 */
export function formatResources(params) {
  var cacheItem = params.cacheItem,
    resourcesOrigin = params.resourcesOrigin;
  try {
    var maps = {};
    var list = resourcesOrigin.map(function (item) {
      var _item = cloneDeep(item);
      var renderListMaps = {};
      _item.renderList = _item.renderList.map(function (d) {
        var res = formatResource(d, cacheItem);
        var unbound = !item.optional_resource.includes(res.id) && !item.default_resource.includes(res.id) && res.id !== 0;
        if (unbound) res.unbound = true;
        renderListMaps[res.id] = res;
        return res;
      }).sort(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.warn('[BookingContext] formatResources error', err);
    return {
      list: [],
      maps: {}
    };
  }
}

/** 取可用资源中"最大空闲时长"的那一个，作为自动分派候选。 */
function getResourceMaxFreeTime(resource, isAutoAllocationOn) {
  var renderList = resource.renderList,
    form_id = resource.form_id;
  if (!isAutoAllocationOn(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 _d$times = d.times,
      times = _d$times === void 0 ? [] : _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;
}

/**
 * 计算每类资源的默认值（写入 cacheItem._extend.resource）。
 * 与 info2 `service/addService/utils.tsx#setDefaultResource` 等价；
 * `resourceIdFromCalendar` 替代原版 sessionStorage `serviceParams.resource_id` 读取。
 */
export function setDefaultResource(params) {
  var cacheItem = params.cacheItem,
    resources = params.resources,
    resourceIdFromCalendar = params.resourceIdFromCalendar,
    _params$isAutoAllocat = params.isAutoAllocationOn,
    isAutoAllocationOn = _params$isAutoAllocat === void 0 ? function () {
      return true;
    } : _params$isAutoAllocat;
  var obj = {};
  var resourceId = Number(resourceIdFromCalendar) || 0;
  var _iterator2 = _createForOfIteratorHelper(resources),
    _step2;
  try {
    var _loop2 = function _loop2() {
      var item = _step2.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;
        }
        return d.is_default === 1 || d.id === resourceId;
      });
      var defaultOriginalResource = [];
      if (renderList.length === 0) {
        defaultOriginalResource = getResourceMaxFreeTime(item, isAutoAllocationOn);
      } else {
        defaultOriginalResource = renderList;
      }
      obj[item.form_id] = defaultOriginalResource.map(function (d) {
        return {
          children: d.children,
          relation_type: d.relation_type,
          form_id: item.form_id,
          relation_id: d.id,
          like_status: 'common',
          metadata: {
            form_name: item.title,
            resource_name: d.main_field
          }
        };
      });
      // errors 字段由调用方在需要时通过 getResourceErrors 单独算，OS 这里不耦合。
    };
    for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
      _loop2();
    }
  } catch (err) {
    _iterator2.e(err);
  } finally {
    _iterator2.f();
  }
  return obj;
}

/**
 * 计算默认容量（与 info2 `setDefaultCapacitys` 等价）。
 * package：按 _extend.other.bundle 拆 quantity；custom：按 capacity.custom[].min；其他：[{id:0,value:1}]。
 */
export function setDefaultCapacitys(params) {
  var capacitys = params.capacitys,
    cacheItem = params.cacheItem;
  if ((capacitys === null || capacitys === void 0 ? void 0 : capacitys.type) === 'package') {
    var _cacheItem$_extend4;
    return ((cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend4 = cacheItem._extend) === null || _cacheItem$_extend4 === void 0 || (_cacheItem$_extend4 = _cacheItem$_extend4.other) === null || _cacheItem$_extend4 === void 0 ? void 0 : _cacheItem$_extend4.bundle) || []).map(function (d) {
      var id = d._bundle_product_id;
      var item = ((capacitys === null || capacitys === void 0 ? void 0 : capacitys.package) || []).find(function (p) {
        return p.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
      };
    });
  }
  return [{
    id: 0,
    value: 1,
    name: ''
  }];
}

/**
 * 通过商品 `product_resource.resources[]` 关联的 form/resource id，从 resourcesOriginMap 还原资源数据。
 * 与 info2 `service/addService/utils.tsx#getResourceByIds` 等价（保留三特性）。
 */
export 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) || []).filter(function (d) {
    return Number(d === null || d === void 0 ? void 0 : d.status) === 1;
  }).map(function (item) {
    return _objectSpread({}, item);
  });
  var _ref = extraParams || {},
    _ref$extraResources = _ref.extraResources,
    extraResources = _ref$extraResources === void 0 ? [] : _ref$extraResources,
    _ref$resourcesOrigin = _ref.resourcesOrigin,
    resourcesOrigin = _ref$resourcesOrigin === void 0 ? [] : _ref$resourcesOrigin,
    _ref$resourceTab = _ref.resourceTab,
    resourceTab = _ref$resourceTab === void 0 ? {} : _ref$resourceTab;
  var _iterator3 = _createForOfIteratorHelper(_resources),
    _step3;
  try {
    var _loop3 = function _loop3() {
      var _resourceTab$item$cod;
      var item = _step3.value;
      var form_id = item.id;
      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';
      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(id) {
        var combiningResources = [];
        var origin = resourcesOriginMap[id];
        if (origin !== null && origin !== void 0 && origin.combined_resource && origin.combined_resource.status === 1) {
          (origin.combined_resource.resource_ids || []).forEach(function (cid) {
            if (resourcesOriginMap[cid]) {
              var _resourcesOriginMap$c, _resourcesOriginMap$c2;
              combiningResources.push(_objectSpread(_objectSpread({}, resourcesOriginMap[cid]), {}, {
                relation_id: ((_resourcesOriginMap$c = resourcesOriginMap[cid]) === null || _resourcesOriginMap$c === void 0 ? void 0 : _resourcesOriginMap$c.relation_id) || ((_resourcesOriginMap$c2 = resourcesOriginMap[cid]) === null || _resourcesOriginMap$c2 === void 0 ? void 0 : _resourcesOriginMap$c2.id)
              }));
            }
          });
        }
        return {
          children: combiningResources,
          metadata: _objectSpread(_objectSpread({}, (origin === null || origin === void 0 ? void 0 : origin.metadata) || {}), {}, {
            combined_resource: origin === null || origin === void 0 ? void 0 : origin.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 origin = resourcesOriginMap[d];
        if (origin) {
          origin.is_default = 1;
          return Object.assign({}, origin, _objectSpread({
            form_id: form_id,
            resourceType: item.type
          }, getChildrenMetadata(d)));
        }
        return null;
      }).filter(function (d) {
        return d;
      });
      item.renderList = optional_resource.concat(default_resource);
      item.form_id = form_id;
    };
    for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
      _loop3();
    }
  } catch (err) {
    _iterator3.e(err);
  } finally {
    _iterator3.f();
  }
  return _resources;
}