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 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 { getUniqueId } from "@pisell/utils";
import { getProductTotalPrice } from "../../../utils";
import { distributeDiscountOrIncrease } from "../../service/serviceManager/distributeDiscount";
import { setProductPrice } from "../../../info2/service/editService/utils";
import { genServiceKey } from "../../../../ticketBooking/utils";
import Decimal from "decimal.js";

// 创建group

// 拆分group

// 编辑group

// 合并group

export var getGroupTotalPrice = function getGroupTotalPrice(items) {
  return items.reduce(function (prev, next) {
    prev.duration += next._extend.duration;
    prev.total += next._extend.total;
    // prev.price += next._extend.price;
    prev.origin_total += next._extend.origin_total;
    return prev;
  }, {
    total: 0,
    origin_total: 0
  });
};

/**
 * @title: 创建一个虚拟的组
 * @description: 
 * @param {any} items
 * @return {*}
 * @Author: zhiwei.Wang
 */
export var concatBookings = function concatBookings(items) {
  var firstItem = items[0];
  var lastItem = items[items.length - 1];
  var _items$reduce = items.reduce(function (prev, next) {
      prev.duration += next._extend.duration;
      prev.total += next._extend.total;
      // prev.price += next._extend.price;
      prev.origin_total += next._extend.origin_total;
      return prev;
    }, {
      price: 0,
      total: 0,
      origin_total: 0,
      duration: 0,
      startDate: firstItem._extend.startDate,
      endDate: lastItem._extend.endDate
    }),
    total = _items$reduce.total,
    duration = _items$reduce.duration,
    startDate = _items$reduce.startDate,
    endDate = _items$reduce.endDate,
    origin_total = _items$reduce.origin_total;
  return _objectSpread(_objectSpread({}, firstItem), {}, {
    // 虚拟组, id使用组id
    _id: firstItem._extend.groupId,
    _extend: _objectSpread(_objectSpread({}, firstItem._extend), {}, {
      items: items,
      duration: duration,
      // price: total,
      total: total,
      origin_total: origin_total,
      startDate: startDate,
      endDate: endDate,
      start_date: startDate,
      end_date: endDate
    })
  });
};
export var createBookingItemsByGroup = function createBookingItemsByGroup(item, isBatchEdit) {
  var groupId = item._extend.groupId || getUniqueId('bookingGroup_');
  var bookings = [];

  // 根据时长 进行创建多个商品
  for (var i = 0; i < item._extend.duration; i++) {
    var _extend$multiDayPrice;
    var _extend = _objectSpread({}, item._extend);
    var startDate = _extend.start_date.add(i, 'day');
    var endDate = _extend.start_date.add(i + 1, 'day');
    // 商品原始价格  
    var price = ((_extend$multiDayPrice = _extend.multiDayPrices) === null || _extend$multiDayPrice === void 0 || (_extend$multiDayPrice = _extend$multiDayPrice[startDate.format('YYYY-MM-DD')]) === null || _extend$multiDayPrice === void 0 ? void 0 : _extend$multiDayPrice.total) || item._extend.price;
    var cacheItem = _objectSpread(_objectSpread({}, item), {}, {
      // 编辑时组商品需要清空booking_id  否则会重复
      booking_id: isBatchEdit ? 0 : item.booking_id,
      _id: "".concat(item._id, "-").concat(i + 1),
      price: price,
      _extend: _objectSpread(_objectSpread({}, _extend), {}, {
        metadata: _objectSpread(_objectSpread({}, (_extend === null || _extend === void 0 ? void 0 : _extend.metadata) || {}), {}, {
          unique_identification_number: undefined
        }),
        unique_identification_number: undefined,
        order_detail_id: isBatchEdit ? 0 : item.order_detail_id,
        groupId: groupId,
        duration: 1,
        price: price,
        startDate: startDate,
        endDate: endDate,
        start_date: startDate,
        end_date: endDate,
        dateKey: "".concat(startDate.format('YYYY-MM-DD'), "~").concat(endDate.format('YYYY-MM-DD'), "}")
      })
    });
    var totalPrice = getProductTotalPrice(cacheItem);
    cacheItem._extend.total = totalPrice;
    cacheItem._extend.origin_total = totalPrice;
    cacheItem._extend.items = undefined;
    cacheItem._serviceKey = genServiceKey(cacheItem);
    bookings.push(cacheItem);
  }
  if (isBatchEdit) {
    // 当前金额
    var groupTotalPrice = item._extend.total;
    // 原始金额
    var groupOriginTotalPrice = item._extend.origin_total;
    // 折扣金额 转成负数
    var discountAmount = (groupOriginTotalPrice - groupTotalPrice) * -1;
    if (discountAmount !== 0) {
      if (groupOriginTotalPrice !== 0) {
        bookings = distributeDiscountOrIncrease(bookings, discountAmount, groupOriginTotalPrice);
        bookings = bookings.map(function (booking) {
          var _booking$_extend, _booking$_extend2;
          return setProductPrice(booking, {
            newTotal: booking === null || booking === void 0 || (_booking$_extend = booking._extend) === null || _booking$_extend === void 0 ? void 0 : _booking$_extend.total,
            origin_total: booking === null || booking === void 0 || (_booking$_extend2 = booking._extend) === null || _booking$_extend2 === void 0 ? void 0 : _booking$_extend2.origin_total
          });
        });
      } else {
        // 原价为 0 无法按比例分摊（会除零），按 booking 数量均摊手动改价后的 groupTotalPrice
        // 最后一个 booking 吸收两位小数的精度误差，确保总和等于 groupTotalPrice
        var count = bookings.length;
        var avgTotal = new Decimal(groupTotalPrice).div(count).toDecimalPlaces(2, Decimal.ROUND_HALF_UP);
        var assignedSum = new Decimal(0);
        bookings = bookings.map(function (booking, i) {
          var newTotal = i === count - 1 ? new Decimal(groupTotalPrice).sub(assignedSum).toNumber() : avgTotal.toNumber();
          if (i !== count - 1) {
            assignedSum = assignedSum.add(avgTotal);
          }
          return _objectSpread(_objectSpread({}, booking), {}, {
            _extend: _objectSpread(_objectSpread({}, booking._extend), {}, {
              total: newTotal,
              price: newTotal
            })
          });
        });
      }
    }
  }
  console.log('bookings', bookings);
  return bookings;
};
export var isGroupBooking = function isGroupBooking(_id) {
  var _id$indexOf;
  return (_id === null || _id === void 0 || (_id$indexOf = _id.indexOf) === null || _id$indexOf === void 0 ? void 0 : _id$indexOf.call(_id, 'bookingGroup_')) === 0;
};
export var getProductByGroupId = function getProductByGroupId(groupId, items) {
  return items.filter(function (item) {
    var _item$_extend;
    return ((_item$_extend = item._extend) === null || _item$_extend === void 0 ? void 0 : _item$_extend.groupId) === groupId;
  }).map(function (item) {
    return item._id;
  });
};
export var getGroupBooking = function getGroupBooking(groupId, items) {
  var products = getProductByGroupId(groupId, items);
  return concatBookings(products);
};
export var filterItemByGroupId = function filterItemByGroupId(groupId, items) {
  return items.filter(function (item) {
    var _item$_extend2;
    return ((_item$_extend2 = item._extend) === null || _item$_extend2 === void 0 ? void 0 : _item$_extend2.groupId) !== groupId;
  });
};