const require_runtime = require("../../../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_utils = require("../../../utils.js");
const require_model = require("../../model.js");
const require_index = require("../../../components/drawer/index.js");
const require_useEngineContext = require("../../../../../hooks/useEngineContext.js");
const require_index$1 = require("../../../components/browserSelect/index.js");
const require_index$2 = require("../../../components/footer/index.js");
const require_utils$1 = require("./utils.js");
const require_serve = require("./serve.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
let react = require("react");
react = require_runtime.__toESM(react);
let antd = require("antd");
let _pisell_utils = require("@pisell/utils");
let classnames = require("classnames");
classnames = require_runtime.__toESM(classnames);
let ahooks = require("ahooks");
require("./index.less");
//#region src/components/booking/info/service/addTimeModal/index.tsx
const numberList = (0, _pisell_utils.createArray)(100, (d, i) => {
	return {
		label: i + 1,
		value: i + 1
	};
});
const AddTimeModal = () => {
	var _context$appHelper, _state$bookingConfig2, _currentTimeItem$stat, _currentProduct$add_t;
	const { state, dispatch } = (0, react.useContext)(require_model.Context);
	const [isEdit, setIsEdit] = (0, react.useState)(false);
	const [loading, setLoading] = (0, react.useState)("");
	const [recordKey, setRecordKey] = (0, react.useState)("");
	const [number, setNumber] = (0, react.useState)(1);
	const [newPrice, setNewPrice] = (0, react.useState)(0);
	const originServices = (0, react.useRef)([]);
	const [renderList, setRenderList] = (0, react.useState)([]);
	const { interaction } = (_context$appHelper = require_useEngineContext.default().appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils;
	const statusMap = {
		available: {
			label: _pisell_utils.locales.getText("page.booking.text.available"),
			color: "#079455"
		},
		fully_booked: {
			label: _pisell_utils.locales.getText("page.booking.text.fully-booked"),
			color: "#DC6803"
		},
		unavailable: {
			label: _pisell_utils.locales.getText("page.booking.text.unavailable"),
			color: "#98A2B3"
		}
	};
	const updateServices = (0, ahooks.useDebounceFn)(() => {
		createNewServices();
	}, { wait: 200 });
	const transaction_habit_selection = (0, react.useMemo)(() => {
		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.transaction_habit_selection) || {
			type: "service_now_pay_later",
			button_rows: 1
		};
	}, [state === null || state === void 0 || (_state$bookingConfig2 = state.bookingConfig) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.config) === null || _state$bookingConfig2 === void 0 ? void 0 : _state$bookingConfig2.information_tab]);
	const currentProductId = (0, react.useMemo)(() => {
		return require_utils$1.addTimeRowKey.getValue(recordKey).product_id;
	}, [recordKey]);
	const currentTime = (0, react.useMemo)(() => {
		return require_utils$1.addTimeRowKey.getValue(recordKey).time || "";
	}, [recordKey]);
	const currentProduct = (0, react.useMemo)(() => {
		return (renderList || []).find((d) => d.id == currentProductId);
	}, [renderList, currentProductId]);
	const currentTimeItem = (0, react.useMemo)(() => {
		var _currentProduct$times;
		return (currentProduct === null || currentProduct === void 0 || (_currentProduct$times = currentProduct.times) === null || _currentProduct$times === void 0 ? void 0 : _currentProduct$times.find((d) => d.value == currentTime)) || { price: 0 };
	}, [currentTime, currentProduct]);
	const currentResource = (0, react.useMemo)(() => {
		var _state$service;
		return (((_state$service = state.service) === null || _state$service === void 0 ? void 0 : _state$service.resourcesOrigin) || []).find((d) => {
			var _state$service$cacheI;
			return d.form_record_id == ((_state$service$cacheI = state.service.cacheItem) === null || _state$service$cacheI === void 0 || (_state$service$cacheI = _state$service$cacheI._extend) === null || _state$service$cacheI === void 0 ? void 0 : _state$service$cacheI.relation_id);
		});
	}, [state.service.cacheItem, state.service.resourcesOrigin]);
	const currentResourceTimeEndDate = (0, react.useMemo)(() => {
		try {
			var _state$service$cacheI2;
			if (!currentResource || !((_state$service$cacheI2 = state.service.cacheItem) === null || _state$service$cacheI2 === void 0 ? void 0 : _state$service$cacheI2._extend)) return "";
			let timeItem = currentResource === null || currentResource === void 0 ? void 0 : currentResource.times.find((_time) => _time.item_id === state.service.cacheItem._extend.relation_id);
			return (0, dayjs.default)(timeItem.end_date + " " + timeItem.end_time).add(1, "second");
		} catch (err) {
			console.log("err", err);
		}
		return "";
	}, [state.service.cacheItem, currentResource]);
	(0, react.useEffect)(() => {
		if (currentTimeItem.price) setNewPrice(currentTimeItem.price * number);
	}, [currentTimeItem, number]);
	const getTimeUsableStatus = (time) => {
		var _state$service$cacheI3;
		if (!((_state$service$cacheI3 = state.service.cacheItem) === null || _state$service$cacheI3 === void 0 ? void 0 : _state$service$cacheI3._extend) || !currentResource) return { status: statusMap.unavailable };
		try {
			var _res$_extend;
			let _extend = require_objectSpread2._objectSpread2({}, state.service.cacheItem._extend);
			_extend.endDate = _extend.endDate.add(time, "minutes");
			_extend.start_date = _extend.startDate;
			_extend.end_date = _extend.endDate;
			_extend.end_time = _extend.endDate.format("HH:mm");
			_extend.start_time = _extend.startDate.format("HH:mm");
			_extend.duration = require_utils.flexibleObj.add(_extend.duration, time);
			if (require_utils.isNowTime(_extend.start_time)) _extend.start_time = require_utils.getNowTime();
			_extend.startDate.format("hh:mm A");
			let endText = _extend.endDate.format("hh:mm A");
			if (_extend.endDate.isAfter(_extend.startDate, "day")) endText = _pisell_utils.locales.getText("pisell1.text.tomorrow") + endText;
			if (!((_res$_extend = require_utils.getResourceTimeIsUsable(currentResource === null || currentResource === void 0 ? void 0 : currentResource.times.find((_time) => _time.item_id === _extend.relation_id), require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, state.service.cacheItem), {}, { _extend: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, state.service.cacheItem._extend), _extend) }))._extend) === null || _res$_extend === void 0 ? void 0 : _res$_extend.isUsable)) return {
				status: statusMap.unavailable,
				message: `${currentResource.room_name || currentResource.name} ${_pisell_utils.locales.getText("pisell2.text.status.service-error-2")}`
			};
		} catch (err) {}
		return { status: statusMap.available };
	};
	const _getAddTimeProducts = function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* () {
			var _state$client, _state$client2;
			const data = yield require_serve.getAddTimeProducts({
				skip: 1,
				num: 500,
				open_quotation: 1,
				status: "published",
				schedule_date: state.date.value.format("YYYY-MM-DD"),
				customer_id: require_utils.isWalkIn((_state$client = state.client) === null || _state$client === void 0 || (_state$client = _state$client.value) === null || _state$client === void 0 ? void 0 : _state$client.id) ? void 0 : (_state$client2 = state.client) === null || _state$client2 === void 0 || (_state$client2 = _state$client2.value) === null || _state$client2 === void 0 ? void 0 : _state$client2.id,
				extension_type: ["product_add_time"],
				status: "published"
			}, { useCache: true });
			return (data === null || data === void 0 ? void 0 : data.list) || [];
		});
		return function _getAddTimeProducts() {
			return _ref.apply(this, arguments);
		};
	}();
	const getTimeProducts = function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* () {
			setLoading("list");
			let list = (yield _getAddTimeProducts()).map((d) => {
				let isUsable = require_utils$1.isUsableProduct(d.add_time, state.service.cacheItem);
				return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, d), {}, {
					usable: isUsable,
					times: isUsable ? require_utils$1.getAddTimeSplits(d, state.service.cacheItem, currentResourceTimeEndDate).map((time) => {
						return require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, time), {}, { status: getTimeUsableStatus(time.value) });
					}) : void 0
				});
			}).filter((d) => d.usable && d.times.length).sort((a, b) => b.sort - a.sort);
			setRenderList(list);
			if (list.length) setDefaultProduct(list);
			setLoading("");
			setIsEdit(true);
		});
		return function getTimeProducts() {
			return _ref2.apply(this, arguments);
		};
	}();
	const setDefaultProduct = (list) => {
		try {
			let productId = list[0].id;
			let time = list[0].times[0].value;
			setRecordKey(require_utils$1.addTimeRowKey.create(productId, time));
		} catch (err) {}
	};
	(0, ahooks.useUpdateEffect)(() => {
		if (state.service.addTimeModal) {
			getTimeProducts();
			originServices.current = state.service;
		} else updateServices.run();
	}, [state.service.addTimeModal]);
	const onSelectItem = (pItem, item) => {
		setRecordKey(require_utils$1.addTimeRowKey.create(pItem.id, item.value));
		setIsEdit(true);
		updateServices.run();
	};
	const newService = (0, react.useMemo)(() => {
		if (!currentProduct || !state.service.cacheItem) return null;
		const relation_product = {
			product_add_schedule_time: currentTime,
			num: number,
			price: currentTimeItem.price || 0,
			product_id: currentProduct.id,
			discount_amount: 0,
			product_discount_reason: "",
			is_charge_tax: currentProduct.is_charge_tax,
			discountway: "num",
			discount_type: "discount"
		};
		let _extend = require_objectSpread2._objectSpread2({}, state.service.cacheItem._extend);
		let relation_products = require_utils$1.createRelationProducts(number, newPrice, relation_product);
		_extend.endDate = _extend.endDate.add(relation_product.product_add_schedule_time, "minutes");
		const start_date = _extend.startDate.format("YYYY-MM-DD");
		const end_date = _extend.endDate.format("YYYY-MM-DD");
		const end_time = _extend.endDate.format("HH:mm");
		let start_time = _extend.startDate.format("HH:mm");
		let duration = require_utils.flexibleObj.add(_extend.duration, relation_product.product_add_schedule_time);
		if (require_utils.isNowTime(_extend.start_time)) start_time = require_utils.getNowTime();
		_extend.relation_details = (_extend.relation_details || []).concat(relation_products);
		_extend.duration = duration;
		_extend.start_time = start_time;
		_extend.end_time = end_time;
		_extend.start_date = start_date;
		_extend.end_date = end_date;
		return {
			id: _extend.id,
			relation_id: _extend.relation_id,
			like_status: _extend.like_status,
			relation_type: _extend.relation_type,
			is_all: _extend.is_all,
			schedule_id: _extend.schedule_id,
			end_time,
			sub_type: _extend.sub_type,
			select_date: start_date,
			start_time,
			end_date,
			start_date,
			duration,
			number: _extend.number || 1,
			relation_products,
			_extend
		};
	}, [
		currentTime,
		state.service.cacheItem,
		currentProduct,
		number,
		currentTimeItem,
		newPrice
	]);
	const resetService = () => {
		var _originServices$curre, _originServices$curre2;
		let _val = ((_originServices$curre = originServices.current) === null || _originServices$curre === void 0 ? void 0 : _originServices$curre.value) || [];
		let _edit = (_originServices$curre2 = originServices.current) === null || _originServices$curre2 === void 0 ? void 0 : _originServices$curre2.edit;
		originServices.current = null;
		dispatch({
			type: "setService",
			payload: {
				value: _val,
				edit: _edit
			}
		});
	};
	const createNewServices = (0, ahooks.useMemoizedFn)(() => {
		var _state$service2;
		let _list = ((_state$service2 = state.service) === null || _state$service2 === void 0 ? void 0 : _state$service2.value) || [];
		if (!originServices.current) return;
		if (state.service.addTimeModal) {
			_list = _list.map((d) => {
				let _item = require_objectSpread2._objectSpread2({}, d);
				if (_item._extend.id === (newService === null || newService === void 0 ? void 0 : newService.id)) _item = require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, _item), newService || {}), {}, { _extend: newService === null || newService === void 0 ? void 0 : newService._extend });
				return _item;
			});
			dispatch({
				type: "setService",
				payload: {
					value: _list,
					edit: true
				}
			});
		} else resetService();
	});
	const goCheckout = function() {
		var _ref3 = require_asyncToGenerator._asyncToGenerator(function* () {
			/** terminal中打开原生checkout模块 */
			if (state.isTerminal) {
				var _interaction$utils, _interaction$utils$po;
				return interaction === null || interaction === void 0 || (_interaction$utils = interaction.utils) === null || _interaction$utils === void 0 || (_interaction$utils$po = _interaction$utils.postMessageToApp) === null || _interaction$utils$po === void 0 ? void 0 : _interaction$utils$po.call(_interaction$utils, {
					module: "booking",
					key: "booking_checkout",
					data: {
						order_id: state.bookingId,
						callbackType: "pisell2"
					}
				});
			}
			state.action({
				type: "pisell1.handlePayment",
				data: { orderId: state.bookingId },
				callback: () => {
					state === null || state === void 0 || state.callback();
				}
			});
		});
		return function goCheckout() {
			return _ref3.apply(this, arguments);
		};
	}();
	const handleCheckout = function() {
		var _ref4 = require_asyncToGenerator._asyncToGenerator(function* () {
			if (isEdit) yield handleSave("checkout");
			goCheckout();
		});
		return function handleCheckout() {
			return _ref4.apply(this, arguments);
		};
	}();
	const handleSave = function() {
		var _ref5 = require_asyncToGenerator._asyncToGenerator(function* (loadingType = "save") {
			if (currentTime === null) return;
			setLoading(loadingType);
			yield require_serve.saveAddTimeProduct({
				orderId: state.bookingId,
				params: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, newService), {}, { _extend: void 0 })
			});
			setLoading("");
			antd.message.success(_pisell_utils.locales.getText("page.booking.text.add-time-success"));
			onCancel();
			if (loadingType === "checkout") return;
			state === null || state === void 0 || state.action("init");
		});
		return function handleSave() {
			return _ref5.apply(this, arguments);
		};
	}();
	(0, react.useEffect)(() => {
		if (!state.modalOpen) onCancel();
	}, [state.modalOpen]);
	const onCancel = () => {
		setIsEdit(false);
		setRecordKey("");
		resetService();
		setTimeout(() => {
			dispatch({
				type: "setService",
				payload: { addTimeModal: false }
			});
		}, 50);
	};
	const updateTime = (0, react.useMemo)(() => {
		if (!newService) return "";
		let startTime = newService.start_time;
		let endTime = newService.end_time;
		let hours = require_utils.getDiscountTime(require_utils.flexibleObj.getValue(newService.duration));
		if (newService.start_date !== newService.end_date) {
			const locale = state.locale;
			const format = locale === "en" || locale === "en-US" ? "HH:mm DD/MM" : "MM-DD HH:mm";
			startTime = (0, _pisell_utils.formatDate)(`${newService.start_date} ${newService.start_time}`, format);
			endTime = (0, _pisell_utils.formatDate)(`${newService.end_date} ${newService.end_time}`, format);
		}
		return `${startTime} ~ ${endTime} (${hours})`;
	}, [newService, state.locale]);
	return /* @__PURE__ */ react.default.createElement(require_index.default, {
		titleNoWrap: true,
		open: state.service.addTimeModal,
		title: _pisell_utils.locales.getText("page.booking.text.add-time"),
		rootClassName: "booking-server-wrap",
		onClose: onCancel,
		footerStyle: { padding: "10px 32px 20px" },
		hideScrollBar: false,
		bodyStyle: { position: "relative" },
		footer: /* @__PURE__ */ react.default.createElement("div", null, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-total-wrap" }, currentTimeItem && (currentTimeItem === null || currentTimeItem === void 0 || (_currentTimeItem$stat = currentTimeItem.status) === null || _currentTimeItem$stat === void 0 ? void 0 : _currentTimeItem$stat.message) ? /* @__PURE__ */ react.default.createElement(antd.Alert, {
			message: currentTimeItem.status.message,
			type: "warning",
			showIcon: true,
			style: { marginBottom: 12 }
		}) : null, newService ? /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-summary-wrap" }, /* @__PURE__ */ react.default.createElement("div", {
			className: "pisell-lowcode__booking-add-time-summary-item",
			style: { flex: 1 }
		}, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-summary-label" }, _pisell_utils.locales.getText("page.booking.text.update-time"), ":"), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-summary-value" }, updateTime)), (currentProduct === null || currentProduct === void 0 || (_currentProduct$add_t = currentProduct.add_time) === null || _currentProduct$add_t === void 0 ? void 0 : _currentProduct$add_t.calculate_type) === "select_quantity" && /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-summary-item" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-summary-label" }, _pisell_utils.locales.getText("page.booking.text.quantity")), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-summary-value" }, /* @__PURE__ */ react.default.createElement(require_index$1.default, {
			value: number,
			onChange: (e) => {
				setNumber(Number(e.target.value));
				updateServices.run();
			},
			className: "pisell-lowcode__booking-add-time-quantity-select",
			options: numberList
		}))), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-summary-item" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-summary-label" }, _pisell_utils.locales.getText("pisell1.text.subtotal")), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-summary-value" }, /* @__PURE__ */ react.default.createElement(antd.InputNumber, {
			prefix: state.amountSymbol,
			size: "large",
			value: newPrice,
			precision: 2,
			style: {
				minWidth: 150,
				alignItems: "center",
				height: 44
			},
			min: 0,
			max: (currentTimeItem.price || 0) * number,
			onChange: (e) => {
				setNewPrice(e);
				updateServices.run();
			}
		})))) : null), /* @__PURE__ */ react.default.createElement(require_index$2.default, {
			state,
			dispatch,
			source: "addTime",
			buttons: [/* @__PURE__ */ react.default.createElement(antd.Button, {
				className: "pisell-lowcode__booking-footer-buttons-item",
				type: transaction_habit_selection.type === "service_now_pay_later" ? "default" : "primary",
				disabled: loading === "list" || !isEdit || !currentTime,
				onClick: handleCheckout,
				loading: loading === "checkout"
			}, _pisell_utils.locales.getText("pisell2.text.checkout")), /* @__PURE__ */ react.default.createElement(antd.Button, {
				className: "pisell-lowcode__booking-footer-buttons-item",
				type: transaction_habit_selection.type === "service_now_pay_later" ? "primary" : "default",
				disabled: loading === "list" || !isEdit || !currentTime,
				loading: loading === "save",
				onClick: () => {
					handleSave("save");
				}
			}, _pisell_utils.locales.getText("pisell2.text.save"))]
		}))
	}, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-body" }, /* @__PURE__ */ react.default.createElement(antd.Skeleton, {
		loading: loading === "list",
		active: true,
		round: true
	}, /* @__PURE__ */ react.default.createElement("div", { className: "" }, renderList.map((d) => {
		return /* @__PURE__ */ react.default.createElement("div", { className: "" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-hours" }, d.title), d.times ? /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-child-card-list" }, d.times.map((child) => {
			var _child$status, _child$status2;
			return /* @__PURE__ */ react.default.createElement("div", {
				className: (0, classnames.default)("pisell-lowcode__booking-add-time-child-card", { "pisell-lowcode__booking-add-time-child-card-active": recordKey === require_utils$1.addTimeRowKey.create(d.id, child.value) }),
				onClick: () => {
					if (!child.value) return;
					onSelectItem(d, child);
				}
			}, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-child-card-left" }, /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-child-card-left-time" }, child.label), /* @__PURE__ */ react.default.createElement("div", { className: "pisell-lowcode__booking-add-time-child-card-left-price" }, (0, _pisell_utils.formatAmount)(child.price, 2, state.amountSymbol))), /* @__PURE__ */ react.default.createElement("div", {
				className: "pisell-lowcode__booking-add-time-child-card-right",
				style: { color: (_child$status = child.status) === null || _child$status === void 0 || (_child$status = _child$status.status) === null || _child$status === void 0 ? void 0 : _child$status.color }
			}, (_child$status2 = child.status) === null || _child$status2 === void 0 || (_child$status2 = _child$status2.status) === null || _child$status2 === void 0 ? void 0 : _child$status2.label));
		})) : null);
	}))), /* @__PURE__ */ react.default.createElement("div", { className: "" })));
};
//#endregion
exports.default = AddTimeModal;
