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 _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 _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 _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 _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; }
import { getDiscountTime, flexibleObj } from "../../utils";
import { formatAmount } from '@pisell/utils';
import { isDayBooking, isDayBookingProduct, isNormalProductByDurationSchedule } from "../../info/service2/utils";
import { getBundleDiscountList } from "./utils";
export var getRelationDetailsTotal = function getRelationDetailsTotal(relation_details) {
  var total = 0;
  var _iterator = _createForOfIteratorHelper(relation_details),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var item = _step.value;
      var number = item.product_quantity || item.num;
      var price = item.payment_price || item.price;
      total += Number(price) * Number(number);
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return total;
};
export var getProductDiscountProductDiscountDifference = function getProductDiscountProductDiscountDifference(product) {
  var _product$_extend;
  var mainDiscountList = product.discount_list || [];
  var bundleDiscountList = getBundleDiscountList(((_product$_extend = product._extend) === null || _product$_extend === void 0 || (_product$_extend = _product$_extend.other) === null || _product$_extend === void 0 ? void 0 : _product$_extend.bundle) || []);
  var discountList = [].concat(_toConsumableArray(mainDiscountList), _toConsumableArray(bundleDiscountList));
  return discountList.reduce(function (pre, cur) {
    var _cur$metadata;
    return pre + ((cur === null || cur === void 0 || (_cur$metadata = cur.metadata) === null || _cur$metadata === void 0 ? void 0 : _cur$metadata.product_discount_difference) || 0);
  }, 0);
};

/**
 * 总金额
 * @param state 
 * @returns 
 */
var getProductAmount = function getProductAmount(state, isEdit) {
  var price = 0;
  var duration = 0;
  // 是否是跨日预约
  var isDay = isDayBooking(state);
  if (isEdit) {
    // 计算总价  服务 和 附加商品
    if (state !== null && state !== void 0 && state.service || state !== null && state !== void 0 && state.addons) {
      var _iterator2 = _createForOfIteratorHelper(state === null || state === void 0 ? void 0 : state.service.value),
        _step2;
      try {
        for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) {
          var _item = _step2.value;
          // 跨日预约
          if (isDay || isNormalProductByDurationSchedule(_item)) {
            var quantity = _item._extend.quantity || 1;
            price += Number(_item._extend.total) * Number(quantity);

            // 商品折扣差价
            price -= getProductDiscountProductDiscountDifference(_item);

            // 普通商品不能加到时长上
            var _duration = isDayBookingProduct(_item, state) ? _item._extend.duration : 0;
            duration += _duration;
          } else {
            var _quantity = _item._extend.quantity || 1;
            price += Number(_item._extend.total) * Number(_quantity);

            // 附加商品
            price += getRelationDetailsTotal(_item._extend.relation_details || []);

            // 商品折扣差价
            price -= getProductDiscountProductDiscountDifference(_item);
            duration += flexibleObj.getValue(_item._extend.duration);
          }
        }

        // 不是跨日预约才执行
      } catch (err) {
        _iterator2.e(err);
      } finally {
        _iterator2.f();
      }
      if (!isDay) {
        var _iterator3 = _createForOfIteratorHelper(state.addons.value),
          _step3;
        try {
          for (_iterator3.s(); !(_step3 = _iterator3.n()).done;) {
            var item = _step3.value;
            price += Number(item._extend.total) * item._extend.quantity;
          }
        } catch (err) {
          _iterator3.e(err);
        } finally {
          _iterator3.f();
        }
      }
    }
  } else {
    var _state$bookingDetail, _state$service;
    price = Number((_state$bookingDetail = state.bookingDetail) === null || _state$bookingDetail === void 0 ? void 0 : _state$bookingDetail.product_expect_amount);
    var services = (state === null || state === void 0 || (_state$service = state.service) === null || _state$service === void 0 ? void 0 : _state$service.value) || [];
    duration = services.reduce(function (pre, cur) {
      var current = 0;
      if (isDay) {
        // 普通商品不能加到时长上
        var _duration2 = isDayBookingProduct(cur, state) ? cur._extend.duration : 0;
        current = _duration2 || 0;
      } else {
        var _cur$_extend;
        current = flexibleObj.getValue(((_cur$_extend = cur._extend) === null || _cur$_extend === void 0 ? void 0 : _cur$_extend.duration) || 0);
      }
      return pre + current;
    }, 0);
  }
  return {
    price: Number(price),
    duration: getDiscountTime(duration, isDay)
  };
};
var getProductItemTax = function getProductItemTax(item, bookingDetail) {
  var price = 0;
  // 折扣后的金额 = 商品金额 - 商品折扣
  var productDiscountPrice = Number(item.total);
  // 店铺税 = 折扣后的金额 * 店铺税率 * 商品是否收税  (is_charge_tax 0 为不收税)
  var shopTax = productDiscountPrice * Number(bookingDetail.tax_rate) * Number(item.is_charge_tax);
  // 店铺税率  =  1 + 店铺税率 * 是否含税
  var shopTaxRate = 1 + bookingDetail.tax_rate * bookingDetail.is_price_include_tax;

  // 结果
  var res = shopTax / shopTaxRate * item.quantity;
  price += res;
  return price;
};

/**
 * @title: 
 * @description: 后端返回的商品使用 payment_price(均摊后的最终价)  新添加的商品使用 total(不包含整单折扣)
 * @param {any} item
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-02-28 10:56
 */
var getTotal = function getTotal(item) {
  return item._extend.payment_price !== undefined ? item._extend.payment_price : item._extend.total;
};

/**
 * 税费
 * @param state 
 * @returns 
 */
var getTax = function getTax(state, isEdit) {
  var price = 0;

  // 新建不计算税费
  if (!state.bookingId || !state.bookingDetail) {
    return 0;
  }
  if (!isEdit) {
    var _state$bookingDetail2;
    return Number((_state$bookingDetail2 = state.bookingDetail) === null || _state$bookingDetail2 === void 0 ? void 0 : _state$bookingDetail2.tax_fee);
  }
  if (state !== null && state !== void 0 && state.service || state !== null && state !== void 0 && state.addons) {
    var _iterator4 = _createForOfIteratorHelper(state === null || state === void 0 ? void 0 : state.service.value),
      _step4;
    try {
      for (_iterator4.s(); !(_step4 = _iterator4.n()).done;) {
        var item = _step4.value;
        price += getProductItemTax(_objectSpread(_objectSpread({}, item), {}, {
          total: getTotal(item),
          price: item._extend.price,
          quantity: item._extend.quantity
        }), state.bookingDetail);
      }
    } catch (err) {
      _iterator4.e(err);
    } finally {
      _iterator4.f();
    }
    var _iterator5 = _createForOfIteratorHelper(state.addons.value),
      _step5;
    try {
      for (_iterator5.s(); !(_step5 = _iterator5.n()).done;) {
        var _item2 = _step5.value;
        price += getProductItemTax(_objectSpread(_objectSpread({}, _item2), {}, {
          total: getTotal(_item2),
          price: _item2._extend.price,
          quantity: _item2._extend.quantity
        }), state.bookingDetail);
      }
    } catch (err) {
      _iterator5.e(err);
    } finally {
      _iterator5.f();
    }
  }
  return price;
};
var getPaySurchargeFee = function getPaySurchargeFee(state) {
  var bookingDetail = state.bookingDetail,
    bookingId = state.bookingId;

  // 新增为 0
  if (!bookingDetail || !bookingId) return 0;
  return Number(bookingDetail.pay_processing_fee) + Number(bookingDetail.gateway_fee);
};

// const getSurcharge = (state: any) => {
//   const { bookingDetail, bookingId } = state;
//   let obj = {
//     list: [],
//     price: 0
//   }

//   // 新增为 0
//   if (!bookingDetail || !bookingId) return obj;

//   const surchargeList = bookingDetail.surcharge || [];

//   for (let item of surchargeList) {
//     obj.price += Number(item.amount)
//   }
//   obj.list = surchargeList;

//   return obj;
// }

/**
 * 其他金额
 * @param state 
 * @returns 
 */
var getOtherAmount = function getOtherAmount(state) {
  var bookingDetail = state.bookingDetail,
    bookingId = state.bookingId;

  // 新增为 0
  if (!bookingDetail || !bookingId) return 0;
  return Number(bookingDetail.surcharge_fee);
};

/**
 * 已付金额 包含手续费
 * @param state 
 * @returns 
 */
var getPaidAmount = function getPaidAmount(state) {
  var _state$bookingDetail3;
  var bookingDetail = state.bookingDetail,
    bookingId = state.bookingId;
  // 新增为 0
  if (!bookingDetail || !bookingId) return 0;
  return Number((_state$bookingDetail3 = state.bookingDetail) === null || _state$bookingDetail3 === void 0 ? void 0 : _state$bookingDetail3.paid_amount) || 0;
};

/**
 * 订单已付金额  不包含手续费
 * @param state 
 * @returns 
 */
var getOrderPaidAmount = function getOrderPaidAmount(state) {
  var _state$bookingDetail4;
  var bookingDetail = state.bookingDetail,
    bookingId = state.bookingId;
  // 新增为 0
  if (!bookingDetail || !bookingId) return 0;
  return Number((_state$bookingDetail4 = state.bookingDetail) === null || _state$bookingDetail4 === void 0 ? void 0 : _state$bookingDetail4.order_paid_amount) || 0;
};
export var is_price_include_tax = function is_price_include_tax(state) {
  var _state$bookingDetail5;
  return (_state$bookingDetail5 = state.bookingDetail) === null || _state$bookingDetail5 === void 0 ? void 0 : _state$bookingDetail5.is_price_include_tax;
};
var getExpectAmount = function getExpectAmount(_ref) {
  var price = _ref.price,
    tax = _ref.tax,
    otherAmount = _ref.otherAmount,
    shopDiscount = _ref.shopDiscount,
    state = _ref.state,
    isEdit = _ref.isEdit;
  if (!isEdit) {
    var _state$bookingDetail6;
    return Number((_state$bookingDetail6 = state.bookingDetail) === null || _state$bookingDetail6 === void 0 ? void 0 : _state$bookingDetail6.expect_amount) || 0;
  }
  var _tax = tax;

  // 新增时, 税费为0
  if (state.bookingDetail && is_price_include_tax(state)) {
    _tax = 0;
  }
  // 商品价格 + 税费 + 其他金额 - 整单折扣
  return price + _tax + otherAmount - shopDiscount;
};
var getTotalRefundAmount = function getTotalRefundAmount(state) {
  var _state$bookingDetail7;
  return Number((_state$bookingDetail7 = state.bookingDetail) === null || _state$bookingDetail7 === void 0 ? void 0 : _state$bookingDetail7.total_refund_amount) || 0;
};
var getShopDiscount = function getShopDiscount(state) {
  var _state$bookingDetail8;
  return Number((_state$bookingDetail8 = state.bookingDetail) === null || _state$bookingDetail8 === void 0 ? void 0 : _state$bookingDetail8.shop_discount) || 0;
};
var getRoundingAmount = function getRoundingAmount(state) {
  var _state$bookingDetail9;
  return Number(state === null || state === void 0 || (_state$bookingDetail9 = state.bookingDetail) === null || _state$bookingDetail9 === void 0 ? void 0 : _state$bookingDetail9.rounding_amount) || 0;
};
var getSumTotalAmount = function getSumTotalAmount(_ref2) {
  var expectAmount = _ref2.expectAmount,
    roundingAmount = _ref2.roundingAmount;
  return expectAmount + roundingAmount;
};

/**
 * 总金额
 * @param state 
 * @returns 
 */
export var getSumTotal = function getSumTotal(state, isEdit) {
  // 商品金额
  var _getProductAmount = getProductAmount(state, isEdit),
    price = _getProductAmount.price,
    duration = _getProductAmount.duration;

  // 舍入金额
  var roundingAmount = getRoundingAmount(state);

  // 税费
  var tax = getTax(state, isEdit);

  // 支付手续费
  var paySurchargeFee = getPaySurchargeFee(state);

  // 其他金额
  var otherAmount = getOtherAmount(state);

  // 已付金额 (包含手续费)
  var paidAmount = getPaidAmount(state);

  // 订单实际已支付金额
  var orderPaidAmount = getOrderPaidAmount(state);

  // 退款金额
  var totalRefundAmount = getTotalRefundAmount(state);

  // 整单折扣
  var shopDiscount = getShopDiscount(state);

  // 总计(总订单金额) 商品金额 + 税费 + 附加费
  var expectAmount = getExpectAmount({
    price: price,
    tax: tax,
    otherAmount: otherAmount,
    shopDiscount: shopDiscount,
    state: state,
    isEdit: isEdit
  });

  // 总支付金额  总计
  var sumTotalAmount = getSumTotalAmount({
    expectAmount: expectAmount,
    roundingAmount: roundingAmount
  });

  // 未支付的金额  负数代表着欠款
  var notPaidAmount = Number(formatAmount(sumTotalAmount, 2, '')) - orderPaidAmount;

  // 实付金额    已付金额
  var actualPaidAmount = paidAmount;

  // 欠款金额
  var dueAmount = notPaidAmount < 0 ? Number(formatAmount(notPaidAmount + totalRefundAmount, 2, '')) : 0;
  return {
    productAmount: price,
    duration: duration,
    tax: tax,
    shopDiscount: shopDiscount,
    // taxText,
    otherAmount: otherAmount,
    sumTotalAmount: sumTotalAmount,
    paidAmount: paidAmount,
    notPaidAmount: notPaidAmount,
    paySurchargeFee: paySurchargeFee,
    expectAmount: expectAmount,
    actualPaidAmount: actualPaidAmount,
    orderPaidAmount: orderPaidAmount,
    totalRefundAmount: totalRefundAmount,
    dueAmount: dueAmount,
    roundingAmount: roundingAmount
  };
};