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';
export var handleProductInfo = function handleProductInfo(eventDetail, num) {
  var productDetail = eventDetail.productDetail,
    bookingOptionItem = eventDetail.bookingOptionItem;
  var normalProduct = bookingOptionItem === null || bookingOptionItem === void 0 ? void 0 : bookingOptionItem._originData;
  var totalPrice = Number((normalProduct === null || normalProduct === void 0 ? void 0 : normalProduct.price) || '');
  var originTotal = Number((normalProduct === null || normalProduct === void 0 ? void 0 : normalProduct.original_price) || '');
  var is_charge_tax = normalProduct === null || normalProduct === void 0 ? void 0 : normalProduct.is_charge_tax;
  if (productDetail) {
    var origin = productDetail.origin,
      bundle = productDetail.bundle,
      options = productDetail.options,
      product_variant_id = productDetail.product_variant_id;
    var variant = null;

    // 如果是组合规格，需要单独处理
    if (product_variant_id) {
      var _origin$variant, _variant;
      variant = origin === null || origin === void 0 || (_origin$variant = origin.variant) === null || _origin$variant === void 0 ? void 0 : _origin$variant.find(function (item) {
        return (item === null || item === void 0 ? void 0 : item.id) === product_variant_id;
      });
      is_charge_tax = (_variant = variant) === null || _variant === void 0 ? void 0 : _variant.is_charge_tax;
    }
    var params = {
      product: origin,
      variant: variant,
      bundle: bundle,
      options: options,
      num: num
    };
    totalPrice = getTotalPrice(params);
    originTotal = getOriginTotalPrice(params);
  }
  return {
    totalPrice: totalPrice,
    originTotal: originTotal,
    is_charge_tax: is_charge_tax
  };
};

/**
 * 获取商品总价
 * @description 当前总价计算基于商品数量为1
 * @param item 商品
 * @returns 商品总价
 */
export var getTotalPrice = function getTotalPrice(params) {
  var product = params.product,
    bundle = params.bundle,
    options = params.options,
    variant = params.variant;
  var num = params.num || 1;
  var price = Number(product.price);

  // 组合规格
  if (variant) {
    price = Number(variant === null || variant === void 0 ? void 0 : variant.price);
  }

  // 套餐
  if (bundle !== null && bundle !== void 0 && bundle.length) {
    price = bundle.reduce(function (accumulator, currentValue) {
      return accumulator + Number(currentValue.price) * Number(currentValue.num);
    }, price);
  }

  // 单规格
  if (options !== null && options !== void 0 && options.length) {
    price = options.reduce(function (accumulator, currentValue) {
      return accumulator + Number(currentValue.price) * Number(currentValue.num);
    }, price);
  }
  return price * num;
};

/**
 * 获取商品原始总价
 * @description 当前总价计算基于商品数量为1
 * @param item 商品
 * @returns 商品原始总价
 */
export var getOriginTotalPrice = function getOriginTotalPrice(params) {
  var product = params.product,
    bundle = params.bundle,
    options = params.options,
    variant = params.variant;
  var num = (params === null || params === void 0 ? void 0 : params.num) || 1;
  var price = Number(product.original_price);

  // 组合规格
  if (variant) {
    price = Number(variant === null || variant === void 0 ? void 0 : variant.original_price);
  }
  if (isNaN(price) || price === 0) {
    return undefined;
  }

  // 套餐
  if (bundle !== null && bundle !== void 0 && bundle.length) {
    price = bundle.reduce(function (accumulator, currentValue) {
      return accumulator + Number(currentValue.price) * Number(currentValue.num);
    }, price);
  }

  // 单规格
  if (options !== null && options !== void 0 && options.length) {
    price = options.reduce(function (accumulator, currentValue) {
      return accumulator + Number(currentValue.price) * Number(currentValue.num);
    }, price);
  }
  return price * num;
};
export var handleCartItemOrigin = function handleCartItemOrigin(cartItem, eventDetail) {
  var productDetail = eventDetail.productDetail;
  var originData = (cartItem === null || cartItem === void 0 ? void 0 : cartItem._originData) || {};
  if (productDetail) {
    var bundle = productDetail.bundle,
      options = productDetail.options,
      product_variant_id = productDetail.product_variant_id;
    if (!originData.product) {
      originData.product = {};
    }
    if (product_variant_id) {
      originData.product.product_variant_id = product_variant_id;
    }
    if (bundle !== null && bundle !== void 0 && bundle.length) {
      originData.product.product_bundle = formatBundleToOrigin(bundle);
    }
    if (options !== null && options !== void 0 && options.length) {
      originData.product.product_option_item = formatOptionsToOrigin(options);
    }
  }
  console.log('originData>>>>>>', originData);
  return originData;
};
export var formatBundleToOrigin = function formatBundleToOrigin(bundle) {
  if (!(bundle !== null && bundle !== void 0 && bundle.length)) return [];
  return bundle.map(function (d) {
    return {
      bundle_group_id: d.group_id,
      bundle_id: d.id,
      bundle_product_id: (d === null || d === void 0 ? void 0 : d._bundle_product_id) || (d === null || d === void 0 ? void 0 : d.product_id),
      bundle_variant_id: d.bundle_variant_id,
      num: d.num,
      extension_id: d.extension_id,
      extension_type: d.extension_type,
      option: formatOptionsToOrigin(d.option)
    };
  });
};
export var formatOptionsToOrigin = function formatOptionsToOrigin(options) {
  if (!(options !== null && options !== void 0 && options.length)) {
    return [];
  }
  return options.map(function (d) {
    return {
      num: d.num,
      option_group_item_id: d.product_option_item_id,
      option_group_id: d.option_group_id
    };
  });
};
export var handleProductDeposit = function handleProductDeposit(cartItem, eventDetail, num) {
  var _origin$custom_deposi;
  var productDetail = eventDetail.productDetail,
    bookingOptionItem = eventDetail.bookingOptionItem;

  // 如果是普通商品
  var normalProduct = bookingOptionItem === null || bookingOptionItem === void 0 ? void 0 : bookingOptionItem._originData;
  if (!productDetail && normalProduct) {
    var custom_deposit_data = normalProduct.custom_deposit_data;
    if ((custom_deposit_data === null || custom_deposit_data === void 0 ? void 0 : custom_deposit_data.has_deposit) == 1) {
      return getProductDeposit({
        cartItem: cartItem,
        product: normalProduct,
        num: num
      });
    } else {
      return null;
    }
  }
  if (!productDetail) {
    return null;
  }
  var _ref = productDetail || {},
    origin = _ref.origin,
    bundle = _ref.bundle,
    options = _ref.options,
    product_variant_id = _ref.product_variant_id;
  var deposit = null;
  var product = origin;
  if (product_variant_id) {
    product.product_variant_id = product_variant_id;
  }
  if ((origin === null || origin === void 0 || (_origin$custom_deposi = origin.custom_deposit_data) === null || _origin$custom_deposi === void 0 ? void 0 : _origin$custom_deposi.has_deposit) == 1) {
    deposit = getProductDeposit({
      cartItem: cartItem,
      product: product,
      bundle: bundle,
      options: options,
      num: num
    });
  }
  return deposit;
};

/**
 * 获取商品定金
 * @description 定金基于商品售价来算，最终乘商品数量
 * 1、如果套餐主商品有定金规则，则定金为：（套餐商品总售价 * 定金百分比 + 定金固定金额）* 商品数量
 * 2、如果套餐主商品没有定金规则，子商品有定金规则，则定金为：（套餐子商品售价 * 套餐子商品定金百分比 + 套餐子商品定金固定金额）* 商品数量，最终将所有子商品定金相加
 * 3、普通商品/单规格商品/组合规则商品，定金规则：（商品总售价 * 定金百分比 + 定金固定金额）* 商品数量
 * @param params 参数
 * @returns 商品定金
 */
export var getProductDeposit = function getProductDeposit(params) {
  var _product$custom_depos;
  var cartItem = params.cartItem,
    product = params.product,
    bundle = params.bundle,
    options = params.options;
  var num = (params === null || params === void 0 ? void 0 : params.num) || 1;

  // 判定商品是否有定金规则
  if ((product === null || product === void 0 || (_product$custom_depos = product.custom_deposit_data) === null || _product$custom_depos === void 0 ? void 0 : _product$custom_depos.has_deposit) == 1) {
    var total = new Decimal(0);
    var _ref2 = (product === null || product === void 0 ? void 0 : product.custom_deposit_data) || {},
      deposit_fixed = _ref2.deposit_fixed,
      deposit_percentage = _ref2.deposit_percentage,
      deposit_policy_data = _ref2.deposit_policy_data,
      self_deposit_policy_ids = _ref2.self_deposit_policy_ids;
    // 所有协议数据
    var allProtocols = deposit_policy_data || [];
    // 是否存在定金，主商品has_deposit为1，但是自身没有定金设置，需要判定子商品是否存在定金，如果不存在最终判定也是不存在定金
    var productHasDeposit = false;
    // 关联的定金协议id
    var protocolIds = [];

    // 判断主商品是否有定金规则
    if (typeof deposit_fixed === 'string' && typeof deposit_percentage === 'string') {
      var _calculateProductDepo = calculateProductDeposit({
          depositData: product === null || product === void 0 ? void 0 : product.custom_deposit_data,
          total: (cartItem === null || cartItem === void 0 ? void 0 : cartItem.total) || 0,
          num: num
        }),
        depositTotal = _calculateProductDepo.depositTotal,
        result = _calculateProductDepo.result;
      if (result) {
        total = depositTotal;
        protocolIds.push.apply(protocolIds, _toConsumableArray(self_deposit_policy_ids || []));
        productHasDeposit = true;
      }
    } else {
      // 组合规格商品
      if (product !== null && product !== void 0 && product.product_variant_id) {
        var _product$variant;
        var variantProduct = product === null || product === void 0 || (_product$variant = product.variant) === null || _product$variant === void 0 ? void 0 : _product$variant.find(function (item) {
          return (item === null || item === void 0 ? void 0 : item.id) === (product === null || product === void 0 ? void 0 : product.product_variant_id);
        });
        if (variantProduct) {
          var depositData = variantProduct === null || variantProduct === void 0 ? void 0 : variantProduct.custom_deposit_data;
          var _calculateProductDepo2 = calculateProductDeposit({
              depositData: depositData,
              total: (cartItem === null || cartItem === void 0 ? void 0 : cartItem.total) || 0,
              num: num
            }),
            _depositTotal = _calculateProductDepo2.depositTotal,
            _result = _calculateProductDepo2.result;
          if (_result) {
            total = _depositTotal;
            protocolIds.push.apply(protocolIds, _toConsumableArray((depositData === null || depositData === void 0 ? void 0 : depositData.self_deposit_policy_ids) || []));
            productHasDeposit = true;
          }
        }
      }
      if (bundle !== null && bundle !== void 0 && bundle.length) {
        total = bundle.reduce(function (accumulator, currBundleProduct) {
          var depositData = currBundleProduct === null || currBundleProduct === void 0 ? void 0 : currBundleProduct.custom_deposit_data;
          var _calculateProductDepo3 = calculateProductDeposit({
              depositData: depositData,
              total: currBundleProduct === null || currBundleProduct === void 0 ? void 0 : currBundleProduct.price,
              num: (currBundleProduct === null || currBundleProduct === void 0 ? void 0 : currBundleProduct.num) || 1
            }),
            depositTotal = _calculateProductDepo3.depositTotal,
            result = _calculateProductDepo3.result;
          if (result) {
            protocolIds.push.apply(protocolIds, _toConsumableArray((depositData === null || depositData === void 0 ? void 0 : depositData.self_deposit_policy_ids) || []));
            productHasDeposit = true;
            return accumulator.plus(depositTotal);
          }
          return accumulator;
        }, new Decimal(0));
      }
    }
    if (productHasDeposit) {
      var ids = new Set(protocolIds);
      var protocols = allProtocols.filter(function (item) {
        return ids.has(item.id);
      });
      return {
        total: total.toNumber(),
        protocols: protocols
      };
    }
    return null;
  }
  return null;
};

/**
 * 计算商品定金
 * @param params 参数
 * @returns 商品定金
 */
export var calculateProductDeposit = function calculateProductDeposit(params) {
  var depositData = params.depositData,
    total = params.total,
    num = params.num;
  if (!depositData) {
    return {
      result: false,
      depositTotal: new Decimal(0)
    };
  }
  var _ref3 = depositData || {},
    deposit_fixed = _ref3.deposit_fixed,
    deposit_percentage = _ref3.deposit_percentage;
  if (typeof deposit_fixed === 'string' && typeof deposit_percentage === 'string') {
    var depositFixed = new Decimal(deposit_fixed || 0);
    var depositPercent = new Decimal(deposit_percentage || 0);
    var productTotalPrice = new Decimal(total || 0);
    var deposit = depositFixed.plus(depositPercent.times(productTotalPrice));
    return {
      depositTotal: deposit.times(num),
      result: true
    };
  }
  return {
    result: false,
    depositTotal: new Decimal(0)
  };
};