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); }
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 _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 Decimal from 'decimal.js';

/**
 * 将value转换为SelectorGroup需要的格式
 */
export var transformValueToSelectorValue = function transformValueToSelectorValue(value, dataSource) {
  var _Object$keys, _Object$keys2;
  console.log('transformValueToSelectorValue_value>>>>>>>', value);
  if (!value || !dataSource || ((_Object$keys = Object.keys(value || {})) === null || _Object$keys === void 0 ? void 0 : _Object$keys.length) === 0 || ((_Object$keys2 = Object.keys(dataSource || {})) === null || _Object$keys2 === void 0 ? void 0 : _Object$keys2.length) === 0) {
    return {};
  }
  var transformValue = {};

  // 套餐商品数据
  if (value !== null && value !== void 0 && value.bundle) {
    var _value$bundle, _newBundle$forEach;
    // 首先需要把value?.bundle中id相同的商品合并，value?.bundle转换为：[{id: number, options: Array<any>}, {id: number, options: Array<any>}, ...]
    var newBundle = value === null || value === void 0 || (_value$bundle = value.bundle) === null || _value$bundle === void 0 ? void 0 : _value$bundle.reduce(function (acc, v) {
      var _bundleItemId = v === null || v === void 0 ? void 0 : v.id;
      var idx = acc === null || acc === void 0 ? void 0 : acc.findIndex(function (v1) {
        return (v1 === null || v1 === void 0 ? void 0 : v1.id) === _bundleItemId;
      });
      if (idx !== -1) {
        var _acc$idx, _acc$idx$push;
        (_acc$idx = acc[idx]) === null || _acc$idx === void 0 || (_acc$idx = _acc$idx.bundleOptions) === null || _acc$idx === void 0 || (_acc$idx$push = _acc$idx.push) === null || _acc$idx$push === void 0 || _acc$idx$push.call(_acc$idx, v);
      } else {
        var _acc$push;
        acc === null || acc === void 0 || (_acc$push = acc.push) === null || _acc$push === void 0 || _acc$push.call(acc, {
          id: _bundleItemId,
          groupId: v === null || v === void 0 ? void 0 : v.group_id,
          bundleOptions: [v]
        });
      }
      return acc;
    }, []);
    newBundle === null || newBundle === void 0 || (_newBundle$forEach = newBundle.forEach) === null || _newBundle$forEach === void 0 || _newBundle$forEach.call(newBundle, function (v1) {
      var _bundleGroupId = v1 === null || v1 === void 0 ? void 0 : v1.groupId;
      var _bundleValue = createBundleValue(v1, dataSource);
      if (transformValue[_bundleGroupId]) {
        transformValue[_bundleGroupId] = [].concat(_toConsumableArray(transformValue[_bundleGroupId] || []), [_bundleValue]);
      } else {
        transformValue[_bundleGroupId] = [_bundleValue];
      }
    });
  }

  // 单规格商品数据
  if (value !== null && value !== void 0 && value.option) {
    transformValue = createOptionValue(transformValue, value, dataSource);
  }

  // 组合规格商品数据
  if (value !== null && value !== void 0 && value.product_variant_id) {
    var _dataSource$variant;
    // 根据product_variant_id从dataSource中的variant中进行匹配，最终筛选出对应的组合规格商品
    var filteredVariant = dataSource === null || dataSource === void 0 || (_dataSource$variant = dataSource.variant) === null || _dataSource$variant === void 0 ? void 0 : _dataSource$variant.find(function (item) {
      return (item === null || item === void 0 ? void 0 : item.id) === (value === null || value === void 0 ? void 0 : value.product_variant_id);
    });
    if (!!filteredVariant) {
      var _filteredVariant$sku_;
      var ids = (filteredVariant === null || filteredVariant === void 0 || (_filteredVariant$sku_ = filteredVariant.sku_ids) === null || _filteredVariant$sku_ === void 0 ? void 0 : _filteredVariant$sku_.split('_')) || [];
      ids.forEach(function (id) {
        var _dataSource$variant_g;
        // 拆分出variantGroupId和variantId，需要将variantGroupId和variantId转换为数字
        var _id$split = id.split(':'),
          _id$split2 = _slicedToArray(_id$split, 2),
          variantGroupId = _id$split2[0],
          variantId = _id$split2[1];
        var _variantGroupId = Number(variantGroupId);
        var _variantId = Number(variantId);
        // 从variant_group中匹配出数据
        var _variantGroupItem = null;
        // 只要找到数据就结束查找
        dataSource === null || dataSource === void 0 || (_dataSource$variant_g = dataSource.variant_group) === null || _dataSource$variant_g === void 0 || _dataSource$variant_g.find(function (v1) {
          if ((v1 === null || v1 === void 0 ? void 0 : v1.id) === _variantGroupId) {
            var _v1$variant_item;
            v1 === null || v1 === void 0 || (_v1$variant_item = v1.variant_item) === null || _v1$variant_item === void 0 || _v1$variant_item.find(function (v2) {
              if ((v2 === null || v2 === void 0 ? void 0 : v2.id) === _variantId) {
                _variantGroupItem = v2;
                return true;
              }
              return false;
            });
            return true;
          }
          return false;
        });
        if (!!_variantGroupItem) {
          transformValue[_variantGroupId] = {
            data: _objectSpread({}, _variantGroupItem || {}),
            quantity: 1,
            value: _variantId
          };
        }
      });
    }
  }
  return transformValue;
};

/**
 * 创建套餐商品数据
 */
var createBundleValue = function createBundleValue(v, dataSource) {
  var _dataSource$bundle_gr, _v$bundleOptions, _v$bundleOptions$forE;
  var _createdValue = null;

  // 从dataSource的bundle_group中匹配出数据
  var bundleGroupItem = dataSource === null || dataSource === void 0 || (_dataSource$bundle_gr = dataSource.bundle_group) === null || _dataSource$bundle_gr === void 0 ? void 0 : _dataSource$bundle_gr.find(function (v1) {
    return (v1 === null || v1 === void 0 ? void 0 : v1.id) === (v === null || v === void 0 ? void 0 : v.groupId);
  });
  var findedBundleItem = null;
  if (!!bundleGroupItem) {
    var _bundleGroupItem$bund;
    findedBundleItem = bundleGroupItem === null || bundleGroupItem === void 0 || (_bundleGroupItem$bund = bundleGroupItem.bundle_item) === null || _bundleGroupItem$bund === void 0 ? void 0 : _bundleGroupItem$bund.find(function (v1) {
      return (v1 === null || v1 === void 0 ? void 0 : v1.id) === (v === null || v === void 0 ? void 0 : v.id);
    });
    if (!!findedBundleItem) {
      var _findedBundleItem;
      _createdValue = {
        value: (_findedBundleItem = findedBundleItem) === null || _findedBundleItem === void 0 ? void 0 : _findedBundleItem.id,
        data: _objectSpread({}, findedBundleItem || {})
      };
    }
  }

  // 如果选项在套餐组中不匹配到数据，则直接返回null
  if (!_createdValue) {
    return null;
  }
  var totalQuantity = 0;
  v === null || v === void 0 || (_v$bundleOptions = v.bundleOptions) === null || _v$bundleOptions === void 0 || (_v$bundleOptions$forE = _v$bundleOptions.forEach) === null || _v$bundleOptions$forE === void 0 || _v$bundleOptions$forE.call(_v$bundleOptions, function (v1) {
    var _v1$option, _findedBundleItem2;
    if (v1 !== null && v1 !== void 0 && (_v1$option = v1.option) !== null && _v1$option !== void 0 && _v1$option.length) {
      var _createdValue2;
      var _data = ((_createdValue2 = _createdValue) === null || _createdValue2 === void 0 || (_createdValue2 = _createdValue2.data) === null || _createdValue2 === void 0 ? void 0 : _createdValue2._data) || [];
      var _createdValueData = createOptionValue({}, v1, findedBundleItem);
      _data.push({
        value: v1 === null || v1 === void 0 ? void 0 : v1.id,
        data: _createdValueData,
        quantity: (v1 === null || v1 === void 0 ? void 0 : v1.quantity) || 1
      });
      _createdValue.data._data = _data;
    }
    // 计算总数量，优先使用quantity，没有的话则使用num
    totalQuantity = totalQuantity + ((v1 === null || v1 === void 0 ? void 0 : v1.quantity) || (v1 === null || v1 === void 0 ? void 0 : v1.num) || 1);
    // 优先传入的价格，没有的话则从原始数据中获取
    var _price = (v1 === null || v1 === void 0 ? void 0 : v1.price) || ((_findedBundleItem2 = findedBundleItem) === null || _findedBundleItem2 === void 0 ? void 0 : _findedBundleItem2.price) || 0;
    _createdValue.totalPrice = new Decimal(_createdValue.totalPrice || 0).plus(new Decimal(_price).times((v1 === null || v1 === void 0 ? void 0 : v1.quantity) || 1)).toNumber();
  });
  _createdValue.quantity = totalQuantity;
  _createdValue.data.quantity = totalQuantity;
  _createdValue.data.num = totalQuantity;
  return _createdValue;
};

/**
 * 创建单规格商品value
 */
var createOptionValue = function createOptionValue(initValue, value, dataSource) {
  var _value$option, _value$option$forEach;
  var _createdValue = initValue || {};
  value === null || value === void 0 || (_value$option = value.option) === null || _value$option === void 0 || (_value$option$forEach = _value$option.forEach) === null || _value$option$forEach === void 0 || _value$option$forEach.call(_value$option, function (v1) {
    var _dataSource$option_gr, _matchedGroup$option_;
    var _optionGroupId = v1 === null || v1 === void 0 ? void 0 : v1.option_group_id;
    // 从dataSource?.option_group的option_item中匹配出option数据
    var matchedGroup = dataSource === null || dataSource === void 0 || (_dataSource$option_gr = dataSource.option_group) === null || _dataSource$option_gr === void 0 ? void 0 : _dataSource$option_gr.find(function (v2) {
      return (v2 === null || v2 === void 0 ? void 0 : v2.id) === _optionGroupId;
    });
    var matchedOptionItem = matchedGroup === null || matchedGroup === void 0 || (_matchedGroup$option_ = matchedGroup.option_item) === null || _matchedGroup$option_ === void 0 ? void 0 : _matchedGroup$option_.find(function (v3) {
      return (v3 === null || v3 === void 0 ? void 0 : v3.id) === (v1 === null || v1 === void 0 ? void 0 : v1.id);
    });
    var _num = (v1 === null || v1 === void 0 ? void 0 : v1.quantity) || (v1 === null || v1 === void 0 ? void 0 : v1.num) || 1;
    // 使用原始数据中的价格
    var _price = (matchedOptionItem === null || matchedOptionItem === void 0 ? void 0 : matchedOptionItem.add_price) || 0;
    var _tempOptionValue = {
      data: _objectSpread(_objectSpread(_objectSpread({}, matchedOptionItem || {}), v1 || {}), {}, {
        num: _num,
        price: _price,
        original_price: _price,
        original_total: _price
      }),
      quantity: _num,
      value: v1 === null || v1 === void 0 ? void 0 : v1.id,
      totalPrice: new Decimal((matchedOptionItem === null || matchedOptionItem === void 0 ? void 0 : matchedOptionItem.add_price) || 0).times(_num).toNumber()
    };

    // 首先判定_createdValue中是否存在该group的key，如果存在则需要将v1的数据合并到_createdValue中
    if (_createdValue[_optionGroupId]) {
      _createdValue[_optionGroupId] = [].concat(_toConsumableArray(_createdValue[_optionGroupId] || []), [_tempOptionValue]);
    } else {
      // 从dataSource中的option_group中匹配出group数据，判断该group是单选还是多选
      if ((matchedGroup === null || matchedGroup === void 0 ? void 0 : matchedGroup.is_multiple) == 1) {
        _createdValue[_optionGroupId] = [_tempOptionValue];
      } else {
        _createdValue[_optionGroupId] = _tempOptionValue;
      }
    }
  });
  return _createdValue;
};