var _excluded = ["detail"];
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 _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; }
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 _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
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 { isNormalProductByDurationSchedule } from "../../booking/info/service2/utils";
import { isArr, getUniqueId } from '@pisell/utils';

/** dayjs对象格式化为字符串时间 */
export var formatDateToStr = function formatDateToStr(date) {
  var format = function format(val) {
    return dayjs(val).format('YYYY-MM-DD HH:mm:ss');
  };
  if (Array.isArray(date)) {
    return date.map(format);
  }
  return format(date);
};
export var getDefaultStartParam = function getDefaultStartParam() {
  /** 获取默认查询时间范围 */
  return formatDateToStr([dayjs().startOf('day'), dayjs().endOf('day')]);
};
export var formatBookingList = function formatBookingList(bookingList) {
  return bookingList.map(function (item) {
    var _item$order, _item$order2, _item$order3;
    return _objectSpread(_objectSpread({}, item), {}, {
      startDateTime: "".concat(item.start_date, " ").concat(item.start_time),
      endDateTime: "".concat(item.end_date, " ").concat(item.end_time),
      total_amount: item === null || item === void 0 || (_item$order = item.order) === null || _item$order === void 0 ? void 0 : _item$order.total_amount,
      customer: (item === null || item === void 0 || (_item$order2 = item.order) === null || _item$order2 === void 0 || (_item$order2 = _item$order2.customer) === null || _item$order2 === void 0 || (_item$order2 = _item$order2.display_name) === null || _item$order2 === void 0 ? void 0 : _item$order2.trim()) || ((item === null || item === void 0 || (_item$order3 = item.order) === null || _item$order3 === void 0 || (_item$order3 = _item$order3.customer) === null || _item$order3 === void 0 ? void 0 : _item$order3.nickname) || '').trim()
      // durationStr: this.formatDurationStr(item),
      // durationNum: this.calcDuration(item),
    });
  });
};
export var getNextTimeSlice = function getNextTimeSlice(sliceMinutes) {
  var currentTime = dayjs();

  // 计算下一个时间切片
  var nextSlice = Math.ceil(currentTime.minute() / sliceMinutes) * sliceMinutes;

  // 设置下一个时间切片的分钟数
  var nextTime = currentTime.minute(nextSlice);
  return nextTime;
};
export var getDisabledEdit = function getDisabledEdit(_ref) {
  var shop_discount = _ref.shop_discount,
    bookings = _ref.bookings,
    payment_status = _ref.payment_status;
  // 如果预约列表里没有商品新信息, 则任何信息都不能编辑
  if (bookings.list.some(function (d) {
    return !d.detail;
  })) {
    return true;
  }

  // //有整单折扣 不可编辑
  // if (shop_discount && Number(shop_discount)) {
  //   return true;
  // }

  var list = ['unfulfilled', 'paid', 'partially_paid', 'unpaid', 'payment_processing'];
  // (支付状态 = 已支付 || 部分付款 || 未付款 || 支付处理中) && 预约状态 !== 已取消
  if (bookings.appointment_status === 'cancelled' || !list.includes(payment_status)) {
    return true;
  }
  return false;
};
export var formatOptions = function formatOptions(detail) {
  var _detail$product_sku;
  return ((detail === null || detail === void 0 || (_detail$product_sku = detail.product_sku) === null || _detail$product_sku === void 0 ? void 0 : _detail$product_sku.option) || []).map(function (item) {
    return _objectSpread(_objectSpread({}, item), {}, {
      price: item.price || item.add_price
    });
  });
};
export var formatHolder = function formatHolder(detail) {
  var _detail$holder;
  return detail === null || detail === void 0 || (_detail$holder = detail.holder) === null || _detail$holder === void 0 || (_detail$holder = _detail$holder.form_record) === null || _detail$holder === void 0 ? void 0 : _detail$holder[0];
};

// 还原商品other数据
export var restoreProductOtherData = function restoreProductOtherData(data) {
  var detail = data.detail,
    resetD = _objectWithoutProperties(data, _excluded);
  if (!detail) {
    return;
  }
  return {
    product_id: detail.product_id,
    option: formatOptions(detail),
    bundle: (detail.product_bundle || []).map(function (bundleItem) {
      return _objectSpread(_objectSpread({}, bundleItem), {}, {
        title: bundleItem.bundle_title,
        group_id: bundleItem.bundle_group_id,
        id: bundleItem.bundle_id,
        product_id: bundleItem.bundle_product_id,
        _bundle_product_id: bundleItem.bundle_product_id,
        bundle_variant_id: bundleItem.bundle_variant_id,
        quantity: bundleItem.num,
        option: bundleItem.option.map(function (optionItem) {
          return _objectSpread(_objectSpread({}, optionItem), {}, {
            name: optionItem.name['auto'],
            quantity: bundleItem.num,
            product_option_item_id: optionItem.option_group_item_id
          });
        }),
        price: (bundleItem === null || bundleItem === void 0 ? void 0 : bundleItem.bundle_sum_type) === 'markdown' ? "-".concat(Number(bundleItem.bundle_sum_price)) : Number(bundleItem.bundle_sum_price)
      });
    }),
    product_variant_id: detail.product_variant_id || 0,
    quantity: Number(detail.product_quantity)
  };
};

// 是相同的商品
export var isSameProduct = function isSameProduct(a, b) {
  var _a$_extend2, _b$_extend2;
  if (isNormalProductByDurationSchedule(a) && isNormalProductByDurationSchedule(b)) {
    var _a$_extend, _b$_extend;
    return ((_a$_extend = a._extend) === null || _a$_extend === void 0 || (_a$_extend = _a$_extend.other) === null || _a$_extend === void 0 ? void 0 : _a$_extend.rowKey) === ((_b$_extend = b._extend) === null || _b$_extend === void 0 || (_b$_extend = _b$_extend.other) === null || _b$_extend === void 0 ? void 0 : _b$_extend.rowKey);
  }
  return ((_a$_extend2 = a._extend) === null || _a$_extend2 === void 0 || (_a$_extend2 = _a$_extend2.other) === null || _a$_extend2 === void 0 ? void 0 : _a$_extend2.rowKey) === ((_b$_extend2 = b._extend) === null || _b$_extend2 === void 0 || (_b$_extend2 = _b$_extend2.other) === null || _b$_extend2 === void 0 ? void 0 : _b$_extend2.rowKey) && a._serviceKey === b._serviceKey;
};
export var addService = function addService(list, addItem, state) {
  var value = list;
  var count;
  // 预约商品 并且配置商品卡片不叠加 直接添加
  if (!isNormalProductByDurationSchedule(addItem) && !getIsOverlayProduct(addItem, state)) {
    value.unshift(addItem);
    count = addItem._extend.quantity;
  } else {
    // 非预约商品判断是否相同，相同合并
    var isNotSame = true;
    // 是否设置过 只追加到第一个中
    var isSetCount = false;
    value = list.map(function (item) {
      // 是否商品券折扣的商品
      var isGoodPassDiscountProduct = (item.discount_list || []).some(function (item) {
        return item.type === 'good_pass';
      });
      if (isSameProduct(item, addItem) && !isSetCount && !isGoodPassDiscountProduct) {
        var _item$_extend, _addItem$_extend, _item$_extend2;
        isNotSame = false;
        var quantity = ((item === null || item === void 0 || (_item$_extend = item._extend) === null || _item$_extend === void 0 ? void 0 : _item$_extend.quantity) || 1) + ((addItem === null || addItem === void 0 || (_addItem$_extend = addItem._extend) === null || _addItem$_extend === void 0 ? void 0 : _addItem$_extend.quantity) || 1);
        count = quantity;
        isSetCount = true;
        return _objectSpread(_objectSpread({}, item), {}, {
          _extend: _objectSpread(_objectSpread({}, item._extend), {}, {
            quantity: quantity,
            other: _objectSpread(_objectSpread({}, ((_item$_extend2 = item._extend) === null || _item$_extend2 === void 0 ? void 0 : _item$_extend2.other) || {}), {}, {
              quantity: quantity
            })
          })
        });
      }
      return item;
    });
    var _idx = value.findIndex(function (item) {
      return item.id === addItem.id;
    });
    if (_idx !== -1) {
      var _value$splice = value.splice(_idx, 1),
        _value$splice2 = _slicedToArray(_value$splice, 1),
        removed = _value$splice2[0];
      // 再添加到数组开头
      value.unshift(removed);
    }
    if (isNotSame) {
      value.unshift(addItem);
      count = addItem._extend.quantity;
    }
  }
  return {
    list: value,
    quantity: count
  };
};
export var addServiceScroll = function addServiceScroll(rowKey, cacheItem) {
  var list = document.querySelectorAll("#rowKey-".concat(rowKey));
  setTimeout(function () {
    if (list.length && isNormalProductByDurationSchedule(cacheItem)) {
      list[list.length - 1].scrollIntoView({
        behavior: 'smooth',
        block: 'center'
      });
    } else {
      setTimeout(function () {
        var bookingWrap = document.querySelectorAll(".pisell-lowcode__booking-service-wrap");
        if (bookingWrap.length) {
          bookingWrap[0].scrollTo({
            top: 0,
            behavior: 'smooth'
          });
        }
      }, 100);
    }
  });
};

// 获取购物车商品覆盖规则
export var getCartProductOverlay = function getCartProductOverlay(state) {
  var _state$bookingConfig;
  return (state === null || state === void 0 || (_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.cart_product_overlay) || {
    type: "product_all"
  };
};

// 获取购物车商品是否覆盖
export var getIsOverlayProduct = function getIsOverlayProduct(item, state) {
  var _getCartProductOverla = getCartProductOverlay(state),
    type = _getCartProductOverla.type,
    product_ids = _getCartProductOverla.product_ids;
  if (type === 'product_all') {
    return true;
  }
  return product_ids.includes(item.product_id || item.id);
};

// 获取购物车商品是否显示数量
export var getIsShowNumber = function getIsShowNumber(item, state) {
  var isBookingTicket2 = state.isBookingTicket2;
  return isNormalProductByDurationSchedule(item) || isBookingTicket2 && getIsOverlayProduct(item, state);
};

// 生成服务key
export var genServiceKey = function genServiceKey(item) {
  var _item$_extend3, _item$_extend4, _item$_extend5;
  var product_id = item.product_id;
  var durationKey = (_item$_extend3 = item._extend) === null || _item$_extend3 === void 0 ? void 0 : _item$_extend3.duration;
  var start_time = (_item$_extend4 = item._extend) === null || _item$_extend4 === void 0 ? void 0 : _item$_extend4.start_time;
  var total = (_item$_extend5 = item._extend) === null || _item$_extend5 === void 0 ? void 0 : _item$_extend5.total;
  var resourceKey = '';
  Object.values(item._extend.resource || []).forEach(function (resources) {
    resources.forEach(function (resource) {
      resourceKey += "".concat(resource.relation_id);
    });
  });
  return "".concat(product_id, "-").concat(durationKey, "-").concat(resourceKey, "-").concat(start_time, "-").concat(total);
};

// 是否是平行资源预约
export var getIsParallelResourcesBooking = function getIsParallelResourcesBooking(record) {
  return (record === null || record === void 0 ? void 0 : record.relation_id) === 0 && (record === null || record === void 0 ? void 0 : record.relation_type) === "";
};
export var formatScanCustomer = function formatScanCustomer(data) {
  var result = data.result,
    scanCode = data.scanCode;
  var _ref2 = result || {},
    response = _ref2.response,
    searchType = _ref2.searchType;
  var _ref3 = response || {},
    customerData = _ref3.data,
    _ref3$code = _ref3.code,
    code = _ref3$code === void 0 ? 200 : _ref3$code;
  if (code !== 200) {
    return null;
  }
  if (isArr(customerData)) {
    var _customerData$;
    return {
      searchType: searchType,
      data: (_customerData$ = customerData[0]) === null || _customerData$ === void 0 ? void 0 : _customerData$.customer,
      scanCode: scanCode
    };
  }
  return {
    searchType: searchType,
    data: customerData === null || customerData === void 0 ? void 0 : customerData.customer,
    scanCode: scanCode
  };
};
export var formatScanGlobal = function formatScanGlobal(data) {
  var result = data.result,
    scanCode = data.scanCode;
  var _ref4 = result || {},
    response = _ref4.response,
    searchType = _ref4.searchType;
  var _ref5 = response || {},
    resultData = _ref5.data,
    code = _ref5.code;
  if (code !== 200 && searchType !== 'local_product') {
    return null;
  }
  if (searchType === 'wallet') {
    return {
      searchType: searchType,
      data: resultData.customer,
      scanCode: scanCode
    };
  }
  if (searchType === 'walletPass') {
    var _resultData$;
    return {
      searchType: searchType,
      data: resultData === null || resultData === void 0 || (_resultData$ = resultData[0]) === null || _resultData$ === void 0 ? void 0 : _resultData$.customer,
      scanCode: scanCode
    };
  }
  if (searchType === 'product' || searchType === 'local_product') {
    return {
      searchType: searchType,
      data: resultData,
      scanCode: scanCode
    };
  }
};
export var createSimpleCacheItem = function createSimpleCacheItem(item, e, state) {
  var cacheItem = _objectSpread(_objectSpread({}, item), {}, {
    product_id: item.id,
    _id: getUniqueId(),
    _key: e.key,
    _extend: {
      start_date: state.date.value,
      quantity: (e === null || e === void 0 ? void 0 : e.quantity) || 1,
      price: item.price,
      product_name: item.title,
      other: e
    },
    new: 1
  });
  return cacheItem;
};