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 _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 _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 _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';

/**
 * @title: 格式化商品为二维结构
 * @description: 
 * @param {any} list
 * @param {any} filterItem
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-03-05 18:01
 */
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);
};

/**
 * @title: 获取背景色
 * @description: 
 * @param {string} colors
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-03-05 18:02
 */
export var formatBackgroundColors = function formatBackgroundColors(colors) {
  var _colors = Array.from(new Set(colors.map(function (color) {
    return color === null || color === void 0 ? void 0 : color.toLocaleLowerCase();
  }) || [])).filter(function (d) {
    return !!d;
  });
  var colorStr = _colors.map(function (color, index) {
    return "".concat(color, " ").concat(index * 100 / _colors.length, "% ").concat((index + 1) * 100 / _colors.length, "%");
  }).join(", ");
  if (colorStr) {
    return "conic-gradient(".concat(colorStr, ")");
  }
  return '';
};

/**
 * @title: 获取 schedules 的所有颜色
 * @description: 
 * @param {any} schedules
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-03-05 18:02
 */
export var getScheduleColors = function getScheduleColors(schedules) {
  return formatBackgroundColors(schedules.map(function (d) {
    return d.color;
  }));
};

/**
 * @title: 获取当前商品的最小开始时间和最大结束时间  --废弃
 * @description: 
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-03-05 18:02
 */
export var getProductMinTimeRangeStr = function getProductMinTimeRangeStr(_ref) {
  var schedules = _ref.schedules,
    product = _ref.product;
  // 商品关联的全部schedules的id列表
  var productScheduleIds = product['schedule.ids'] || [];
  // 从schedules 中获取完整数据
  var filterList = schedules.filter(function (d) {
    return true || productScheduleIds.includes(d.id);
  });
  var times = [];
  // 分别获取每个 schedule 的最小时间和最大时间
  var _iterator = _createForOfIteratorHelper(filterList),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var schedule = _step.value;
      times = times.concat(getMinTimeRangeBySchedule(schedule));
    }

    // 获取所有 schedule 中最小的时间和最大的时间
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return getMinTimeRangeStr(getMinTimeRange(times));
};

/**
 * @title: 获取数组内最小的时间和最大的时间
 * @description: 
 * @param {any} array
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-03-05 18:04
 */
export var getMinTimeRange = function getMinTimeRange(array) {
  if (!array.length) {
    return {
      minTime: '',
      maxTime: ''
    };
  }
  var minTime = array[0].minTime;
  var maxTime = array[0].maxTime;
  for (var i = 1; i < array.length; i++) {
    var startTime = array[i].minTime;
    var endTime = array[i].maxTime;
    if (startTime.isBefore(minTime)) {
      minTime = startTime;
    }
    if (endTime.isAfter(maxTime)) {
      maxTime = endTime;
    }
  }
  return {
    minTime: minTime,
    maxTime: maxTime
  };
};

/**
 * @title: 获取店铺的营业时间 开始-结束
 * @description: 
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-03-05 18:04
 */
export var getShopOpeningHoursRange = function getShopOpeningHoursRange() {
  var operating_day_boundary = {
    time: '23:59',
    type: "end_time"
  };
  if (localStorage.getItem('shopOpeningHoursObject')) {
    operating_day_boundary = JSON.parse(localStorage.getItem('shopOpeningHoursObject') || '');
  }
  var time = dayjs(operating_day_boundary.time, 'HH:mm');
  var type = operating_day_boundary.type;
  var startDate = dayjs(time);
  if (type === 'end_time') {
    startDate = startDate.subtract(1, 'days');
  }
  var startDay = dayjs(startDate);
  var endDate = dayjs(time).add(1, 'days').subtract(1, 'second');
  if (type === 'end_time') {
    endDate = endDate.subtract(1, 'days');
  }
  var endDay = dayjs(endDate);
  return {
    shopStartDate: startDay,
    shopEndDate: endDay,
    shopStartTime: startDay.format("HH:mm"),
    shopEndTime: endDay.format("HH:mm")
  };
};

/**
 * @title: 将时间范围格式化
 * @description: 
 * @param {any} range
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-03-05 18:05
 */
export var getMinTimeRangeStr = function getMinTimeRangeStr(range) {
  if (!range.minTime || !range.maxTime) {
    return '';
  }
  if (range.minTime.format("HH:mm") === '00:00' && range.maxTime.format("HH:mm") === '23:59') {
    return locales.getText('pisell2.text.schedules.all-day');
  }
  var _getShopOpeningHoursR = getShopOpeningHoursRange(),
    shopStartDate = _getShopOpeningHoursR.shopStartDate,
    shopEndDate = _getShopOpeningHoursR.shopEndDate;
  var minTime = '';
  var maxTime = '';

  // 开始时间和店铺营业时间相同 为 open
  if (range.minTime.format("YYYY-MM-DD HH:mm") === shopStartDate.format("YYYY-MM-DD HH:mm")) {
    minTime = 'open';
  } else {
    minTime = range.minTime.format("hh:mm a");
  }

  // 结束时间和店铺营业关门时间相同 为 close
  if (range.maxTime.format("YYYY-MM-DD HH:mm") === shopEndDate.format("YYYY-MM-DD HH:mm")) {
    maxTime = 'close';
  } else {
    maxTime = range.maxTime.format("hh:mm a");
  }
  return "".concat(minTime, " - ").concat(maxTime);
};

/**
 * @title: 获取可用的 schedule
 * @description: 
 * @param {any} schedule
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-03-05 18:05
 */
export var getUsableSchedules = function getUsableSchedules(schedule) {
  if (!schedule) {
    return true;
  }
  if (!schedule.minTime || !schedule.maxTime) {
    return false;
  }
  var currentDate = dayjs();
  // 如果最大时间在当前时间之前, 代表没有可用的日程
  if (currentDate.isAfter(schedule.maxTime)) {
    return false;
  }
  return true;
};

/**
 * @title: 获取单个 Schedule 内 最小的时间和最大的时间 --废弃
 * @description: 
 * @param {any} item
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-03-05 18:06
 */
export var getMinTimeRangeBySchedule = function getMinTimeRangeBySchedule(item) {
  var minTime = dayjs(),
    maxTime = dayjs();
  if (item.type === "standard") {
    minTime = dayjs(item.start_time);
    maxTime = dayjs(item.end_time);
  }
  if (item.type === "time-slots") {
    var minTimeRange = getMinTimeRange(item.time_slot.map(function (d) {
      return {
        startDate: dayjs(d.start_time, 'HH:mm'),
        endDate: dayjs(d.end_time, 'HH:mm')
      };
    }));
    minTime = minTimeRange.minTime;
    maxTime = minTimeRange.maxTime;
  }
  if (item.type === "designation") {
    var _minTimeRange = getMinTimeRange(item.designation.map(function (d) {
      return {
        startDate: dayjs(d.start_date + ' ' + d.start_time),
        endDate: dayjs(d.end_date + ' ' + d.end_time)
      };
    }));
    minTime = _minTimeRange.minTime;
    maxTime = _minTimeRange.maxTime;
  }
  return {
    startDate: minTime,
    endDate: maxTime
  };
};
var formatProductItemSchedules = function formatProductItemSchedules(item, scheduleMap) {
  var _list = (item['schedule.ids'] || []).map(function (t) {
    var _scheduleMap$t, _scheduleMap$t2;
    return {
      id: t,
      minTime: (_scheduleMap$t = scheduleMap[t]) === null || _scheduleMap$t === void 0 ? void 0 : _scheduleMap$t.minTime,
      maxTime: (_scheduleMap$t2 = scheduleMap[t]) === null || _scheduleMap$t2 === void 0 ? void 0 : _scheduleMap$t2.maxTime
    };
  }).filter(function (t) {
    return !!t.minTime && !!t.maxTime;
  });
  var total = getMinTimeRange(_list);
  var str = getMinTimeRangeStr(total);
  return _objectSpread(_objectSpread({}, item), {}, {
    _schedules: {
      minTime: total.minTime,
      maxTime: total.maxTime,
      str: str
    }
  });
};

/**
 * 1. 获取每个日程的最小开始时间和最大结束时间.
 * 2. 
 */
export var formatProductSchedules = function formatProductSchedules(products, scheduleMap) {
  return products.map(function (d) {
    return formatProductItemSchedules(d, scheduleMap);
  });
};
export var updateProductById = function updateProductById(_ref2) {
  var products = _ref2.products,
    scheduleMap = _ref2.scheduleMap,
    id = _ref2.id,
    schedule = _ref2.schedule;
  return products.map(function (d) {
    return d.id === id ? formatProductItemSchedules(_objectSpread(_objectSpread({}, d), {}, {
      'schedule.ids': schedule
    }), scheduleMap) : d;
  });
};