import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { isOption } from "../../ticketBooking/components/addServiceVariant/utils.js";
import { isMultiDayProduct } from "./service/addService/utils.js";
import { isNormalProductByDurationSchedule } from "../info/service2/utils.js";
import { findNextDuration, flexibleObj, getCacheParams, getDays, getLastServer, getServeStartTime, getServiceTimes, isSessionProduct } from "../utils.js";
import dayjs from "dayjs";
import { locales } from "@pisell/utils";
//#region src/components/booking/info2/utilsByBooking.ts
const getUseableEventCount = (eventList, current) => {
	return (eventList || []).reduce((pre, event) => {
		return pre - event.pax;
	}, current || 0);
};
const isConflict = (event, current) => {
	const eventStart = dayjs(event.start_at);
	const eventEnd = dayjs(event.end_at);
	const _isBefore = dayjs(current.start_at).isBefore(eventEnd);
	let _isAfter = true;
	if (current.end_at) _isAfter = dayjs(current.end_at).isAfter(eventStart);
	return _isBefore && _isAfter;
};
const getResourceTimeIsUsable = (item, cacheItem, resourceItem) => {
	const startDate = dayjs(dayjs(cacheItem._extend.start_date).format("YYYY-MM-DD") + " " + getServeStartTime(cacheItem._extend.start_time));
	const isFlexible = flexibleObj.isFlexible(cacheItem._extend.duration);
	let isMaxLimitRange = false;
	let isDateRange = false;
	let isCountRange = false;
	let time = _objectSpread2({}, item);
	let timeStartDate = dayjs(time.start_date + " " + time.start_time).subtract(1, "second");
	let timeEndDate = dayjs(time.end_date + " " + time.end_time).add(1, "second");
	getUseableEventCount(time.event_list, resourceItem.capacity);
	const currentCount = getSumCapacity({ cacheItem });
	const eventList = getEventList(time.event_list || [], cacheItem);
	let endDate = null;
	let isCalcCount = true;
	/**
	* 从这里为判断是否在时间范围内
	*/
	if (isFlexible) {
		isDateRange = startDate.isAfter(timeStartDate) && startDate.isBefore(timeEndDate);
		if (!isDateRange && eventList.length) {
			isCalcCount = false;
			isDateRange = true;
			isCountRange = false;
		}
	} else {
		endDate = startDate.add(flexibleObj.getValue(cacheItem._extend.duration), "minute");
		if (startDate.isAfter(timeStartDate) && endDate.isBefore(timeEndDate)) isDateRange = true;
	}
	if (isCalcCount) {
		/**
		* 从这里判断预约量
		*/
		let conflict = (eventList || []).filter((d) => {
			return isConflict({
				start_at: d.start_at,
				end_at: d.end_at
			}, {
				start_at: startDate,
				end_at: endDate
			});
		});
		if (resourceItem.resourceType === "single") if (conflict.length === 0) isCountRange = true;
		else isCountRange = false;
		else if (currentCount <= getUseableEventCount(conflict, resourceItem.capacity)) isCountRange = true;
		else isCountRange = false;
	}
	time._extend = {
		isMaxLimitRange,
		isDateRange,
		isCountRange,
		isUsable: isDateRange && isCountRange
	};
	return time;
};
const getSumCapacity = ({ cacheItem }, isCalcQuantity = true) => {
	var _cacheItem$_extend;
	let sum = 0;
	for (let item of cacheItem._extend.capacity || []) sum += item.value;
	return sum * (isCalcQuantity ? (cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend = cacheItem._extend) === null || _cacheItem$_extend === void 0 ? void 0 : _cacheItem$_extend.quantity) || 1 : 1);
};
const getEventList = (list, cacheItem) => {
	if (cacheItem === null || cacheItem === void 0 ? void 0 : cacheItem.booking_id) {
		const newList = [];
		list.forEach((event) => {
			var _event$pax_list;
			if ((_event$pax_list = event.pax_list) === null || _event$pax_list === void 0 ? void 0 : _event$pax_list[cacheItem === null || cacheItem === void 0 ? void 0 : cacheItem.booking_id]) {
				const pax = event.pax - event.pax_list[cacheItem === null || cacheItem === void 0 ? void 0 : cacheItem.booking_id];
				if (pax > 0) newList.push(_objectSpread2(_objectSpread2({}, event), {}, { pax }));
			} else newList.push(event);
		});
		return newList;
	}
	return list;
};
/**
* @title: 查找是否有可用的time
* @description:
* @param {any} resourceItem
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-01-09 13:57
*/
const formatTimes = (resourceItem, cacheItem) => {
	let usableTimes = [];
	let _resourceItem = _objectSpread2({}, resourceItem);
	let sum = getSumCapacity({ cacheItem });
	if (_resourceItem.capacity >= sum) _resourceItem.times = _resourceItem.times.map((time) => {
		let _time = getResourceTimeIsUsable(time, cacheItem, _resourceItem);
		if (_time === null || _time === void 0 ? void 0 : _time._extend.isDateRange) usableTimes.push(_time);
		return _time;
	});
	let _time = (usableTimes || []).sort((a, b) => {
		return dayjs(a.end_date + " " + a.end_time).valueOf() - dayjs(b.end_date + " " + b.end_time).valueOf();
	})[0];
	resourceItem._extend = _objectSpread2(_objectSpread2({}, resourceItem._extend), {}, { usableTime: _time });
	return resourceItem;
};
const getErrorList = (resource, cacheItem) => {
	if (!(cacheItem === null || cacheItem === void 0 ? void 0 : cacheItem.id)) return [{
		label: locales.getText("pisell2.text.no-product-added"),
		type: "products"
	}];
	if (!resource) return [];
	let list = [];
	if (!resource.usable) {
		var _cacheItem$_data, _resource$_extend;
		const { startDate, endDate } = getServiceTimes(cacheItem);
		const startText = startDate.format("hh:mm A");
		let endText = endDate.format("hh:mm A");
		if (dayjs(endDate).isAfter(startDate, "day")) endText = locales.getText("pisell1.text.tomorrow") + endText;
		cacheItem === null || cacheItem === void 0 || (_cacheItem$_data = cacheItem._data) === null || _cacheItem$_data === void 0 || (_cacheItem$_data = _cacheItem$_data.resourceMaps) === null || _cacheItem$_data === void 0 || (_cacheItem$_data = _cacheItem$_data[resource === null || resource === void 0 ? void 0 : resource.form_id]) === null || _cacheItem$_data === void 0 || _cacheItem$_data.type;
		if (!((_resource$_extend = resource._extend) === null || _resource$_extend === void 0 ? void 0 : _resource$_extend.usableTime)) list.push({
			label: locales.getText("pisell1.text.resource-error-message-2")(resource.labelText, startText, endText),
			type: "time"
		});
		else {
			var _resource$_extend2;
			if (!((_resource$_extend2 = resource._extend) === null || _resource$_extend2 === void 0 || (_resource$_extend2 = _resource$_extend2.usableTime) === null || _resource$_extend2 === void 0 || (_resource$_extend2 = _resource$_extend2._extend) === null || _resource$_extend2 === void 0 ? void 0 : _resource$_extend2.isCountRange)) list.push({
				label: locales.getText("pisell1.text.resource-error-message-3")(resource.labelText, startText, endText),
				type: "limit"
			});
		}
	}
	if (resource.unbound) list.push({
		label: locales.getText("pisell1.text.resource-error-message-unbound"),
		type: "time"
	});
	return list;
};
/**
* @title: 格式化资源, 添加自定义参数
* @description:
* @param {any} resourceItem
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-01-09 13:40
*/
const formatResource = (resourceItem, cacheItem, formatLabel) => {
	var _resourceItem$_extend;
	let _resourceItem = _objectSpread2({}, resourceItem);
	_resourceItem = formatTimes(_resourceItem, cacheItem);
	_resourceItem.labelText = _resourceItem.main_field;
	const usable = (_resourceItem$_extend = _resourceItem._extend.usableTime) === null || _resourceItem$_extend === void 0 || (_resourceItem$_extend = _resourceItem$_extend._extend) === null || _resourceItem$_extend === void 0 ? void 0 : _resourceItem$_extend.isUsable;
	_resourceItem.usable = usable;
	if (formatLabel) _resourceItem.label = formatLabel(_resourceItem);
	return _resourceItem;
};
const getAppointmentTimingPreference = (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.information_tab) === null || _state$bookingConfig === void 0 ? void 0 : _state$bookingConfig.appointment_timing_preference) || "sequential";
};
/**
* @title: 创建服务的开始时间和结束时间
* @description: 
* @param {any} state
* @param {any} item
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-01-26 14:09
*/
const getServiceStartTimeAndEndTime = (state, cacheItem, timeObj) => {
	var _state$service$value, _cacheItem$_extend2;
	if (cacheItem === null || cacheItem === void 0 ? void 0 : cacheItem.isCustomItem) return { duration: null };
	const appointmentTimingPreference = getAppointmentTimingPreference(state);
	let lastServer = getLastServer((_state$service$value = state.service.value) === null || _state$service$value === void 0 ? void 0 : _state$service$value.filter((item) => !item.isCustomItem && !isNormalProductByDurationSchedule(item)));
	const getDuration = (cacheItem) => {
		var _cacheItem$duration;
		if (isMultiDayProduct(cacheItem)) return getDays(cacheItem, "days");
		return findNextDuration(cacheItem.duration, timeObj === null || timeObj === void 0 ? void 0 : timeObj.durationSlicesBasedOnTime, cacheItem === null || cacheItem === void 0 || (_cacheItem$duration = cacheItem.duration) === null || _cacheItem$duration === void 0 ? void 0 : _cacheItem$duration.value);
	};
	let _extend = { duration: getDuration(cacheItem) };
	if (lastServer) {
		let lastServerStartDate = lastServer._extend.startDate;
		let lastServerEndDate = lastServer._extend.endDate;
		if (appointmentTimingPreference === "parallel") _extend.start_time = lastServerStartDate.format("HH:mm");
		else if (dayjs(lastServerEndDate).isAfter(lastServerStartDate, "day")) {
			var _timeObj$timeSlices;
			_extend.start_time = timeObj === null || timeObj === void 0 ? void 0 : timeObj.timeSlices[(timeObj === null || timeObj === void 0 || (_timeObj$timeSlices = timeObj.timeSlices) === null || _timeObj$timeSlices === void 0 ? void 0 : _timeObj$timeSlices.length) - 1].value;
		} else {
			var _ref;
			_extend.start_time = (_ref = lastServerEndDate || dayjs()) === null || _ref === void 0 ? void 0 : _ref.format("HH:mm");
		}
	} else {
		let findNextSliceProps = { date: "" };
		const serviceParams = getCacheParams();
		if (serviceParams) {
			let str = serviceParams.start_date;
			if (str) findNextSliceProps.date = dayjs(str).format("HH:mm");
		}
		if (findNextSliceProps.date && findNextSliceProps.date !== "00:00") _extend.start_time = findNextSliceProps.date;
		else if (cacheItem.currentDefaultTime) _extend.start_time = cacheItem.currentDefaultTime;
		else _extend.start_time = dayjs().format("HH:mm");
	}
	_extend = _objectSpread2(_objectSpread2({}, _extend), cacheItem._extend);
	const { startDate, endDate } = getServiceTimes(_objectSpread2(_objectSpread2({}, cacheItem), {}, { _extend }));
	_extend.startDate = startDate;
	_extend.endDate = endDate;
	const session = cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend2 = cacheItem._extend) === null || _cacheItem$_extend2 === void 0 || (_cacheItem$_extend2 = _cacheItem$_extend2.other) === null || _cacheItem$_extend2 === void 0 ? void 0 : _cacheItem$_extend2.session;
	if (isSessionProduct(cacheItem) && session) {
		const startAt = dayjs(`${state.date.value.format("YYYY-MM-DD")} ${session.start_at.format("HH:mm:ss")}`);
		const endAt = dayjs(`${state.date.value.format("YYYY-MM-DD")} ${session.end_at.format("HH:mm:ss")}`);
		_extend.start_date = startAt;
		_extend.startDate = startAt;
		_extend.start_time = session.start_time;
		_extend.end_date = endAt;
		_extend.endDate = endAt;
		_extend.end_time = session.end_time;
		_extend.duration = getDays({ _extend }, "minutes");
	}
	return _extend;
};
const getIsNoSpecAndPackage = (product) => {
	var _product$variant;
	if ((product === null || product === void 0 ? void 0 : product.extension_type) !== "normal") return false;
	if (product === null || product === void 0 ? void 0 : product.isEditBooking) {
		var _product$product_bund, _product$product_sku;
		return (product === null || product === void 0 || (_product$product_bund = product.product_bundle) === null || _product$product_bund === void 0 ? void 0 : _product$product_bund.length) === 0 && (product === null || product === void 0 ? void 0 : product.product_variant_id) === 0 && ((product === null || product === void 0 || (_product$product_sku = product.product_sku) === null || _product$product_sku === void 0 || (_product$product_sku = _product$product_sku.option) === null || _product$product_sku === void 0 ? void 0 : _product$product_sku.length) || 0) === 0;
	}
	return (product === null || product === void 0 ? void 0 : product.is_bundle) === 0 && ((product === null || product === void 0 || (_product$variant = product.variant) === null || _product$variant === void 0 ? void 0 : _product$variant.length) || 0) === 0 && !isOption(product);
};
//#endregion
export { formatResource, getAppointmentTimingPreference, getErrorList, getIsNoSpecAndPackage, getResourceTimeIsUsable, getServiceStartTimeAndEndTime, getSumCapacity };
