const require_runtime = require("../../../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_mock = require("../../../mock.js");
const require_asyncToGenerator = require("../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_utilsByBooking = require("../../utilsByBooking.js");
const require_utils = require("../editService/utils.js");
const require_utils$1 = require("../../../info/service2/utils.js");
const require_utils$2 = require("../../../utils.js");
const require_utils$3 = require("../../../info/utils.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_utils = require("@pisell/utils");
let _pisell_icon_es_AlertTriangle = require("@pisell/icon/es/AlertTriangle");
_pisell_icon_es_AlertTriangle = require_runtime.__toESM(_pisell_icon_es_AlertTriangle);
let lodash = require("lodash");
//#region src/components/booking/info2/service/addService/utils.tsx
const getUsableTime = (cacheItem) => {
	try {
		let items = [];
		for (let form_id in cacheItem._extend.resource) items = items.concat(cacheItem._extend.resource[form_id].map((d) => {
			return cacheItem._data.resourceMaps[form_id].renderListMaps[d.relation_id];
		}));
		return items.reduce((pre, event) => {
			var _event$_extend, _pre$_extend;
			return (0, dayjs.default)((_event$_extend = event._extend) === null || _event$_extend === void 0 || (_event$_extend = _event$_extend.usableTime) === null || _event$_extend === void 0 ? void 0 : _event$_extend.end_at).isBefore((_pre$_extend = pre._extend) === null || _pre$_extend === void 0 || (_pre$_extend = _pre$_extend.usableTime) === null || _pre$_extend === void 0 ? void 0 : _pre$_extend.end_at) ? event : pre;
		}, items[0]);
	} catch (err) {
		return null;
	}
};
const getDurationProps = ({ cacheItem, useStartTime, currentResource, slice }) => {
	let _cacheItem = cacheItem;
	return {
		startDate: (0, dayjs.default)((0, dayjs.default)(_cacheItem._extend.start_date).format("YYYY-MM-DD ") + (require_utils$2.getServeStartTime(useStartTime) || "00:00")),
		usableTime: getUsableTime(cacheItem),
		duration: require_utils$2.getDuration(_cacheItem === null || _cacheItem === void 0 ? void 0 : _cacheItem.duration),
		locale: _pisell_utils.locales.locale,
		slice,
		selectProps: { size: "large" }
	};
};
/**
* @title: 灵活时长选项
* @description:
* @param {*} useMemo
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-02-23 10:10
*/
const getFlexibleOption = ({ cacheItem, useStartTime, currentResource, slice, durationProps }) => {
	const _durationProps = durationProps || getDurationProps({
		cacheItem,
		useStartTime,
		currentResource,
		slice
	});
	let _duration = _durationProps.duration;
	if (_duration === "flexible") {
		var _durationProps$usable, _durationProps$usable2;
		let timeValue = require_utils$2.getEndDate(_durationProps.startDate, _duration, ((_durationProps$usable = _durationProps.usableTime) === null || _durationProps$usable === void 0 || (_durationProps$usable = _durationProps$usable._extend) === null || _durationProps$usable === void 0 || (_durationProps$usable = _durationProps$usable.usableTime) === null || _durationProps$usable === void 0 ? void 0 : _durationProps$usable.end_at) ? (0, dayjs.default)((_durationProps$usable2 = _durationProps.usableTime) === null || _durationProps$usable2 === void 0 || (_durationProps$usable2 = _durationProps$usable2._extend) === null || _durationProps$usable2 === void 0 || (_durationProps$usable2 = _durationProps$usable2.usableTime) === null || _durationProps$usable2 === void 0 ? void 0 : _durationProps$usable2.end_at) : null).diff(_durationProps.startDate, "minute");
		return {
			label: _pisell_utils.locales.getText("pisell2.text.flexible"),
			value: require_utils$2.flexibleObj.create(timeValue)
		};
	}
	return null;
};
/**
* @title: 时间切片
* @description:
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-01-09 13:37
*/
const getTimeObj = ({ cacheItem, useStartTime, currentResource, state, useDuration, durationProps }) => {
	var _state$bookingConfig2;
	const isMultiDay = isMultiDayProduct(cacheItem);
	const flexibleOption = getFlexibleOption({
		cacheItem,
		useStartTime,
		currentResource,
		durationProps
	});
	let obj = require_utils$2.sliceDayIntoFiveMinutes((_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 ? void 0 : _state$bookingConfig2.service_time, _pisell_utils.locales.locale, isMultiDay);
	let timeSlices = [...obj.timeSlices];
	let durationSlicesBasedOnTime = [...obj.durationSlicesBasedOnTime];
	if (flexibleOption) durationSlicesBasedOnTime.unshift(flexibleOption);
	if (useDuration && !durationSlicesBasedOnTime.some((d) => d.value === useDuration)) durationSlicesBasedOnTime.unshift({
		label: require_utils$2.getDiscountTime(useDuration, isMultiDay),
		value: useDuration,
		disabled: true
	});
	return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, obj), {}, {
		timeSlices,
		durationSlicesBasedOnTime
	});
};
/**
* @title: 获取资源列表
* @description:
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-01-09 13:38
*/
const formatResources = ({ cacheItem, resourcesOrigin, id }) => {
	try {
		let _list = [];
		let maps = {};
		const _cacheItem = cacheItem;
		_list = resourcesOrigin.map((item) => {
			let renderListMaps = {};
			let _item = (0, lodash.cloneDeep)(item);
			_item.renderList = _item.renderList.map((d) => {
				let res = require_utilsByBooking.formatResource(d, _cacheItem, (newData) => {
					let unbound = !item.optional_resource.includes(newData.id) && !item.default_resource.includes(newData.id) && newData.id !== 0;
					return /* @__PURE__ */ react.default.createElement("div", { className: "resource-option" }, /* @__PURE__ */ react.default.createElement("div", { className: "like-wrap" }), /* @__PURE__ */ react.default.createElement("span", { className: "resource-option-label-text" }, newData.labelText), (!newData.usable || unbound) && /* @__PURE__ */ react.default.createElement(_pisell_icon_es_AlertTriangle.default, { className: "resource-option-alert-icon" }));
				});
				if (!item.optional_resource.includes(d.id) && !item.default_resource.includes(d.id) && d.id !== 0) res.unbound = true;
				renderListMaps[res.id] = res;
				return res;
			}).sort((a, b) => b.usable ? 1 : -1);
			maps[_item.form_id] = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, _item), {}, { renderListMaps });
			return _item;
		});
		return {
			list: _list,
			maps
		};
	} catch (err) {
		console.log("formatResourcesErr", err);
	}
	return {
		list: [],
		maps: []
	};
};
const getResourceMaxFreeTime = (resource) => {
	const { renderList, form_id } = resource;
	if (!require_utils.getAutoAllocationStorage(form_id)) return [];
	const usableList = renderList.filter((d) => d.usable && d.id !== 0);
	let defaultResource = [];
	let maxFreeTime = 0;
	usableList.forEach((d) => {
		const { times } = d;
		const currentMaxFreeTime = times.reduce((pre, cur) => {
			var _cur$event_list, _cur$event_list2;
			const start = ((_cur$event_list = cur.event_list) === null || _cur$event_list === void 0 || (_cur$event_list = _cur$event_list[((_cur$event_list2 = cur.event_list) === null || _cur$event_list2 === void 0 ? void 0 : _cur$event_list2.length) - 1]) === null || _cur$event_list === void 0 ? void 0 : _cur$event_list.end_at) || cur.start_at;
			const end = cur.end_at;
			const diff = (0, dayjs.default)(end).diff((0, dayjs.default)(start), "minute");
			return diff > pre ? diff : pre;
		}, 0);
		if (currentMaxFreeTime > maxFreeTime) {
			maxFreeTime = currentMaxFreeTime;
			defaultResource = [d];
		}
	});
	return defaultResource;
};
const setDefaultResource = ({ cacheItem, resources }) => {
	let obj = {};
	const serviceParams = require_utils$2.getCacheParams();
	let resourceId = Number(serviceParams === null || serviceParams === void 0 ? void 0 : serviceParams.resource_id);
	for (let item of resources) {
		const { select_type = {}, optional_resource = [], default_resource = [] } = item;
		const renderList = item.renderList.filter((d) => {
			if ((select_type === null || select_type === void 0 ? void 0 : select_type.type) === "single") {
				if (resourceId && (optional_resource.includes(resourceId) || default_resource.includes(resourceId))) return d.id === resourceId;
				return d.is_default === 1;
			} else return d.is_default === 1 || d.id === resourceId;
		});
		let defaultOriginalResource = [];
		if (renderList.length === 0) defaultOriginalResource = getResourceMaxFreeTime(item);
		else defaultOriginalResource = renderList;
		const defaultResource = defaultOriginalResource.map((d) => {
			return {
				children: d.children,
				relation_type: d.relation_type,
				form_id: item.form_id,
				relation_id: d.id,
				like_status: "common",
				errors: require_utilsByBooking.getErrorList(d, cacheItem),
				metadata: {
					form_name: item.title,
					resource_name: d.main_field
				}
			};
		});
		obj[item.form_id] = defaultResource;
	}
	return obj;
};
/**
* @title: 设置默认容量
* @description:
* @param {any} param1
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-09-19 20:26
*/
const setDefaultCapacitys = ({ capacitys, cacheItem }) => {
	if ((capacitys === null || capacitys === void 0 ? void 0 : capacitys.type) === "package") {
		var _cacheItem$_extend;
		return ((cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend = cacheItem._extend) === null || _cacheItem$_extend === void 0 || (_cacheItem$_extend = _cacheItem$_extend.other) === null || _cacheItem$_extend === void 0 ? void 0 : _cacheItem$_extend.bundle) || []).map((d) => {
			const id = d._bundle_product_id;
			const item = ((capacitys === null || capacitys === void 0 ? void 0 : capacitys.package) || []).find((item) => item.product_id === id);
			return {
				id,
				value: item ? d.quantity || 0 : 0,
				name: (item === null || item === void 0 ? void 0 : item.name) || (d === null || d === void 0 ? void 0 : d.title)
			};
		});
	}
	if ((capacitys === null || capacitys === void 0 ? void 0 : capacitys.type) === "custom") return ((capacitys === null || capacitys === void 0 ? void 0 : capacitys.custom) || []).map((d) => {
		return {
			id: d.id,
			value: d.min,
			name: d.name
		};
	});
	return [{
		id: 0,
		value: 1,
		name: ""
	}];
};
/**
* @title: 将商品内关联的资源id还原成数据
* @description:
* @param {any} resourcesOriginMap
* @param {any} cacheItem
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-09-19 20:23
*/
const getResourceByIds = (resourcesOriginMap, cacheItem, extraParams) => {
	var _cacheItem$product_re;
	let _resources = [...(cacheItem === null || cacheItem === void 0 || (_cacheItem$product_re = cacheItem.product_resource) === null || _cacheItem$product_re === void 0 ? void 0 : _cacheItem$product_re.resources) || []];
	const { extraResources = [], resourcesOrigin = [], resourceTab = {} } = extraParams || {};
	_resources = _resources.filter((d) => d.status == 1);
	for (let item of _resources) {
		var _resourceTab$item$cod;
		const form_id = item.id;
		const isAllResource = (resourceTab === null || resourceTab === void 0 || (_resourceTab$item$cod = resourceTab[item.code]) === null || _resourceTab$item$cod === void 0 ? void 0 : _resourceTab$item$cod.resource_display_scope) === "all";
		let extraResourceIds = [];
		if (isAllResource) extraResourceIds = (resourcesOrigin || []).filter((d) => d.form_code === item.code).map((d) => d.id);
		else extraResourceIds = extraResources.filter((_extraItem) => {
			return _extraItem.form_id === form_id && !!_extraItem.id && !item.optional_resource.includes(_extraItem.id) && !item.default_resource.includes(_extraItem.id);
		}).map((_extraItem) => _extraItem.id);
		extraResourceIds = Array.from(new Set(extraResourceIds));
		item.optional_resource = (item.optional_resource || []).filter((d) => item.default_resource.indexOf(d) == -1);
		const getChildrenMetadata = (d) => {
			const combiningResources = [];
			if (resourcesOriginMap[d].combined_resource && resourcesOriginMap[d].combined_resource.status === 1) resourcesOriginMap[d].combined_resource.resource_ids.forEach((id) => {
				if (resourcesOriginMap[id]) {
					var _resourcesOriginMap$i, _resourcesOriginMap$i2;
					combiningResources.push(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, resourcesOriginMap[id]), {}, { relation_id: ((_resourcesOriginMap$i = resourcesOriginMap[id]) === null || _resourcesOriginMap$i === void 0 ? void 0 : _resourcesOriginMap$i.relation_id) || ((_resourcesOriginMap$i2 = resourcesOriginMap[id]) === null || _resourcesOriginMap$i2 === void 0 ? void 0 : _resourcesOriginMap$i2.id) }));
				}
			});
			return {
				children: combiningResources,
				metadata: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, resourcesOriginMap[d].metadata), {}, { combined_resource: resourcesOriginMap[d].combined_resource })
			};
		};
		let optional_resource = Array.from(new Set([...item.optional_resource, ...extraResourceIds])).map((d) => {
			if (!resourcesOriginMap[d]) return null;
			return Object.assign({}, resourcesOriginMap[d], require_objectSpread2._objectSpread2({
				form_id,
				resourceType: item.type
			}, getChildrenMetadata(d)));
		}).filter((d) => d).concat(require_mock.getNoResource2({ form_id }));
		let default_resource = item.default_resource.map((d) => {
			let item = resourcesOriginMap[d];
			if (item) {
				item.is_default = 1;
				return Object.assign({}, item, require_objectSpread2._objectSpread2({
					form_id,
					resourceType: item.type
				}, getChildrenMetadata(d)));
			} else return null;
		}).filter((d) => d);
		item.renderList = optional_resource.concat(default_resource);
		item.form_id = form_id;
	}
	console.log("_resources", _resources);
	return _resources;
};
const getIsAutoClose = (cacheItem) => {
	var _cacheItem$_data;
	if (((_cacheItem$_data = cacheItem._data) === null || _cacheItem$_data === void 0 || (_cacheItem$_data = _cacheItem$_data.capacitys) === null || _cacheItem$_data === void 0 ? void 0 : _cacheItem$_data.type) !== "custom") {
		var _cacheItem$_data2;
		if ((cacheItem === null || cacheItem === void 0 || (_cacheItem$_data2 = cacheItem._data) === null || _cacheItem$_data2 === void 0 ? void 0 : _cacheItem$_data2.resources.length) === 1) {
			var _cacheItem$_data3, _first$select_type;
			const first = cacheItem === null || cacheItem === void 0 || (_cacheItem$_data3 = cacheItem._data) === null || _cacheItem$_data3 === void 0 ? void 0 : _cacheItem$_data3.resources[0];
			if (((_first$select_type = first.select_type) === null || _first$select_type === void 0 ? void 0 : _first$select_type.type) === "single") {
				if (first.default_resource.length > 0) return true;
			}
		}
	}
	return Object.entries(cacheItem._extend.resource).every(([key, value]) => {
		return require_utils.getAutoAllocationStorage(key) && (value === null || value === void 0 ? void 0 : value.length);
	});
};
/**
* @title: 是否是跨日商品
* @description:
* @param {any} cacheItem
* @return {*}
*/
const isMultiDayProduct = (product) => {
	var _product$duration;
	return (product === null || product === void 0 || (_product$duration = product.duration) === null || _product$duration === void 0 ? void 0 : _product$duration.type) === "days";
};
const getMultiDay = function() {
	var _ref = require_asyncToGenerator._asyncToGenerator(function* ({ start_date, end_date, state, cacheItem }) {
		let _cacheItem = cacheItem || state.service.cacheItem;
		if (isMultiDayProduct(_cacheItem)) {
			const { multiDayPrices, price } = yield require_utils$1.updateAppointmentServicePrice(state, {
				start_date,
				end_date,
				product_id: _cacheItem.product_id
			});
			_cacheItem._extend.multiDayPrices = require_utils$3.getMultiDayPrices(multiDayPrices || []);
			if (!(multiDayPrices === null || multiDayPrices === void 0 ? void 0 : multiDayPrices.length)) _cacheItem._extend.price = price;
			return _cacheItem;
		}
		return _cacheItem;
	});
	return function getMultiDay(_x) {
		return _ref.apply(this, arguments);
	};
}();
/**
* @title: 预生成服务的 extend
* @description:
* @param {any} param1
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-06-01 13:25
*/
const getProductExtend = ({ cacheItem, state, isDisabledTime }) => {
	console.time("console.time getProductExtend");
	const isNew = cacheItem.new || !cacheItem._extend.endDate;
	let _cacheItem = require_objectSpread2._objectSpread2({}, cacheItem);
	const resourcesOriginMap = state.service.resourcesOriginMap || {};
	_cacheItem._data = {};
	if (isMultiDayProduct(cacheItem)) {
		var _cacheItem$_extend2;
		_cacheItem._extend.holder_id = (cacheItem === null || cacheItem === void 0 || (_cacheItem$_extend2 = cacheItem._extend) === null || _cacheItem$_extend2 === void 0 ? void 0 : _cacheItem$_extend2.holder_id) || [];
		_cacheItem._extend.sub_type = "days";
	}
	if (isNew) {
		var _state$bookingConfig3;
		_cacheItem._data.timeObj = getTimeObj({
			cacheItem,
			currentResource: null,
			state
		});
		_cacheItem._extend = require_utilsByBooking.getServiceStartTimeAndEndTime(state, cacheItem, _cacheItem._data.timeObj);
		_cacheItem._data.capacitys = cacheItem.capacity;
		_cacheItem._data.resourcesOrigin = getResourceByIds(resourcesOriginMap, cacheItem, {
			resourceTab: state === null || state === void 0 || (_state$bookingConfig3 = state.bookingConfig) === null || _state$bookingConfig3 === void 0 || (_state$bookingConfig3 = _state$bookingConfig3.config) === null || _state$bookingConfig3 === void 0 ? void 0 : _state$bookingConfig3.resource_tab,
			resourcesOrigin: state.service.resourcesOrigin
		});
		_cacheItem._extend.capacity = setDefaultCapacitys({
			capacitys: _cacheItem._data.capacitys,
			cacheItem: _cacheItem
		});
		const { list, maps } = formatResources({
			cacheItem: _cacheItem,
			resourcesOrigin: _cacheItem._data.resourcesOrigin
		});
		_cacheItem._data.resources = list;
		_cacheItem._data.resourceMaps = maps;
		_cacheItem._extend.resource = setDefaultResource({
			cacheItem: _cacheItem,
			resources: _cacheItem._data.resources
		});
		if (require_utils$2.getDuration(_cacheItem === null || _cacheItem === void 0 ? void 0 : _cacheItem.duration)) {
			_cacheItem._data.timeObj = getTimeObj({
				cacheItem: _cacheItem,
				useStartTime: _cacheItem._extend.start_time,
				currentResource: _cacheItem._extend.resource,
				state
			});
			if (require_utils$2.getDuration(_cacheItem === null || _cacheItem === void 0 ? void 0 : _cacheItem.duration) === "flexible") {
				var _cacheItem$_data$time;
				_cacheItem._extend.duration = (_cacheItem$_data$time = _cacheItem._data.timeObj) === null || _cacheItem$_data$time === void 0 || (_cacheItem$_data$time = _cacheItem$_data$time.durationSlicesBasedOnTime) === null || _cacheItem$_data$time === void 0 || (_cacheItem$_data$time = _cacheItem$_data$time[0]) === null || _cacheItem$_data$time === void 0 ? void 0 : _cacheItem$_data$time.value;
				const { startDate, endDate } = require_utils$2.getServiceTimes(_cacheItem);
				_cacheItem._extend.endDate = endDate;
			}
		}
		_cacheItem.autoClose = getIsAutoClose(_cacheItem);
		if (_cacheItem._extend.bundle_edit !== void 0) _cacheItem._extend.bundle_edit = 1;
		if (!isDisabledTime) _cacheItem._time = (/* @__PURE__ */ new Date()).getTime();
	} else {
		if (!_cacheItem._data.capacitys) _cacheItem._data.capacitys = cacheItem.capacity;
		if (!_cacheItem._data.resourcesOrigin) {
			var _state$bookingConfig4;
			const extraResources = [];
			if (Array.isArray(_cacheItem._extend.event_resources)) _cacheItem._extend.event_resources.forEach((_item) => {
				extraResources.push({
					form_id: _item.form_id,
					id: _item.relation_id
				});
			});
			_cacheItem._data.resourcesOrigin = getResourceByIds(resourcesOriginMap, cacheItem, {
				extraResources,
				resourceTab: state === null || state === void 0 || (_state$bookingConfig4 = state.bookingConfig) === null || _state$bookingConfig4 === void 0 || (_state$bookingConfig4 = _state$bookingConfig4.config) === null || _state$bookingConfig4 === void 0 ? void 0 : _state$bookingConfig4.resource_tab,
				resourcesOrigin: state.service.resourcesOrigin
			});
		}
		if (!_cacheItem._data.resources) {
			const { list, maps } = formatResources({
				cacheItem: _cacheItem,
				resourcesOrigin: _cacheItem._data.resourcesOrigin
			});
			_cacheItem._data.resources = list;
			_cacheItem._data.resourceMaps = maps;
		}
		_cacheItem._data.timeObj = getTimeObj({
			cacheItem: _cacheItem,
			useStartTime: _cacheItem._extend.start_time,
			currentResource: _cacheItem._extend.resource,
			state
		});
	}
	console.timeEnd("console.time getProductExtend");
	return _cacheItem;
};
//#endregion
exports.formatResources = formatResources;
exports.getDurationProps = getDurationProps;
exports.getFlexibleOption = getFlexibleOption;
exports.getMultiDay = getMultiDay;
exports.getProductExtend = getProductExtend;
exports.getResourceByIds = getResourceByIds;
exports.getTimeObj = getTimeObj;
exports.getUsableTime = getUsableTime;
exports.isMultiDayProduct = isMultiDayProduct;
exports.setDefaultCapacitys = setDefaultCapacitys;
