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 _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; }
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 { flexibleObj, isNowTime, getNowTime } from "../../utils";
import { isWalkIn } from "../../utils";
import { getSumCapacity } from "../../info2/utilsByBooking";
import { getDays } from "../../utils";
import { appointmentTypes } from "../../info/service2/status";
import { isDaysBooking, formatDayTime, isEventBooking, isNormalProductByDurationSchedule, genRowKey } from "../../info/service2/utils";
import { isArr, locales, sendWarningLog, getUniqueId, isNumber, isString } from '@pisell/utils';
import { PisellToast } from '@pisell/materials';
import { getClientName } from "../../../../plus/clientName/utils";
import { cloneDeep } from 'lodash';
import Decimal from 'decimal.js';
import { getOptionDiscountAmount } from "./amount";
var formatNote = function formatNote(data) {
  var _data$notes;
  return ((_data$notes = data.notes) === null || _data$notes === void 0 ? void 0 : _data$notes.orderNote) || '';
};
var formatCustomer = function formatCustomer(data) {
  var _data$client, _data$client2, _data$client3, _data$client4, _data$client5, _data$client6;
  var id = (_data$client = data.client) === null || _data$client === void 0 || (_data$client = _data$client.value) === null || _data$client === void 0 ? void 0 : _data$client.id;
  if (isWalkIn(id)) {
    id = 1;
  }
  return {
    customer_id: id,
    customer_name: getClientName((_data$client2 = data.client) === null || _data$client2 === void 0 ? void 0 : _data$client2.value),
    email: (_data$client3 = data.client) === null || _data$client3 === void 0 || (_data$client3 = _data$client3.value) === null || _data$client3 === void 0 ? void 0 : _data$client3.email,
    phone: ((_data$client4 = data.client) === null || _data$client4 === void 0 || (_data$client4 = _data$client4.value) === null || _data$client4 === void 0 ? void 0 : _data$client4.phone) || ((_data$client5 = data.client) === null || _data$client5 === void 0 || (_data$client5 = _data$client5.value) === null || _data$client5 === void 0 ? void 0 : _data$client5.mobile),
    country_calling_code: (_data$client6 = data.client) === null || _data$client6 === void 0 || (_data$client6 = _data$client6.value) === null || _data$client6 === void 0 ? void 0 : _data$client6.country_calling_code
  };
};

/**
 * @title: 套餐单规格信息
 * @description:
 * @param {any} option
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-02-19 09:26
 */
export var formatProductOption = function formatProductOption(option) {
  if (!option) {
    return [];
  }
  return option.map(function (d) {
    return {
      num: d.num,
      option_group_item_id: d.product_option_item_id || d.option_group_item_id,
      option_group_id: d.option_group_id,
      custom_add_price: Number(d === null || d === void 0 ? void 0 : d.add_price)
    };
  });
};

/**
 * @title: 添加套餐警告
 * @description:
 * @param {any} data
 * @return {*}
 * @Author: WangHan
 * @Date: 2025-03-05 18:23
 */
var log = function log(data) {
  sendWarningLog({
    title: '预约2.0下单无效的套餐商品数据',
    content: [{
      key: 'bundle',
      value: JSON.stringify(data)
    }, {
      key: '日期',
      value: dayjs().format('YYYY-MM-DD HH:mm')
    }]
  });
};

/**
 * @title: 套餐信息
 * @description:
 * @param {any} bundle
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-02-19 09:26
 */
export var formatProductBundle = function formatProductBundle(bundle, is_price_include_tax) {
  if (!bundle) {
    return;
  }

  // 无效的商品套餐信息
  try {
    var errorBundles = bundle === null || bundle === void 0 ? void 0 : bundle.filter(function (d) {
      return !(d !== null && d !== void 0 && d.group_id) || !(d !== null && d !== void 0 && d.id) || !(d !== null && d !== void 0 && d._bundle_product_id);
    });
    if ((errorBundles === null || errorBundles === void 0 ? void 0 : errorBundles.length) > 0) {
      log(errorBundles);
    }
  } catch (error) {}
  return bundle.map(function (d) {
    var _d$metadata, _d$original_price;
    var option = formatProductOption(d.option);
    var option_price = option.reduce(function (temp, item) {
      return temp + Number(item.num) * item.custom_add_price;
    }, 0);
    var product_discount_difference = ((d === null || d === void 0 ? void 0 : d.discount_list) || []).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);

    // 提取套餐商品的唯一标识元数据
    var metadata = {};
    var _metadata = (_d$metadata = d === null || d === void 0 ? void 0 : d.metadata) !== null && _d$metadata !== void 0 ? _d$metadata : {};

    // 定义需要提取的元数据字段列表（便于扩展）
    var targetFields = ['custom_product_bundle_map_id', 'unique_identification_number'];
    targetFields.forEach(function (field) {
      if (_metadata[field]) {
        metadata[field] = _metadata[field];
      }
    });
    return {
      "is_charge_tax": d.is_charge_tax,
      "tax_fee": d.tax_fee,
      "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,
      "price": Number(d === null || d === void 0 ? void 0 : d.product_price),
      "price_type": d === null || d === void 0 ? void 0 : d.price_type,
      "price_type_ext": d === null || d === void 0 ? void 0 : d.price_type_ext,
      "custom_price": (d === null || d === void 0 ? void 0 : d.custom_price) || Math.abs(new Decimal((_d$original_price = d === null || d === void 0 ? void 0 : d.original_price) !== null && _d$original_price !== void 0 ? _d$original_price : d === null || d === void 0 ? void 0 : d.product_price).sub(option_price).toNumber()).toFixed(2),
      "custom_price_type": d === null || d === void 0 ? void 0 : d.price_type,
      "option": option,
      "bundle_selling_price": Math.abs(d === null || d === void 0 ? void 0 : d.price),
      // "bundle_sum_price": d?.original_price || d?.original_total,
      is_price_include_tax: is_price_include_tax,
      "metadata": _objectSpread({
        custom_product_bundle_map_id: d._id,
        // 子商品单数量附加费
        "surcharge_fee": d.surcharge_fee,
        // 可选，附加费均摊舍入金额
        "surcharge_rounding_remainder": d.surcharge_rounding_remainder,
        // 可选，税费均摊舍入金额（折后税费）
        "tax_fee_rounding_remainder": d.tax_fee_rounding_remainder,
        relation_surcharge_ids: d.relation_surcharge_ids || [],
        product_discount_difference: product_discount_difference
      }, metadata)
    };
  });
};

/**
 * 获取子商品折扣信息
 * @param item
 */
export var getBundleDiscountList = function getBundleDiscountList(bundle) {
  if (!bundle) {
    return [];
  }
  var discountList = [];
  bundle.forEach(function (d) {
    if (d.discount_list && isArr(d.discount_list)) {
      d.discount_list.forEach(function (item) {
        if (item !== null && item !== void 0 && item.id) {
          item.order_discount_id = item.id;
        }
      });
      discountList.push.apply(discountList, _toConsumableArray(d.discount_list.filter(function (item) {
        return !item.id;
      })));
    }
  });
  return discountList;
};
var getSubType = function getSubType(item) {
  var _item$duration;
  var _type = (_item$duration = item.duration) === null || _item$duration === void 0 ? void 0 : _item$duration.type;
  // 目前不支持跨天
  if (_type) {
    return _type;
  }
  return 'minutes';
};
var formatRelationDetails = function formatRelationDetails(list) {
  return (list || []).map(function (item) {
    return {
      num: item.product_quantity,
      price: item.original_price || 0,
      product_id: item.product_id,
      is_charge_tax: item.is_charge_tax,
      order_detail_id: item.order_detail_id,
      tax_fee: item.tax_fee,
      metadata: {
        // 可选，税费均摊舍入金额（折后税费）
        tax_fee_rounding_remainder: item.tax_fee_rounding_remainder
      }
    };
  });
};
/**
 * @title: 传入资源，如果有子资源，会根据组合资源的 capacity 计算修改子资源的 capacity
 * @description:
 * @param {object} resource
 * @return {*}
 * @Author: jinglin.tan
 */
export var checkSubResourcesCapacity = function checkSubResourcesCapacity(resource) {
  if (resource.children && resource.children.length) {
    var countCapacity = resource.capacity;
    resource.children.forEach(function (child) {
      if (child.capacity <= countCapacity) {
        countCapacity -= child.capacity;
      } else {
        child.capacity = countCapacity;
        countCapacity = 0;
      }
    });
  }
};
export var checkResourcesFormat = function checkResourcesFormat(resources, service, isChild) {
  return resources.map(function (resource) {
    var _resource$children;
    if (!isChild) {
      resource.capacity = getSumCapacity({
        cacheItem: service
      }, false);
    }
    checkSubResourcesCapacity(resource);
    return {
      children: (_resource$children = resource.children) !== null && _resource$children !== void 0 && _resource$children.length ? checkResourcesFormat(resource.children, service, true) : undefined,
      form_id: resource.form_id,
      relation_type: resource.relation_type || 'form',
      relation_id: resource.relation_id || 0,
      capacity: resource.capacity,
      like_status: resource.like_status || 'common',
      metadata: resource.metadata || {}
    };
  });
};
var formatResource = function formatResource(service) {
  if (!service._extend.resource) {
    return undefined;
  }
  try {
    return Object.values(service._extend.resource).reduce(function (pre, cur) {
      var newList = checkResourcesFormat(cur, service);
      pre = pre.concat(newList);
      return pre;
    }, []);
  } catch (err) {
    return undefined;
  }
};

/**
 * @title: 格式化子预约的holder数据
 * @description:
 * @param {any} state
 * @param {any} item
 * @param {any} values
 * @return {*}
 * @Author: WangHan
 * @Date: 2024-12-07 14:52
 */
var formatHolders = function formatHolders(state, item, values) {
  var _state$bookingConfig, _item$_extend, _item$_extend2, _item$_extend3, _item$_extend4;
  var form_id = (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 || (_state$bookingConfig = _state$bookingConfig.appointment_subject) === null || _state$bookingConfig === void 0 ? void 0 : _state$bookingConfig.form_id) || 0;
  var form_record = (_item$_extend = item._extend) !== null && _item$_extend !== void 0 && _item$_extend.holder_id ? [(_item$_extend2 = item._extend) === null || _item$_extend2 === void 0 ? void 0 : _item$_extend2.holder_id] : [];
  if ((_item$_extend3 = item._extend) !== null && _item$_extend3 !== void 0 && _item$_extend3.holder_id && isArr((_item$_extend4 = item._extend) === null || _item$_extend4 === void 0 ? void 0 : _item$_extend4.holder_id)) {
    var _item$_extend5;
    form_record = (_item$_extend5 = item._extend) === null || _item$_extend5 === void 0 ? void 0 : _item$_extend5.holder_id;
  }
  var obj = {
    customer_id: values.customer_id,
    form_id: form_id,
    form_record: form_record
  };

  // 连锁加盟子店铺 增加参数
  if (state.isFranchisee) {
    obj.is_source_shop = 1;
  }
  return obj;
};

/**
 * @title: 格式化商品单价
 * @description:
 * @param {any} item
 * @return {*}
 * @Author: WangHan
 * @Date: 2024-12-23 12:05
 */
export var formatProductPrice = function formatProductPrice(item) {
  var _item$_extend6, _item$price, _item$_extend7, _item$_extend8, _item$_extend9, _item$variant;
  var other = (_item$_extend6 = item._extend) === null || _item$_extend6 === void 0 ? void 0 : _item$_extend6.other;
  var price = Number((_item$price = item === null || item === void 0 ? void 0 : item.price) !== null && _item$price !== void 0 ? _item$price : item === null || item === void 0 || (_item$_extend7 = item._extend) === null || _item$_extend7 === void 0 ? void 0 : _item$_extend7.price);
  if (isString((_item$_extend8 = item._extend) === null || _item$_extend8 === void 0 ? void 0 : _item$_extend8.priceOverride) || isNumber((_item$_extend9 = item._extend) === null || _item$_extend9 === void 0 ? void 0 : _item$_extend9.priceOverride)) {
    var _item$_extend10;
    price = Number(item === null || item === void 0 || (_item$_extend10 = item._extend) === null || _item$_extend10 === void 0 ? void 0 : _item$_extend10.price);
  }

  // 组合规格: 根据当前选择的组合规格id 和商品的组合规格列表 获取当前商品的价格
  if ((other === null || other === void 0 ? void 0 : other.product_variant_id) > 0 && (item === null || item === void 0 || (_item$variant = item.variant) === null || _item$variant === void 0 ? void 0 : _item$variant.length) > 0) {
    var variant = item.variant.find(function (d) {
      return d.id === (other === null || other === void 0 ? void 0 : other.product_variant_id);
    });
    if (variant) {
      price = Number(variant === null || variant === void 0 ? void 0 : variant.price) || 0;
    }
  }

  // 单规格， 单价 + 单规格价格
  if (other !== null && other !== void 0 && other.option) {
    var _other$option;
    price = other === null || other === void 0 || (_other$option = other.option) === null || _other$option === void 0 ? void 0 : _other$option.reduce(function (pre, cur) {
      return pre + Number(cur.price) * Number(cur.num);
    }, price);
  }
  return price;
};

/**
 * checkout2.0: 单个数量商品总价（原价）,包含所有套餐子商品金额、报价单等等
 * @param item
 * @returns
 */
export var formatOriginalPrice = function formatOriginalPrice(item) {
  var _item$_extend11;
  return Number((_item$_extend11 = item._extend) === null || _item$_extend11 === void 0 ? void 0 : _item$_extend11.origin_total);
};

/**
 * 获取套餐子商品折扣差价
 * @param item
 * @returns
 */
var getBundleProductDiscountDifference = function getBundleProductDiscountDifference(item) {
  var _item$_extend12, _item$_extend13, _item$_extend14;
  if (!((_item$_extend12 = item._extend) !== null && _item$_extend12 !== void 0 && (_item$_extend12 = _item$_extend12.other) !== null && _item$_extend12 !== void 0 && _item$_extend12.bundle) || !isArr((_item$_extend13 = item._extend) === null || _item$_extend13 === void 0 || (_item$_extend13 = _item$_extend13.other) === null || _item$_extend13 === void 0 ? void 0 : _item$_extend13.bundle)) {
    return new Decimal(0).toNumber();
  }
  var discountDifference = new Decimal(0);
  getBundleDiscountList(((_item$_extend14 = item._extend) === null || _item$_extend14 === void 0 || (_item$_extend14 = _item$_extend14.other) === null || _item$_extend14 === void 0 ? void 0 : _item$_extend14.bundle) || []).forEach(function (cur) {
    var _cur$metadata2;
    discountDifference = discountDifference.add(new Decimal(((_cur$metadata2 = cur.metadata) === null || _cur$metadata2 === void 0 ? void 0 : _cur$metadata2.product_discount_difference) || 0));
  });
  return discountDifference.toNumber();
};

/**
 * checkout2.0: 商品维度折扣后价格, original_price - 商品折扣金额（商品手动折扣等等）
 * @param item
 * @returns
 */
export var formatSellingPrice = function formatSellingPrice(item) {
  var _item$_extend15;
  return Number((_item$_extend15 = item._extend) === null || _item$_extend15 === void 0 ? void 0 : _item$_extend15.total);
};
var formatMetaData = function formatMetaData(item, isMultiDayPrices) {
  var _item$_extend16, _item$_extend$holder_, _item$_extend17, _item$_extend18, _item$_extend20;
  var metadata = {};
  if ((_item$_extend16 = item._extend) !== null && _item$_extend16 !== void 0 && _item$_extend16.capacity) {
    metadata.capacity = item._extend.capacity;
  }
  if (item._extend.groupId) {
    metadata.groupId = item._extend.groupId;
  }
  // if (item._extend?.holder_id) {
  metadata.holder_id = (_item$_extend$holder_ = (_item$_extend17 = item._extend) === null || _item$_extend17 === void 0 ? void 0 : _item$_extend17.holder_id) !== null && _item$_extend$holder_ !== void 0 ? _item$_extend$holder_ : null;
  // }
  if (isMultiDayPrices && (_item$_extend18 = item._extend) !== null && _item$_extend18 !== void 0 && _item$_extend18.multiDayPrices) {
    var _item$_extend19;
    metadata.multiDayPrices = (_item$_extend19 = item._extend) === null || _item$_extend19 === void 0 ? void 0 : _item$_extend19.multiDayPrices;
  }
  if ((_item$_extend20 = item._extend) !== null && _item$_extend20 !== void 0 && _item$_extend20.unique_identification_number) {
    var _item$_extend21;
    metadata.unique_identification_number = (_item$_extend21 = item._extend) === null || _item$_extend21 === void 0 ? void 0 : _item$_extend21.unique_identification_number;
  }
  if (item.discount_list && isArr(item.discount_list)) {
    metadata.product_discount_difference = item.discount_list.filter(function (item) {
      var _item$metadata;
      return !(item !== null && item !== void 0 && (_item$metadata = item.metadata) !== null && _item$metadata !== void 0 && _item$metadata.custom_product_bundle_map_id);
    }).reduce(function (pre, cur) {
      var _cur$metadata3;
      return pre + ((cur === null || cur === void 0 || (_cur$metadata3 = cur.metadata) === null || _cur$metadata3 === void 0 ? void 0 : _cur$metadata3.product_discount_difference) || 0);
    }, 0);
  }
  return metadata;
};

/**
 * @title: 格式化商品 metadata
 * @description: 处理附加费、税费、唯一标识、赠品父商品信息等
 * @param {any} item 当前商品
 * @param {any[]} list 商品列表（可选），用于赠品商品查找父商品信息
 * @return {any} metadata 对象
 */
var formatProductMetadata = function formatProductMetadata(item, list) {
  var _item$_extend22, _item$metadata2, _item$_extend24, _item$metadata4, _item$_extend26, _item$metadata6, _item$_extend28, _item$_extend30, _item$metadata8, _item$_extend32, _item$metadata10, _item$_extend34;
  var metadata = {};

  // 主商品+非原价(加减价)子商品附加费
  if ((_item$_extend22 = item._extend) !== null && _item$_extend22 !== void 0 && _item$_extend22.surcharge_fee || (_item$metadata2 = item.metadata) !== null && _item$metadata2 !== void 0 && _item$metadata2.main_product_attached_bundle_surcharge_fee) {
    var _item$_extend23, _item$metadata3;
    metadata.main_product_attached_bundle_surcharge_fee = ((_item$_extend23 = item._extend) === null || _item$_extend23 === void 0 ? void 0 : _item$_extend23.surcharge_fee) || ((_item$metadata3 = item.metadata) === null || _item$metadata3 === void 0 ? void 0 : _item$metadata3.main_product_attached_bundle_surcharge_fee);
  }

  // 主商品+非原价(加减价)子商品税费
  if ((_item$_extend24 = item._extend) !== null && _item$_extend24 !== void 0 && _item$_extend24.main_product_attached_bundle_tax_fee || (_item$metadata4 = item.metadata) !== null && _item$metadata4 !== void 0 && _item$metadata4.main_product_attached_bundle_tax_fee) {
    var _item$_extend25, _item$metadata5;
    metadata.main_product_attached_bundle_tax_fee = ((_item$_extend25 = item._extend) === null || _item$_extend25 === void 0 ? void 0 : _item$_extend25.main_product_attached_bundle_tax_fee) || ((_item$metadata5 = item.metadata) === null || _item$metadata5 === void 0 ? void 0 : _item$metadata5.main_product_attached_bundle_tax_fee);
  }

  // 可选，附加费均摊舍入金额
  if ((_item$_extend26 = item._extend) !== null && _item$_extend26 !== void 0 && _item$_extend26.surcharge_rounding_remainder || (_item$metadata6 = item.metadata) !== null && _item$metadata6 !== void 0 && _item$metadata6.surcharge_rounding_remainder) {
    var _item$_extend27, _item$metadata7;
    metadata.surcharge_rounding_remainder = ((_item$_extend27 = item._extend) === null || _item$_extend27 === void 0 ? void 0 : _item$_extend27.surcharge_rounding_remainder) || ((_item$metadata7 = item.metadata) === null || _item$metadata7 === void 0 ? void 0 : _item$metadata7.surcharge_rounding_remainder);
  }

  // 可选，税费均摊舍入金额（折后税费）
  if ((_item$_extend28 = item._extend) !== null && _item$_extend28 !== void 0 && _item$_extend28.tax_fee_rounding_remainder) {
    var _item$_extend29;
    metadata.tax_fee_rounding_remainder = (_item$_extend29 = item._extend) === null || _item$_extend29 === void 0 ? void 0 : _item$_extend29.tax_fee_rounding_remainder;
  }

  // 使用的附加费id列表
  if ((_item$_extend30 = item._extend) !== null && _item$_extend30 !== void 0 && _item$_extend30.relation_surcharge_ids || (_item$metadata8 = item.metadata) !== null && _item$metadata8 !== void 0 && _item$metadata8.relation_surcharge_ids) {
    var _item$_extend31, _item$metadata9;
    metadata.relation_surcharge_ids = ((_item$_extend31 = item._extend) === null || _item$_extend31 === void 0 ? void 0 : _item$_extend31.relation_surcharge_ids) || ((_item$metadata9 = item.metadata) === null || _item$metadata9 === void 0 ? void 0 : _item$metadata9.relation_surcharge_ids);
  }
  if ((_item$_extend32 = item._extend) !== null && _item$_extend32 !== void 0 && _item$_extend32.unique_identification_number || (_item$metadata10 = item.metadata) !== null && _item$metadata10 !== void 0 && _item$metadata10.unique_identification_number) {
    var _item$_extend33, _item$metadata11;
    metadata.unique_identification_number = ((_item$_extend33 = item._extend) === null || _item$_extend33 === void 0 ? void 0 : _item$_extend33.unique_identification_number) || ((_item$metadata11 = item.metadata) === null || _item$metadata11 === void 0 ? void 0 : _item$metadata11.unique_identification_number);
  }
  if (item.discount_list && isArr(item.discount_list)) {
    metadata.product_discount_difference = item.discount_list.filter(function (item) {
      var _item$metadata12;
      return !(item !== null && item !== void 0 && (_item$metadata12 = item.metadata) !== null && _item$metadata12 !== void 0 && _item$metadata12.custom_product_bundle_map_id);
    }).reduce(function (pre, cur) {
      var _cur$metadata4;
      return pre + ((cur === null || cur === void 0 || (_cur$metadata4 = cur.metadata) === null || _cur$metadata4 === void 0 ? void 0 : _cur$metadata4.product_discount_difference) || 0);
    }, 0);
  }

  // 赠品商品：设置 gift_card_type 及父商品关联信息
  if (item._giftInfo) {
    metadata.gift_card_type = "promotion";

    // 通过 _giftInfo.sourceProductId 在列表中匹配父商品，获取父商品的 unique_identification_number 和 product_id
    if (list !== null && list !== void 0 && list.length) {
      var parentProduct = list.find(function (listItem) {
        var _item$_giftInfo;
        return listItem._id === ((_item$_giftInfo = item._giftInfo) === null || _item$_giftInfo === void 0 ? void 0 : _item$_giftInfo.sourceProductId);
      });
      if (parentProduct) {
        var _parentProduct$_exten;
        metadata.parent_unique_identification_number = ((_parentProduct$_exten = parentProduct._extend) === null || _parentProduct$_exten === void 0 ? void 0 : _parentProduct$_exten.unique_identification_number) || '';
        metadata.parent_product_id = parentProduct !== null && parentProduct !== void 0 && parentProduct.product_id || parentProduct.product_id === 0 ? parentProduct.product_id : parentProduct.id;
      }
    }
  }

  // 如果 _extend 有unique_identification_number，往 metadata 里补充一个
  if ((_item$_extend34 = item._extend) !== null && _item$_extend34 !== void 0 && _item$_extend34.unique_identification_number) {
    var _item$_extend35;
    metadata.unique_identification_number = (_item$_extend35 = item._extend) === null || _item$_extend35 === void 0 ? void 0 : _item$_extend35.unique_identification_number;
  }
  return metadata;
};

// const formatDiscountList = (list: any[]) => {
//   return list.map(item => {
//     return {
//       amount: item.amount,
//       product_id: item.product_id || item.discount?.product_id,
//       resource_id: item.resource_id || item.discount?.resource_id,
//       title: item.title || item.discount?.title,
//       original_amount: item.original_amount || item.discount?.original_amount,
//       id: item.id,
//       type: item.type,
//     }
//   })
// }

// 获取商品价格 包含组合规格
export var getSourceProductPrice = function getSourceProductPrice(item) {
  var _item$_extend36, _item$price2, _item$_extend37, _item$variant2;
  var other = (_item$_extend36 = item._extend) === null || _item$_extend36 === void 0 ? void 0 : _item$_extend36.other;
  var price = Number((_item$price2 = item === null || item === void 0 ? void 0 : item.price) !== null && _item$price2 !== void 0 ? _item$price2 : (_item$_extend37 = item._extend) === null || _item$_extend37 === void 0 ? void 0 : _item$_extend37.price);

  // 组合规格: 根据当前选择的组合规格id 和商品的组合规格列表 获取当前商品的价格
  if ((other === null || other === void 0 ? void 0 : other.product_variant_id) > 0 && (item === null || item === void 0 || (_item$variant2 = item.variant) === null || _item$variant2 === void 0 ? void 0 : _item$variant2.length) > 0) {
    var variant = item.variant.find(function (d) {
      return d.id === (other === null || other === void 0 ? void 0 : other.product_variant_id);
    });
    if (variant) {
      price = Number(variant === null || variant === void 0 ? void 0 : variant.price) || 0;
    }
  }
  return price;
};

// 获取主商品价格 要增加option
export var getMainProductSellingPrice = function getMainProductSellingPrice(item) {
  var _item$_extend38, _item$_extend39, _item$_extend$other, _item$_extend$other2, _item$_extend40;
  if (!isNumber((_item$_extend38 = item._extend) === null || _item$_extend38 === void 0 ? void 0 : _item$_extend38.main_product_selling_price) && !isString((_item$_extend39 = item._extend) === null || _item$_extend39 === void 0 ? void 0 : _item$_extend39.main_product_selling_price)) {
    return undefined;
  }
  var optionPrice = new Decimal(0);
  // 单规格
  if ((_item$_extend$other = item._extend.other) !== null && _item$_extend$other !== void 0 && _item$_extend$other.option && Array.isArray((_item$_extend$other2 = item._extend.other) === null || _item$_extend$other2 === void 0 ? void 0 : _item$_extend$other2.option)) {
    var _item$_extend$other3;
    optionPrice = (_item$_extend$other3 = item._extend.other) === null || _item$_extend$other3 === void 0 ? void 0 : _item$_extend$other3.option.reduce(function (accumulator, currentValue) {
      var currentPrice = new Decimal(currentValue.price || 0);
      var currentNum = new Decimal(currentValue.num || 0);
      return accumulator.add(currentPrice.mul(currentNum));
    }, optionPrice);
    if (item !== null && item !== void 0 && item.booking_id) {
      optionPrice = optionPrice.sub(getOptionDiscountAmount((item === null || item === void 0 ? void 0 : item.discount_list) || []));
    }
  }
  return new Decimal((_item$_extend40 = item._extend) === null || _item$_extend40 === void 0 ? void 0 : _item$_extend40.main_product_selling_price).add(optionPrice).toNumber();
};

/**
 * @title: 格式化重量信息
 * @description:
 * @param {any} weighing
 * @return {*}
 */
var formatWeightInfo = function formatWeightInfo(weighing) {
  var _weighing$tare, _weighing$tare2;
  if (!weighing) {
    return undefined;
  }
  var unitsMap = {
    KILOGRAMS: 'kg',
    GRAMS: 'g',
    POUNDS: 'lb',
    OUNCES: 'oz'
  };
  return {
    open_sold_weight: !!weighing ? 1 : 0,
    // 商品信息快照
    unit_data_snapshot: weighing.scalePriceProduct,
    // 转化为标准单位的信息
    unit: unitsMap[weighing.unit] || weighing.unit,
    unit_weight: 1,
    unit_price: weighing.unit_price,
    tare_name: ((_weighing$tare = weighing.tare) === null || _weighing$tare === void 0 ? void 0 : _weighing$tare.label) || '',
    tare_weight: ((_weighing$tare2 = weighing.tare) === null || _weighing$tare2 === void 0 ? void 0 : _weighing$tare2.value) || 0,
    weight: weighing.weight || 0,
    net_weight: weighing.net_weight || 0
  };
};

/**
 * @title: 格式化商品数据
 * @description:
 * @param {any} item 当前商品
 * @param {number} quantity 数量（可选）
 * @param {any[]} list 商品列表（可选），用于赠品商品查找父商品信息
 * @return {*}
 * @Author: WangHan
 * @Date: 2024-12-07 14:21
 */
var formatProducts = function formatProducts(item, quantity, list) {
  var _item$_extend41, _getMainProductSellin, _item$_extend42, _item$_extend43, _item$_extend44, _item$_extend45, _item$_extend$tax_fee, _item$metadata13, _item$_extend46;
  if (item !== null && item !== void 0 && item.discount_list) {
    item === null || item === void 0 || item.discount_list.forEach(function (d) {
      if (d !== null && d !== void 0 && d.id) {
        d.order_discount_id = d.id;
      }
    });
  }
  var total = Number(item._extend.total);
  var origin_total = Number(item._extend.origin_total);
  var discount_amount = origin_total - total;
  var bundleDiscountList = getBundleDiscountList(((_item$_extend41 = item._extend) === null || _item$_extend41 === void 0 || (_item$_extend41 = _item$_extend41.other) === null || _item$_extend41 === void 0 ? void 0 : _item$_extend41.bundle) || []);
  var discount_list = _toConsumableArray((item === null || item === void 0 ? void 0 : item.discount_list) || []);
  discount_list.push.apply(discount_list, _toConsumableArray(bundleDiscountList));

  // 加价时type使用change_price
  var discount_type = discount_amount < 0 ? 'change_price' : 'discount';
  discount_list.forEach(function (d) {
    d.metadata = _objectSpread(_objectSpread({}, d.metadata), {}, {
      unique_identification_number: "".concat(item._extend.unique_identification_number, "_").concat(d.discount.resource_id)
    });
  });

  // 非手动折扣
  var notManualDiscount = discount_list.filter(function (item) {
    return item.type !== 'product';
  });
  if (item.isCustomItem) {
    item.product_id = 0;
  }
  return {
    "name": item.name,
    "num": quantity || item._extend.quantity,
    "price": formatProductPrice(item),
    "main_product_selling_price": (_getMainProductSellin = getMainProductSellingPrice(item)) !== null && _getMainProductSellin !== void 0 ? _getMainProductSellin : formatProductPrice(item),
    "source_product_price": getSourceProductPrice(item),
    "product_id": item !== null && item !== void 0 && item.product_id || item.product_id === 0 ? item.product_id : item.id,
    "discount_amount": notManualDiscount.length > 0 ? 0 : discount_amount,
    "product_discount_reason": item._extend.discount_reason || '',
    "is_charge_tax": item.is_charge_tax,
    "note": ((_item$_extend42 = item._extend) === null || _item$_extend42 === void 0 ? void 0 : _item$_extend42.note) || '',
    "discountway": item._extend.discountway || "num",
    "discount_per": item._extend.discount_per,
    "discount_type": item._extend.discount_type || discount_type,
    "order_detail_id": item._extend.order_detail_id || 0,
    "product_bundle": formatProductBundle((_item$_extend43 = item._extend) === null || _item$_extend43 === void 0 || (_item$_extend43 = _item$_extend43.other) === null || _item$_extend43 === void 0 ? void 0 : _item$_extend43.bundle, item.is_price_include_tax),
    "bundle_edit": item._extend.bundle_edit || bundleDiscountList.length ? 1 : 0,
    "product_option_item": formatProductOption((_item$_extend44 = item._extend) === null || _item$_extend44 === void 0 || (_item$_extend44 = _item$_extend44.other) === null || _item$_extend44 === void 0 ? void 0 : _item$_extend44.option),
    "product_variant_id": ((_item$_extend45 = item._extend) === null || _item$_extend45 === void 0 || (_item$_extend45 = _item$_extend45.other) === null || _item$_extend45 === void 0 ? void 0 : _item$_extend45.product_variant_id) || 0,
    "discount_list": notManualDiscount,
    metadata: formatProductMetadata(item, list),
    // checkout 需求新增字段
    "calculated_original_price": formatOriginalPrice(item),
    "calculated_selling_price": formatSellingPrice(item),
    "tax_fee": (_item$_extend$tax_fee = item._extend.tax_fee) !== null && _item$_extend$tax_fee !== void 0 ? _item$_extend$tax_fee : (_item$metadata13 = item.metadata) === null || _item$metadata13 === void 0 ? void 0 : _item$metadata13.main_product_attached_bundle_tax_fee,
    "custom_deposit_data": item.custom_deposit_data,
    is_price_include_tax: item.is_price_include_tax,
    gift_card: item._giftInfo ? 1 : 0,
    product_sku: formatWeightInfo((_item$_extend46 = item._extend) === null || _item$_extend46 === void 0 ? void 0 : _item$_extend46.weighing)
  };
};

/**
 * @title: 格式化跨日预约下的普通商品
 * @description:
 * @param {any} data
 * @param {any} booking_item
 * @return {*}
 * @Author: WangHan
 * @Date: 2024-12-07 14:48
 */
var formatDayRelationProducts = function formatDayRelationProducts(data, booking_item) {
  var list = data.service.value;

  // 过滤出卡片中的普通商品
  var relation_products = list === null || list === void 0 ? void 0 : list.filter(function (item) {
    var _item$_extend47;
    var holderId = (_item$_extend47 = item._extend) === null || _item$_extend47 === void 0 ? void 0 : _item$_extend47.holder_id;
    var bookingHolderId = booking_item._extend.holder_id;
    var isDayBookingProduct = appointmentTypes.includes(item.extension_type);
    return holderId && holderId === bookingHolderId && !isDayBookingProduct;
  });
  relation_products = relation_products.map(function (item) {
    return formatProducts(item);
  });
  return relation_products || [];
};

/**
 * @title: 格式化跨日预约商品列表
 * @description:
 * @param {any} data
 * @return {*}
 * @Author: WangHan
 * @Date: 2024-12-17 11:06
 */
var formatAppointmentProductLists = function formatAppointmentProductLists(data) {
  try {
    var _Array$from;
    var list = data.service.value;

    // 找出预约商品
    list = list.filter(function (item) {
      var _item$_extend48;
      return ((_item$_extend48 = item._extend) === null || _item$_extend48 === void 0 ? void 0 : _item$_extend48.holder_id) && !isNormalProductByDurationSchedule(item);
    });

    // 对预约商品列表根据holder_id进行分组
    var groupMap = new Map();
    list.forEach(function (item) {
      var _item$_extend49;
      var key = (_item$_extend49 = item._extend) === null || _item$_extend49 === void 0 ? void 0 : _item$_extend49.holder_id; // 分组键
      if (!groupMap.has(key)) {
        groupMap.set(key, []);
      }
      groupMap.get(key).push(item);
    });

    // 处理每个分组
    // groupMap.forEach(group => {
    //   // 只给第一个数据增加 relation_products
    //   group[0].relation_products = formatDayRelationProducts(data, group[0])
    // });

    // 将分组的结果还原为数组
    var result = (_Array$from = Array.from(groupMap.values())) === null || _Array$from === void 0 ? void 0 : _Array$from.reduce(function (acc, group) {
      return acc.concat(group);
    }, []);
    return list || [];
  } catch (error) {}
};
var getHolderByIndex = function getHolderByIndex(holder, index) {
  var _holder$form_record;
  return _objectSpread(_objectSpread({}, holder), {}, {
    form_record: [holder === null || holder === void 0 || (_holder$form_record = holder.form_record) === null || _holder$form_record === void 0 ? void 0 : _holder$form_record[index]].filter(Boolean)
  });
};

/**
 * @title: 是否包含跨日预约商品
 * @description:
 * @param {any} data
 * @return {*}
 */
export var getHasMultiDayProduct = function getHasMultiDayProduct(data) {
  var list = data.service.value;
  var isHas = list.some(function (item) {
    var _item$_extend50;
    return (_item$_extend50 = item._extend) === null || _item$_extend50 === void 0 ? void 0 : _item$_extend50.groupId;
  });
  return isHas;
};

/**
 * @title: 预约商品信息
 * @description:
 * @param {any} data
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-02-19 09:26
 */
var formatBookings = function formatBookings(data, values) {
  // 是否是跨日预约
  var isDay = isDaysBooking(data);
  var isEvent = isEventBooking(data);
  // todo 预约商品 普通商品 字段添加
  var list = data.service.value;

  // 格式化跨日预约商品列表
  if (isDay) {
    list = formatAppointmentProductLists(data);
  }
  if (isEvent) {
    list = list.filter(function (d) {
      var _d$_extend;
      return (_d$_extend = d._extend) === null || _d$_extend === void 0 ? void 0 : _d$_extend.holder_id;
    });
  }
  if (!isDay && !isEvent) {
    list = list.filter(function (item) {
      return !isNormalProductByDurationSchedule(item);
    });
  }
  var dayParams = {};
  var eventOtherParams = data.eventOtherParams;
  // const appointment_booking = data?.appointment_bookin
  var bookings = [];
  var obj = {};

  // 预先为所有商品分配 unique_identification_number，确保赠品商品能正确找到父商品的标识
  list.forEach(function (item) {
    var _item$_extend51;
    if (item._extend && !((_item$_extend51 = item._extend) !== null && _item$_extend51 !== void 0 && _item$_extend51.unique_identification_number)) {
      item._extend.unique_identification_number = getUniqueId();
    }
  });
  list.forEach(function (item) {
    var _item$_extend53, _item$_extend58, _item$_extend59;
    // 自定义商品直接使用 _extend 中的数据，并将 id 转换为 0 提交给后端
    if (item.isCustomItem) {
      var _item$_extend52;
      bookings.push(_objectSpread(_objectSpread({}, item._extend), {}, {
        product_id: 0,
        // 确保后端接收到的 product_id 为 0
        appointment_status: (item === null || item === void 0 || (_item$_extend52 = item._extend) === null || _item$_extend52 === void 0 ? void 0 : _item$_extend52.appointment_status) || (data === null || data === void 0 ? void 0 : data.appointment_status) || 'new'
      }));
      return;
    }

    // 当前商品是跨日预约商品
    var isMultiDay = (_item$_extend53 = item._extend) === null || _item$_extend53 === void 0 ? void 0 : _item$_extend53.groupId;
    var start_date = item._extend.startDate.format('YYYY-MM-DD');
    var end_date = item._extend.endDate.format('YYYY-MM-DD');
    var end_time = item._extend.endDate.format('HH:mm');
    var start_time = item._extend.startDate.format('HH:mm');

    // 更新当前时间
    if (isNowTime(item._extend.start_time)) {
      start_time = getNowTime();
    }
    dayParams.holder = formatHolders(data, item, values);

    // 跨日预约下的普通商品
    if (isDay) {
      var _item$_extend54, _item$_extend55, _item$_extend56, _item$_extend57;
      var startDate = ((_item$_extend54 = item._extend) === null || _item$_extend54 === void 0 ? void 0 : _item$_extend54.startDate) || ((_item$_extend55 = item._extend) === null || _item$_extend55 === void 0 ? void 0 : _item$_extend55.start_date);
      var endDate = ((_item$_extend56 = item._extend) === null || _item$_extend56 === void 0 ? void 0 : _item$_extend56.endDate) || ((_item$_extend57 = item._extend) === null || _item$_extend57 === void 0 ? void 0 : _item$_extend57.end_date);
      var _formatDayTime = formatDayTime({
          startDate: startDate,
          endDate: endDate
        }),
        startDateTime = _formatDayTime.startDateTime,
        endDateTime = _formatDayTime.endDateTime;

      // 根据营业日时间更新时间
      start_date = dayjs(startDateTime).format('YYYY-MM-DD');
      start_time = dayjs(startDateTime).format('HH:mm');
      end_date = dayjs(endDateTime).format('YYYY-MM-DD');
      end_time = dayjs(endDateTime).format('HH:mm');
      dayParams.relation_products = (item === null || item === void 0 ? void 0 : item.relation_products) || [];
      dayParams.holder = formatHolders(data, item, values);
      dayParams.duration = getDays({
        _extend: {
          start_date: startDateTime,
          end_date: endDateTime
        }
      }, 'minutes');
    }

    // 跨日预约处理： 跨日预约所有数据都在list中， 每一组预约通过groupId进行分组
    // 通过obj 记录下每个GroupId第一次出现的时机，  第一次出现需要设置 metadata.multiDayPrices
    // 后续出现不需要设置 metadata.multiDayPrices. 节省体积
    var isSetGroupId = obj[item === null || item === void 0 || (_item$_extend58 = item._extend) === null || _item$_extend58 === void 0 ? void 0 : _item$_extend58.groupId];
    var booking = _objectSpread(_objectSpread({
      appointment_status: (item === null || item === void 0 || (_item$_extend59 = item._extend) === null || _item$_extend59 === void 0 ? void 0 : _item$_extend59.appointment_status) || (data === null || data === void 0 ? void 0 : data.appointment_status) || 'new',
      schedule_event_id: item === null || item === void 0 ? void 0 : item.booking_id,
      product: formatProducts(item, undefined, list),
      relation_products: formatRelationDetails(item._extend.relation_details),
      id: item.booking_id || 0,
      relation_id: item._extend.relation_id || 0,
      like_status: item._extend.like_status || 'common',
      relation_type: item._extend.relation_type || '',
      is_all: false,
      schedule_id: item._extend.schedule_id || 0,
      end_time: end_time,
      sub_type: isDay ? 'days' : getSubType(item),
      select_date: start_date,
      start_time: start_time,
      end_date: end_date,
      start_date: start_date,
      duration: isDay || isMultiDay ? 0 : flexibleObj.getValue(item._extend.duration),
      number: item._extend.capacity ? getSumCapacity({
        cacheItem: item
      }) : item._extend.number || 1,
      resources: formatResource(item),
      note: item._extend.note,
      metadata: formatMetaData(item, !isSetGroupId)
    }, eventOtherParams || {}), dayParams);

    // 记录下每个GroupId第一次出现的时机
    if (!isSetGroupId) {
      obj[item._extend.groupId] = true;
    }

    // 跨日预约模版或当前是跨日预约商品时
    if (isDay || isMultiDay) {
      bookings.push(booking);
      return;
    }
    for (var i = 0; i < (item._extend.quantity || 1); i++) {
      var newItem = cloneDeep(item);
      newItem._extend.unique_identification_number = "".concat(item._extend.unique_identification_number, "_").concat(i);
      // 舍入金额已基于数量计算，拆分时只保留第一个的 surcharge_rounding_remainder
      if (i > 0) {
        var _newItem$_extend;
        // 清除主商品的舍入金额
        newItem._extend.surcharge_rounding_remainder = undefined;
        // 清除 bundle 子商品的舍入金额
        if (((_newItem$_extend = newItem._extend) === null || _newItem$_extend === void 0 || (_newItem$_extend = _newItem$_extend.other) === null || _newItem$_extend === void 0 || (_newItem$_extend = _newItem$_extend.bundle) === null || _newItem$_extend === void 0 ? void 0 : _newItem$_extend.length) > 0) {
          newItem._extend.other.bundle.forEach(function (bundleItem) {
            bundleItem.surcharge_rounding_remainder = undefined;
          });
        }
      }
      bookings.push(_objectSpread(_objectSpread({}, booking), {}, {
        "product": formatProducts(newItem, 1, list),
        "number": item._extend.capacity ? getSumCapacity({
          cacheItem: newItem
        }, false) : newItem._extend.number || 1,
        "holder": getHolderByIndex(booking.holder, i),
        "metadata": formatMetaData(newItem, false)
      }));
    }
  });
  return bookings;
};

/**
 * @title: 普通商品
 * @description:
 * @param {any} data
 * @return {*}
 * @Author: WangHan
 * @Date: 2024-12-06 21:26
 */
var formatRelationProducts = function formatRelationProducts(data, type) {
  var _data$service;
  var allList = ((_data$service = data.service) === null || _data$service === void 0 ? void 0 : _data$service.value) || [];
  // open items 下的商品
  var list = allList.filter(function (item) {
    var _item$_extend60;
    return (
      // 跨日预约把普通商品加在relationProducts 活动预约按之前逻辑
      type === 'day' ? isNormalProductByDurationSchedule(item) : ((_item$_extend60 = item._extend) === null || _item$_extend60 === void 0 ? void 0 : _item$_extend60.holder_id) && appointmentTypes.includes(item.extension_type)
    );
  });
  var relationProducts = [];
  relationProducts = list.map(function (item) {
    var _item$_extend61;
    if (!((_item$_extend61 = item._extend) !== null && _item$_extend61 !== void 0 && _item$_extend61.unique_identification_number)) {
      var unique_identification_number = getUniqueId();
      item._extend.unique_identification_number = unique_identification_number;
    }
    return formatProducts(item, undefined, allList);
  });
  return relationProducts || [];
};

// 非预约商品格式化
var formatNormalProducts = function formatNormalProducts(data) {
  var _data$service2;
  var allList = ((_data$service2 = data.service) === null || _data$service2 === void 0 ? void 0 : _data$service2.value) || [];
  allList.forEach(function (item) {
    var _item$_extend62;
    if (!((_item$_extend62 = item._extend) !== null && _item$_extend62 !== void 0 && _item$_extend62.unique_identification_number)) {
      var unique_identification_number = getUniqueId();
      item._extend.unique_identification_number = unique_identification_number;
    }
  });
  // 非预约的商品
  var list = allList.filter(function (item) {
    return isNormalProductByDurationSchedule(item);
  });
  var relationProducts = [];
  relationProducts = list.map(function (item) {
    return formatProducts(item, undefined, allList);
  });
  return relationProducts || [];
};
/**
 * @title: 预约主体信息
 * @description:
 * @param {any} state
 * @param {any} values
 * @return {*}
 * @Author: zhiwei.Wang
 * @Date: 2024-02-19 09:26
 */
var formatHolder = function formatHolder(state, values) {
  var _state$bookingConfig2, _state$pet$value, _state$pet;
  var form_id = (state === null || state === void 0 || (_state$bookingConfig2 = state.bookingConfig) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.config) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.basic) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.appointment_subject) === null || _state$bookingConfig2 === void 0 ? void 0 : _state$bookingConfig2.form_id) || 0;
  var petValue = ((_state$pet$value = state.pet.value) === null || _state$pet$value === void 0 ? void 0 : _state$pet$value[form_id]) || [];
  var obj = {
    customer_id: values.customer_id,
    form_id: form_id,
    form_record: petValue.map(function (d) {
      return d.form_record_id;
    })
  };

  // 如果 value 为 空 并且originValue有值, 说明接口还没返回 这时候直接用接口的值
  if (!petValue.length && (_state$pet = state.pet) !== null && _state$pet !== void 0 && (_state$pet = _state$pet.originValue) !== null && _state$pet !== void 0 && (_state$pet = _state$pet.form_record) !== null && _state$pet !== void 0 && _state$pet.length) {
    obj.form_record = state.pet.originValue.form_record;
  }

  // 连锁加盟子店铺 增加参数
  if (state.isFranchisee) {
    obj.is_source_shop = 1;
  }
  return obj;
};

// https://menutech.w.eolink.com/home/api-studio/inside/K2bI3n465fe7244b3dbd6679d87caedfbb0636bf8c29eda/api/2778666/detail/53001549?spaceKey=menutech
export var formatValues = function formatValues(state) {
  var _values, _values3, _state$contacts_info;
  var values = {
    type: state.renderType === 'eventBooking' ? 'event_booking_v2' : 'appointment_booking',
    platform: state.isBookingTicket2 ? 'pos' : 'shop',
    sales_channel: 'my_pisel',
    order_sales_channel: state.isBookingTicket2 ? 'pos' : 'online_store',
    bookings: [],
    customer_id: 1,
    customer_name: '',
    holder: {},
    relation_products: [],
    metadata: {},
    business_code: (state === null || state === void 0 ? void 0 : state.businessCode) || undefined
  };

  // 是是跨日预约模版
  var isDay = isDaysBooking(state);
  // 是否包含跨日预约商品
  var isHasMultiDay = getHasMultiDayProduct(state);
  var isEvent = isEventBooking(state);
  if (!state.bookingId || isDay) {
    // 备注
    values.shop_note = formatNote(state);
  }

  // 提交手动价格调整（shop_discount）
  if (state.shop_discount && Number(state.shop_discount) > 0) {
    values.shop_discount = state.shop_discount;
    values.shop_discount_reason = '';
  }
  if (state.contacts) {
    var _state$contacts;
    values.contacts = ((_state$contacts = state.contacts) === null || _state$contacts === void 0 ? void 0 : _state$contacts.value) || [];
  }
  // 客户
  var customer = formatCustomer(state);
  values = _objectSpread(_objectSpread({}, values), customer);

  // 主体
  values.holder = formatHolder(state, values);
  // todo
  if (isEvent) {
    values.relation_products = formatRelationProducts(state, 'event');
  } else {
    var _values$relation_prod;
    values.relation_products = formatNormalProducts(state);
    if (!((_values$relation_prod = values.relation_products) !== null && _values$relation_prod !== void 0 && _values$relation_prod.length)) {
      values.relation_products = undefined;
    }
  }
  // 服务
  values.bookings = formatBookings(state, values);

  // 日期
  if ((_values = values) !== null && _values !== void 0 && (_values = _values.bookings) !== null && _values !== void 0 && (_values = _values[0]) !== null && _values !== void 0 && _values.select_date && !(state !== null && state !== void 0 && state.bookingId)) {
    var _values2;
    // 默认用第一个预约的选择日期并且是新建，编辑目前先不处理，用于解决附加费问题
    var startTime = "".concat((_values2 = values) === null || _values2 === void 0 || (_values2 = _values2.bookings) === null || _values2 === void 0 || (_values2 = _values2[0]) === null || _values2 === void 0 ? void 0 : _values2.start_time);
    startTime = "".concat(startTime || '00:00', ":00");
    values.schedule_date = "".concat(values.bookings[0].select_date, " ").concat(startTime);
  }

  // 跨日预约增加多余参数区分
  if (isDay || isHasMultiDay) {
    values.metadata.is_multiday_appointment = 1;
    // is_bundle_price_calculated 用于区分商品的price是总价，还是商品的单价
    // values.is_bundle_price_calculated = 1
  }
  if (!((_values3 = values) !== null && _values3 !== void 0 && (_values3 = _values3.bookings) !== null && _values3 !== void 0 && _values3.length) && !state.order_type) {
    values.type = 'virtual';
  }

  // 联系信息
  values.contacts_info = ((_state$contacts_info = state.contacts_info) === null || _state$contacts_info === void 0 ? void 0 : _state$contacts_info.value) || null;

  // 入口 order_type（如平面图 dine_in → table-order）最终写入请求 type，且须晚于 virtual 分支
  if (state.order_type) {
    values.type = state.order_type;
  }
  return values;
};

// 检测预约主体是否为空
export var checkHolderIsError = function checkHolderIsError(state) {
  var _state$client;
  var errorRowKey = '';
  var holderError = state.service.value.some(function (item) {
    var _item$_extend$holder_2, _item$_extend64;
    // 普通商品不需要检测holder
    if (isNormalProductByDurationSchedule(item)) {
      return false;
    }
    if (item._extend.quantity === 1 && (!item._extend.holder_id || ((_item$_extend$holder_2 = item._extend.holder_id) === null || _item$_extend$holder_2 === void 0 ? void 0 : _item$_extend$holder_2.length) === 0)) {
      var _item$_extend63;
      errorRowKey = genRowKey(item === null || item === void 0 || (_item$_extend63 = item._extend) === null || _item$_extend63 === void 0 || (_item$_extend63 = _item$_extend63.other) === null || _item$_extend63 === void 0 ? void 0 : _item$_extend63.rowKey);
      return true;
    }
    if (item._extend.quantity > 1 && ((_item$_extend64 = item._extend) === null || _item$_extend64 === void 0 || (_item$_extend64 = _item$_extend64.holder_id) === null || _item$_extend64 === void 0 ? void 0 : _item$_extend64.length) !== item._extend.quantity) {
      var _item$_extend65;
      errorRowKey = genRowKey(item === null || item === void 0 || (_item$_extend65 = item._extend) === null || _item$_extend65 === void 0 || (_item$_extend65 = _item$_extend65.other) === null || _item$_extend65 === void 0 ? void 0 : _item$_extend65.rowKey);
      return true;
    }
    return false;
  });
  var clientId = (_state$client = state.client) === null || _state$client === void 0 || (_state$client = _state$client.value) === null || _state$client === void 0 ? void 0 : _state$client.id;
  if (holderError) {
    var dom = document.getElementById(errorRowKey);
    if (dom) {
      dom.scrollIntoView({
        behavior: 'smooth',
        block: 'start'
      });
    }
  }
  if (holderError && (!clientId || clientId === 0 || clientId === 1)) {
    PisellToast({
      content: locales.getText('pisell2.text.please-select-the-customer-first')
    });
  }
  return holderError;
};