import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { isMultiDayProduct } from "../../booking/info2/service/addService/utils.js";
import { _objectWithoutProperties } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import "./productCache.js";
import { isNormalProductByDurationSchedule } from "../../booking/info/service2/utils.js";
import dayjs from "dayjs";
import { getUniqueId, isArr } from "@pisell/utils";
//#region src/components/ticketBooking/utils/index.ts
const _excluded = ["detail"];
/** dayjs对象格式化为字符串时间 */
const formatDateToStr = (date) => {
	const format = (val) => {
		return dayjs(val).format("YYYY-MM-DD HH:mm:ss");
	};
	if (Array.isArray(date)) return date.map(format);
	return format(date);
};
const getDefaultStartParam = () => {
	/** 获取默认查询时间范围 */
	return formatDateToStr([dayjs().startOf("day"), dayjs().endOf("day")]);
};
const getNextTimeSlice = (sliceMinutes) => {
	const currentTime = dayjs();
	const nextSlice = Math.ceil(currentTime.minute() / sliceMinutes) * sliceMinutes;
	return currentTime.minute(nextSlice);
};
const getDisabledEdit = ({ shop_discount, bookings, payment_status }) => {
	if (bookings.list.some((d) => !d.detail)) return true;
	let list = [
		"unfulfilled",
		"paid",
		"unpaid",
		"payment_processing"
	];
	const ps = payment_status === "partially_paid" ? "unpaid" : payment_status;
	if (bookings.appointment_status === "cancelled" || !list.includes(ps)) return true;
	return false;
};
const formatOptions = (detail) => {
	var _detail$product_sku;
	return ((detail === null || detail === void 0 || (_detail$product_sku = detail.product_sku) === null || _detail$product_sku === void 0 ? void 0 : _detail$product_sku.option) || []).map((item) => {
		return _objectSpread2(_objectSpread2({}, item), {}, { price: item.price || item.add_price });
	});
};
const formatHolder = (detail) => {
	var _detail$holder;
	return detail === null || detail === void 0 || (_detail$holder = detail.holder) === null || _detail$holder === void 0 || (_detail$holder = _detail$holder.form_record) === null || _detail$holder === void 0 ? void 0 : _detail$holder[0];
};
const restoreProductOtherData = (data) => {
	let { detail } = data;
	_objectWithoutProperties(data, _excluded);
	if (!detail) return;
	return {
		product_id: detail.product_id,
		option: formatOptions(detail),
		bundle: (detail.product_bundle || []).map((bundleItem) => {
			return _objectSpread2(_objectSpread2({}, bundleItem), {}, {
				title: bundleItem.bundle_title,
				group_id: bundleItem.bundle_group_id,
				id: bundleItem.bundle_id,
				product_id: bundleItem.bundle_product_id,
				_bundle_product_id: bundleItem.bundle_product_id,
				bundle_variant_id: bundleItem.bundle_variant_id,
				quantity: bundleItem.num,
				option: bundleItem.option.map((optionItem) => {
					return _objectSpread2(_objectSpread2({}, optionItem), {}, {
						name: optionItem.name["auto"],
						quantity: bundleItem.num,
						product_option_item_id: optionItem.option_group_item_id
					});
				}),
				price: (bundleItem === null || bundleItem === void 0 ? void 0 : bundleItem.bundle_sum_type) === "markdown" ? `-${Number(bundleItem.bundle_sum_price)}` : Number(bundleItem.bundle_sum_price)
			});
		}),
		product_variant_id: detail.product_variant_id || 0,
		quantity: Number(detail.product_quantity)
	};
};
const isSameProduct = (a, b) => {
	var _a$_extend2, _b$_extend2;
	if (isNormalProductByDurationSchedule(a) && isNormalProductByDurationSchedule(b)) {
		var _a$_extend, _b$_extend;
		return ((_a$_extend = a._extend) === null || _a$_extend === void 0 || (_a$_extend = _a$_extend.other) === null || _a$_extend === void 0 ? void 0 : _a$_extend.rowKey) === ((_b$_extend = b._extend) === null || _b$_extend === void 0 || (_b$_extend = _b$_extend.other) === null || _b$_extend === void 0 ? void 0 : _b$_extend.rowKey);
	}
	return ((_a$_extend2 = a._extend) === null || _a$_extend2 === void 0 || (_a$_extend2 = _a$_extend2.other) === null || _a$_extend2 === void 0 ? void 0 : _a$_extend2.rowKey) === ((_b$_extend2 = b._extend) === null || _b$_extend2 === void 0 || (_b$_extend2 = _b$_extend2.other) === null || _b$_extend2 === void 0 ? void 0 : _b$_extend2.rowKey) && a._serviceKey === b._serviceKey && a._holderKey === b._holderKey;
};
const addService = (list, addItem, state, isMultiDay) => {
	let value = list;
	let count;
	if (isMultiDay && isArr(addItem)) return {
		list: [...addItem, ...value],
		count: 1
	};
	if (!isNormalProductByDurationSchedule(addItem) && !getIsOverlayProduct(addItem, state)) {
		const quantity = addItem._extend.quantity || 1;
		count = quantity;
		for (let i = 0; i < quantity; i++) {
			var _addItem$_extend;
			const singleItem = _objectSpread2(_objectSpread2({}, addItem), {}, {
				_id: getUniqueId(),
				_extend: _objectSpread2(_objectSpread2({}, addItem._extend), {}, {
					quantity: 1,
					other: _objectSpread2(_objectSpread2({}, ((_addItem$_extend = addItem._extend) === null || _addItem$_extend === void 0 ? void 0 : _addItem$_extend.other) || {}), {}, { quantity: 1 })
				})
			});
			value.unshift(singleItem);
		}
	} else {
		let isNotSame = true;
		let isSetCount = false;
		value = list.map((item) => {
			var _item$_extend;
			const isGoodPassDiscountProduct = (item.discount_list || []).some((item) => item.type === "good_pass");
			const isEdit = item === null || item === void 0 ? void 0 : item.edit;
			const bundleDiscountList = [];
			((item === null || item === void 0 || (_item$_extend = item._extend) === null || _item$_extend === void 0 || (_item$_extend = _item$_extend.other) === null || _item$_extend === void 0 ? void 0 : _item$_extend.bundle) || []).forEach((item) => {
				bundleDiscountList.push(...(item === null || item === void 0 ? void 0 : item.discount_list) || []);
			});
			const isGoodPassBundleProduct = bundleDiscountList.some((item) => item.type === "good_pass");
			if (isSameProduct(item, addItem) && !isSetCount && !isGoodPassDiscountProduct && !isEdit && !isGoodPassBundleProduct) {
				var _item$_extend2, _addItem$_extend2, _item$_extend3;
				isNotSame = false;
				const quantity = ((item === null || item === void 0 || (_item$_extend2 = item._extend) === null || _item$_extend2 === void 0 ? void 0 : _item$_extend2.quantity) || 1) + ((addItem === null || addItem === void 0 || (_addItem$_extend2 = addItem._extend) === null || _addItem$_extend2 === void 0 ? void 0 : _addItem$_extend2.quantity) || 1);
				count = quantity;
				isSetCount = true;
				return _objectSpread2(_objectSpread2({}, item), {}, { _extend: _objectSpread2(_objectSpread2({}, item._extend), {}, {
					quantity,
					other: _objectSpread2(_objectSpread2({}, ((_item$_extend3 = item._extend) === null || _item$_extend3 === void 0 ? void 0 : _item$_extend3.other) || {}), {}, { quantity })
				}) });
			}
			return item;
		});
		const _idx = value.findIndex((item) => item.id === addItem.id);
		if (_idx !== -1) {
			const [removed] = value.splice(_idx, 1);
			value.unshift(removed);
		}
		if (isNotSame) {
			value.unshift(addItem);
			count = addItem._extend.quantity;
		}
	}
	return {
		list: value,
		quantity: count
	};
};
const addServiceScroll = (rowKey, cacheItem) => {
	const list = document.querySelectorAll(`#rowKey-${rowKey}`);
	setTimeout(() => {
		if (list.length && isNormalProductByDurationSchedule(cacheItem)) list[list.length - 1].scrollIntoView({
			behavior: "smooth",
			block: "center"
		});
		else setTimeout(() => {
			const bookingWrap = document.querySelectorAll(`.pisell-lowcode__booking-service-wrap`);
			if (bookingWrap.length) bookingWrap[0].scrollTo({
				top: 0,
				behavior: "smooth"
			});
		}, 100);
	});
};
const getCartProductOverlay = (state) => {
	var _state$bookingConfig;
	return (state === null || state === void 0 || (_state$bookingConfig = state.bookingConfig) === null || _state$bookingConfig === void 0 || (_state$bookingConfig = _state$bookingConfig.config) === null || _state$bookingConfig === void 0 || (_state$bookingConfig = _state$bookingConfig.basic) === null || _state$bookingConfig === void 0 ? void 0 : _state$bookingConfig.cart_product_overlay) || { type: "product_all" };
};
const getIsOverlayProduct = (item, state) => {
	const { type, product_ids } = getCartProductOverlay(state);
	if (type === "product_all") return true;
	return product_ids.includes(item.product_id || item.id);
};
const getIsShowNumber = (item, state) => {
	const isBookingTicket2 = state.isBookingTicket2;
	if (isMultiDayProduct(item)) return false;
	return isNormalProductByDurationSchedule(item) || isBookingTicket2 && getIsOverlayProduct(item, state);
};
const genServiceKey = (item) => {
	var _item$_extend4, _item$_extend5, _item$_extend6;
	const product_id = item.product_id;
	const durationKey = (_item$_extend4 = item._extend) === null || _item$_extend4 === void 0 ? void 0 : _item$_extend4.duration;
	const start_time = (_item$_extend5 = item._extend) === null || _item$_extend5 === void 0 ? void 0 : _item$_extend5.start_time;
	const total = (_item$_extend6 = item._extend) === null || _item$_extend6 === void 0 ? void 0 : _item$_extend6.total;
	let resourceKey = "";
	Object.values(item._extend.resource || []).forEach((resources) => {
		resources.forEach((resource) => {
			resourceKey += `${resource.relation_id}`;
		});
	});
	return `${product_id}-${durationKey}-${resourceKey}-${start_time}-${total}`;
};
const genHolderKey = (item) => {
	var _item$_extend7;
	const product_id = item.product_id;
	let holder_id;
	if (isArr((_item$_extend7 = item._extend) === null || _item$_extend7 === void 0 ? void 0 : _item$_extend7.holder_id)) {
		var _item$_extend8;
		holder_id = (_item$_extend8 = item._extend) === null || _item$_extend8 === void 0 ? void 0 : _item$_extend8.holder_id.join("-");
	} else {
		var _item$_extend9;
		holder_id = (_item$_extend9 = item._extend) === null || _item$_extend9 === void 0 ? void 0 : _item$_extend9.holder_id;
	}
	return `${product_id}-${holder_id}`;
};
const getIsParallelResourcesBooking = (record) => {
	return (record === null || record === void 0 ? void 0 : record.relation_id) === 0 && (record === null || record === void 0 ? void 0 : record.relation_type) === "";
};
const formatScanCustomer = (data) => {
	const { result, scanCode } = data;
	const { response, searchType } = result || {};
	const { data: customerData, code = 200 } = response || {};
	if (code !== 200) return null;
	if (isArr(customerData)) {
		var _customerData$;
		return {
			searchType,
			data: (_customerData$ = customerData[0]) === null || _customerData$ === void 0 ? void 0 : _customerData$.customer,
			scanCode
		};
	}
	return {
		searchType,
		data: customerData === null || customerData === void 0 ? void 0 : customerData.customer,
		scanCode
	};
};
const formatScanGlobal = (data) => {
	const { result, scanCode } = data;
	const { response, searchType } = result || {};
	const { data: resultData, code } = response || {};
	if (code !== 200 && searchType !== "local_product") return null;
	if (searchType === "wallet") return {
		searchType,
		data: resultData.customer,
		scanCode
	};
	if (searchType === "walletPass") {
		var _resultData$;
		return {
			searchType,
			data: resultData === null || resultData === void 0 || (_resultData$ = resultData[0]) === null || _resultData$ === void 0 ? void 0 : _resultData$.customer,
			scanCode
		};
	}
	if (searchType === "product" || searchType === "local_product") return {
		searchType,
		data: resultData,
		scanCode
	};
};
const createSimpleCacheItem = (item, e, state) => {
	return _objectSpread2(_objectSpread2({}, item), {}, {
		product_id: item.id,
		_id: getUniqueId(),
		_key: e.key,
		_extend: {
			start_date: state.date.value,
			quantity: (e === null || e === void 0 ? void 0 : e.quantity) || 1,
			price: item.price,
			product_name: item.title,
			other: e
		},
		new: 1
	});
};
const getBookingTicketKey = (osKey) => {
	return `bookingTicket-${osKey}`;
};
const getShopDiscountKey = (osKey) => {
	return `shopDiscount-${osKey}`;
};
const rulesHooks = {
	getProduct(product) {
		var _product$_extend, _product$_extend2, _product$_extend3, _product$_extend4, _product$_extend5, _product$_extend6;
		return {
			booking_id: product.booking_id,
			id: product.id,
			_id: product._id,
			price: product._extend.price,
			total: product._extend.total,
			discount_list: product.discount_list,
			origin_total: product._extend.origin_total,
			num: product._extend.quantity,
			quantity: product._extend.quantity || 1,
			vouchersApplicable: product.vouchersApplicable,
			bundle: ((_product$_extend = product._extend) === null || _product$_extend === void 0 || (_product$_extend = _product$_extend.other) === null || _product$_extend === void 0 ? void 0 : _product$_extend.bundle) || [],
			startDate: (_product$_extend2 = product._extend) === null || _product$_extend2 === void 0 ? void 0 : _product$_extend2.startDate,
			holder_id: (_product$_extend3 = product._extend) === null || _product$_extend3 === void 0 ? void 0 : _product$_extend3.holder_id,
			isNormalProduct: (_product$_extend4 = product._extend) === null || _product$_extend4 === void 0 ? void 0 : _product$_extend4.isNormalProduct,
			isNeedHolder: product._extend.isFormSubject && !product._extend.isNormalProduct,
			options: ((_product$_extend5 = product._extend) === null || _product$_extend5 === void 0 || (_product$_extend5 = _product$_extend5.other) === null || _product$_extend5 === void 0 ? void 0 : _product$_extend5.option) || [],
			main_product_selling_price: (_product$_extend6 = product._extend) === null || _product$_extend6 === void 0 ? void 0 : _product$_extend6.main_product_selling_price
		};
	},
	setProduct(product, values) {
		return _objectSpread2(_objectSpread2({}, product), {}, {
			_id: values._id || product._id,
			discount_list: values.discount_list,
			_extend: _objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({}, product._extend), {}, { other: _objectSpread2(_objectSpread2(_objectSpread2({}, product._extend.other), "bundle" in values ? { bundle: values.bundle } : {}), Array.isArray(values.options) ? { option: values.options } : {}) }, "total" in values ? { total: values.total } : {}), "main_product_selling_price" in values ? { main_product_selling_price: values.main_product_selling_price } : {}), "quantity" in values ? { quantity: values.quantity } : {})
		});
	}
};
const clearCacheProductDetail = () => {
	try {
		Object.keys(localStorage).forEach((key) => {
			if (key.includes(`productDefaultOther-`)) localStorage.removeItem(key);
		});
	} catch (error) {
		console.error("Failed to clear productDefaultOther cache:", error);
	}
};
//#endregion
export { addService, addServiceScroll, clearCacheProductDetail, createSimpleCacheItem, formatDateToStr, formatHolder, formatScanCustomer, formatScanGlobal, genHolderKey, genServiceKey, getBookingTicketKey, getDefaultStartParam, getDisabledEdit, getIsParallelResourcesBooking, getIsShowNumber, getNextTimeSlice, getShopDiscountKey, isSameProduct, restoreProductOtherData, rulesHooks };
