import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { getSumTotal } from "../../../booking/components/footer/amount.js";
import { _objectWithoutProperties } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import { getBoardConfigCache, setBoardConfigCache } from "../../utils/productCache.js";
import { formatDateToStr, formatHolder, getDisabledEdit, getIsParallelResourcesBooking, getNextTimeSlice, restoreProductOtherData } from "../../utils/index.js";
import { formatProducts } from "../../../booking/info/service2/utils.js";
import useEngineContext from "../../../../hooks/useEngineContext.js";
import { useOsKey } from "../../context/OsKeyContext.js";
import { useShopDiscountModule } from "../../hooks/pisellos/useShopDiscountModule.js";
import { useBookingTicket } from "../../hooks/pisellos/bookingTicket.js";
import { useIsActive } from "../../context/IsActiveContext.js";
import { useCustomer } from "../../hooks/pisellos/useCustomer.js";
import useScanManager from "../../hooks/pisellos/useScanManager.js";
import APP from "../../../booking/info/index.js";
import { getBookingConfig, getBookingDetail, getEventBookingDetail, getOrderInfoByCode, getServices, serve_exports } from "../../serve.js";
import { useStore } from "../../miniRedux.js";
import AddServiceVariant from "../addServiceVariant/index.js";
import TimeBar from "../timeBar/index.js";
import formatProductMessage from "../../utils/formatProductMessage.js";
import { getBookingType } from "../bookingDataPanel/bookingList/utils.js";
import pisellFloatingPanel_default from "../bookingDataPanel/pisellFloatingPanel/index.js";
import FloatButtons from "../floatButtons/index.js";
import useScanGlobal from "../../hooks/pisellos/useScanGlobal.js";
import useScanGlobalHandle from "../../hooks/pisellos/useScanGlobalHandle.js";
import dayjs from "dayjs";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { message } from "antd";
import { locales, sendWarningLog } from "@pisell/utils";
import { Iconfont, PisellModal, useToast } from "@pisell/materials";
import { useDebounceFn, useMemoizedFn } from "ahooks";
import "./index.less";
//#region src/components/ticketBooking/components/ticketBooking/index.tsx
const _excluded = ["detail", "product"];
const _formatBookingDetail = (data, modalState) => {
	var _bookings$list, _bookings$list2;
	let { customer_id, holder, customer_name, email, phone, country_calling_code, bookings, customer, note, payment_status, is_other_entrance_edited, shop_discount, relation_details = [] } = data;
	const clientValue = {
		name: ((customer === null || customer === void 0 ? void 0 : customer.display_name) || "").trim() || ((customer === null || customer === void 0 ? void 0 : customer.nickname) || "").trim() || "",
		id: customer_id || (customer === null || customer === void 0 ? void 0 : customer.id) || (customer === null || customer === void 0 ? void 0 : customer.customer_id) || 1,
		email: customer === null || customer === void 0 ? void 0 : customer.email,
		phone: (customer === null || customer === void 0 ? void 0 : customer.phone) || "",
		country_calling_code: (customer === null || customer === void 0 ? void 0 : customer.country_calling_code) || "",
		cover: (customer === null || customer === void 0 ? void 0 : customer.cover) || ""
	};
	const start_date = bookings === null || bookings === void 0 || (_bookings$list = bookings.list) === null || _bookings$list === void 0 || (_bookings$list = _bookings$list[0]) === null || _bookings$list === void 0 ? void 0 : _bookings$list.start_date;
	const dateValue = dayjs(start_date ? start_date + " " + (bookings === null || bookings === void 0 || (_bookings$list2 = bookings.list) === null || _bookings$list2 === void 0 || (_bookings$list2 = _bookings$list2[0]) === null || _bookings$list2 === void 0 ? void 0 : _bookings$list2.start_time) : /* @__PURE__ */ new Date());
	const getCapacity = (resetD) => {
		var _resetD$metadata;
		return (_resetD$metadata = resetD.metadata) === null || _resetD$metadata === void 0 ? void 0 : _resetD$metadata.capacity;
	};
	const getResource = (resetD) => {
		if (!bookings.relation_type) try {
			var _resetD$event_resourc;
			if ((resetD === null || resetD === void 0 ? void 0 : resetD.event_resources) && (resetD === null || resetD === void 0 || (_resetD$event_resourc = resetD.event_resources) === null || _resetD$event_resourc === void 0 ? void 0 : _resetD$event_resourc.length)) return resetD.event_resources.reduce((pre, cur) => {
				if (pre[cur.form_id]) pre[cur.form_id].push(cur);
				else pre[cur.form_id] = [cur];
				return pre;
			}, {});
		} catch (err) {
			console.error(err);
		}
		return resetD.relation_id;
	};
	let serviceValue = bookings.list.map((d) => {
		let { detail, product } = d, resetD = _objectWithoutProperties(d, _excluded);
		let _detail = detail || mockProduct;
		let start_date = dayjs(resetD.start_date + " " + resetD.start_time);
		let end_date = dayjs(resetD.end_date + " " + resetD.end_time);
		return _objectSpread2(_objectSpread2({ _id: (Math.random() + "").replace(/\D/g, "").substring(0, 11) }, _detail), {}, {
			duration: (_detail === null || _detail === void 0 ? void 0 : _detail.duration) || (product === null || product === void 0 ? void 0 : product.duration),
			"schedule.ids": (_detail === null || _detail === void 0 ? void 0 : _detail["schedule.ids"]) || (product === null || product === void 0 ? void 0 : product["schedule.ids"]),
			booking_id: resetD.id,
			isEditBooking: true,
			id: _detail.product_id,
			title: _detail.product_title,
			quantity: Number(_detail.product_quantity),
			cover: _detail.product_cover,
			price: Number(_detail.source_product_price),
			relation_form_name: resetD.relation_form_name,
			product_resource: product === null || product === void 0 ? void 0 : product.product_resource,
			capacity: product === null || product === void 0 ? void 0 : product.capacity,
			_extend: _objectSpread2(_objectSpread2({}, resetD), {}, {
				quantity: Number(_detail.product_quantity),
				startDate: start_date,
				start_date,
				endDate: end_date,
				end_date,
				holder_id: formatHolder(resetD),
				note: _detail.note,
				price: Number(_detail.source_product_price),
				product_name: _detail.product_title,
				discount_reason: _detail.product_discount_reason,
				order_detail_id: _detail.order_detail_id,
				total: Number(_detail.selling_price),
				origin_total: Number(_detail.original_price),
				payment_price: Number(_detail.payment_price),
				other: restoreProductOtherData(d),
				bundle_edit: 0,
				discount_per: _detail.discount_per,
				discount_type: _detail.discount_type,
				discountway: _detail.discountway,
				capacity: getCapacity(resetD),
				resource: getResource(resetD)
			})
		});
	});
	serviceValue = [...serviceValue, ...formatProductValues(relation_details)];
	let disabledEdit = getDisabledEdit(data);
	let channelDisabledEdit = !!is_other_entrance_edited;
	return _objectSpread2(_objectSpread2({}, modalState), {}, {
		client: _objectSpread2(_objectSpread2({}, modalState.client), {}, {
			value: clientValue,
			edit: false,
			showModal: false
		}),
		date: _objectSpread2(_objectSpread2({}, modalState.date), {}, {
			value: dateValue,
			edit: false,
			showModal: false
		}),
		pet: _objectSpread2(_objectSpread2({}, modalState.pet), {}, {
			showModal: false,
			edit: false
		}),
		service: _objectSpread2(_objectSpread2({}, modalState.service), {}, {
			value: serviceValue,
			addModal: false,
			editModal: false,
			edit: false
		}),
		notes: _objectSpread2(_objectSpread2({}, modalState.notes), {}, {
			orderNote: note,
			edit: false
		}),
		disabledEdit,
		channelDisabledEdit,
		appointment_status: bookings === null || bookings === void 0 ? void 0 : bookings.appointment_status
	});
};
const formatProductValues = (data) => {
	return data.map((d) => {
		return _objectSpread2(_objectSpread2({}, d), {}, {
			_id: (Math.random() + "").replace(/\D/g, "").substring(0, 11),
			id: d.product_id,
			title: d.product_title,
			quantity: d.product_quantity,
			cover: d.product_cover,
			price: Number(d.source_product_price),
			isEditBooking: true,
			_extend: {
				discount_reason: d.product_discount_reason,
				order_detail_id: d.order_detail_id,
				discount_per: d.discount_per,
				discount_type: d.discount_type,
				discountway: d.discountway,
				product_name: d.product_title,
				total: Number(d.selling_price),
				origin_total: Number(d.original_price),
				payment_price: Number(d.payment_price),
				price: Number(d.source_product_price),
				quantity: d.product_quantity,
				bundle_edit: 0,
				other: restoreProductOtherData(d),
				startDate: dayjs(),
				endDate: dayjs(),
				note: d.note
			},
			payment_price: Number(d.payment_price)
		});
	});
};
const TicketBooking = (props) => {
	var _engineContext$appHel, _state$modalState3, _state$modalState5;
	const { onPrerenderComplete, productDisplayConfig, isShowTimeBar = true, isShowFloatButtons = true } = props;
	const [state, setState] = useStore();
	const getProductsRef = useRef(null);
	const handleGetProductsReady = useMemoizedFn((getProducts) => {
		getProductsRef.current = getProducts;
	});
	const engineContext = useEngineContext();
	const { props: engineProps } = engineContext.engine;
	const { action, isTerminal, lowcodeRef, interaction, store, storage, getSymbolic, translation, pisellosAllModule, getData } = (_engineContext$appHel = engineContext.appHelper) === null || _engineContext$appHel === void 0 ? void 0 : _engineContext$appHel.utils;
	const { ScheduleModule } = pisellosAllModule;
	const Toast = useToast();
	const _persistentRef = useRef(false);
	const _initStateRef = useRef({});
	const _listTimerRef = useRef();
	const _timerRef = useRef();
	const _callbackFnRef = useRef();
	const _isFirstLoadBoardConfigRef = useRef(true);
	const [activeBookingId, setActiveBookingId] = useState(0);
	const [showTerminalUpgradeModal, setShowTerminalUpgradeModal] = useState(false);
	const pisellFloatingPanelRef = useRef(null);
	const closeRef = useRef(null);
	const shopDiscount = useShopDiscountModule();
	const isActive = useIsActive();
	const osKey = useOsKey();
	const bookingTicket = useBookingTicket();
	const { openScan, closeScan } = useScanGlobal();
	const handleScan = useScanGlobalHandle();
	const { enableAllScanListeners } = useScanManager();
	const { selectCustomer } = useCustomer();
	const checkTerminalVersion = useMemoizedFn(() => {
		if (isTerminal()) {
			const userAgent = navigator.userAgent;
			if (userAgent.includes("terminal")) {
				const terminalVersionMatch = userAgent.match(/terminal\/[\d.]+\((\d+)\)/i);
				if (terminalVersionMatch && terminalVersionMatch[1]) {
					const buildNumberStr = terminalVersionMatch[1];
					const buildNumber = parseInt(buildNumberStr, 10);
					if (userAgent.includes("com.funtovia.pos")) {
						if (!isNaN(buildNumber) && buildNumber > 0 && buildNumber < 7) setShowTerminalUpgradeModal(true);
						return;
					}
					if (userAgent.includes("com.bbpet.pos")) {
						if (!isNaN(buildNumber) && buildNumber > 0 && buildNumber < 6) setShowTerminalUpgradeModal(true);
						return;
					}
					if (!isNaN(buildNumber) && buildNumber > 0 && buildNumber < 766) setShowTerminalUpgradeModal(true);
				}
			}
		}
	});
	useEffect(() => {
		if (isActive) openScan((data) => {
			handleScan(data);
		});
		return () => {
			closeScan();
		};
	}, [isActive]);
	const { run: clearAllCart } = useDebounceFn((type, orderId) => {
		try {
			var _store$getState;
			_initFn(() => {});
			_setIntervalTime(true);
			setState({ createCount: state.createCount + 1 });
			sendWarningLog({
				title: "清空购物车",
				content: [
					{
						key: "店铺id",
						value: store === null || store === void 0 || (_store$getState = store.getState) === null || _store$getState === void 0 || (_store$getState = _store$getState.call(store)) === null || _store$getState === void 0 || (_store$getState = _store$getState.global) === null || _store$getState === void 0 || (_store$getState = _store$getState.globalConfig) === null || _store$getState === void 0 ? void 0 : _store$getState.id
					},
					{
						key: "订单id",
						value: orderId
					},
					{
						key: "类型",
						value: type
					}
				]
			});
		} catch (err) {
			var _store$getState2;
			sendWarningLog({
				title: "清空购物车失败",
				content: [
					{
						key: "店铺id",
						value: store === null || store === void 0 || (_store$getState2 = store.getState) === null || _store$getState2 === void 0 || (_store$getState2 = _store$getState2.call(store)) === null || _store$getState2 === void 0 || (_store$getState2 = _store$getState2.global) === null || _store$getState2 === void 0 || (_store$getState2 = _store$getState2.globalConfig) === null || _store$getState2 === void 0 ? void 0 : _store$getState2.id
					},
					{
						key: "订单id",
						value: orderId
					},
					{
						key: "类型",
						value: type
					},
					{
						key: "error",
						value: err === null || err === void 0 ? void 0 : err.message
					}
				]
			});
		}
	}, {
		wait: 500,
		leading: true,
		trailing: false
	});
	useEffect(() => {
		var _store$getState3, _interaction$utils, _interaction$utils2;
		localStorage.removeItem("bookingResourceList");
		_persistentRef.current = storage.get(`drawer-booking`) === "true" ? true : isTerminal();
		if (lowcodeRef) lowcodeRef.onReady(void 0);
		if (action) action({
			type: "pisell1.registerPlugin",
			data: { pluginList: ["ProductDetailPlugin", "BookingPlugin3"] }
		});
		const off = _addVisibilityListener(() => {
			setState({ verticalAddServiceKey: state.verticalAddServiceKey + 1 });
		});
		try {
			getData("is_price_include_tax");
			getData("tax_rate");
			getData("tax_title");
			getData("surcharge_list");
			const schedule_list = getData("schedule_list");
			let scheduleById = {};
			if (Array.isArray(schedule_list)) for (let item of schedule_list) scheduleById[item.id] = item;
		} catch (error) {}
		setState({ amountSymbol: (getData === null || getData === void 0 ? void 0 : getData("shop_symbol")) || (store === null || store === void 0 || (_store$getState3 = store.getState) === null || _store$getState3 === void 0 || (_store$getState3 = _store$getState3.call(store)) === null || _store$getState3 === void 0 || (_store$getState3 = _store$getState3.global) === null || _store$getState3 === void 0 ? void 0 : _store$getState3.symbol) || "$" }, () => {
			_initStateRef.current = JSON.parse(JSON.stringify(state));
			_getBoardConfig();
		});
		_setShopOpeningHours();
		_setIntervalTime(true);
		checkTerminalVersion();
		interaction === null || interaction === void 0 || (_interaction$utils = interaction.utils) === null || _interaction$utils === void 0 || _interaction$utils.mountFunction("bookingTicket", "clearAllCart", (type, orderId) => {
			var _shopDiscount$clear;
			console.log("bookingTicket.clearAllCart");
			_initFn(() => {});
			_setIntervalTime(true);
			selectCustomer(null);
			enableAllScanListeners();
			shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$clear = shopDiscount.clear) === null || _shopDiscount$clear === void 0 || _shopDiscount$clear.call(shopDiscount);
		});
		interaction === null || interaction === void 0 || (_interaction$utils2 = interaction.utils) === null || _interaction$utils2 === void 0 || _interaction$utils2.mountFunction("booking", "voidBooking", (orderId) => {});
		return () => {
			off === null || off === void 0 || off();
			if (_listTimerRef.current) clearInterval(_listTimerRef.current);
		};
	}, []);
	const _getProducts = (date) => {
		var _state$modalState, _state$bookingConfig, _getProductsRef$curre;
		const currentDate = date.format("YYYY-MM-DD");
		const currentDatetime = date.format("YYYY-MM-DD HH:mm:ss");
		const customerId = (_state$modalState = state.modalState) === null || _state$modalState === void 0 || (_state$modalState = _state$modalState.client) === null || _state$modalState === void 0 || (_state$modalState = _state$modalState.value) === null || _state$modalState === void 0 ? void 0 : _state$modalState.id;
		const menuList = ((_state$bookingConfig = state.bookingConfig) === null || _state$bookingConfig === void 0 || (_state$bookingConfig = _state$bookingConfig.config) === null || _state$bookingConfig === void 0 || (_state$bookingConfig = _state$bookingConfig.menu_list_tab) === null || _state$bookingConfig === void 0 ? void 0 : _state$bookingConfig.menu_list) || [];
		getProductsRef === null || getProductsRef === void 0 || (_getProductsRef$curre = getProductsRef.current) === null || _getProductsRef$curre === void 0 || _getProductsRef$curre.call(getProductsRef, {
			schedule_date: currentDate,
			customer_id: customerId,
			menu_list_ids: menuList,
			schedule_datetime: currentDatetime
		});
	};
	const _onDateChange = (date, dateString) => {
		_setIntervalTime(false);
		setState({ isDateChange: true });
		_setDataChange(date, dateString);
		if (getProductsRef.current) _getProducts(date);
	};
	const _setIntervalTime = (isInterval) => {
		clearInterval(_timerRef.current);
		if (isInterval) {
			setState({
				isTimeChange: false,
				isDateChange: false
			});
			if (state.bookingId) _openModal({});
			_setDataChange(dayjs());
			_timerRef.current = setInterval(() => {
				_setDataChange(dayjs());
			}, 1e3 * 60);
		}
		setState({ intervalSetTime: isInterval });
	};
	const getDataFromHost = () => {
		try {
			const is_price_include_tax = getData("is_price_include_tax");
			const tax_rate = getData("tax_rate") || "10";
			const tax_title = getData("tax_title") || "GST";
			const surcharge_list = getData("surcharge_list");
			const schedule_list = getData("schedule_list");
			let scheduleById = {};
			if (Array.isArray(schedule_list)) for (let item of schedule_list) scheduleById[item.id] = item;
			return {
				is_price_include_tax,
				tax_rate,
				tax_title,
				surcharge_list,
				schedule_list,
				scheduleById
			};
		} catch (error) {
			console.error(error);
			return {};
		}
	};
	useEffect(() => {
		var _state$modalState2, _locales$getText, _interaction$utils4, _interaction$utils4$p;
		const cartItems = state === null || state === void 0 || (_state$modalState2 = state.modalState) === null || _state$modalState2 === void 0 || (_state$modalState2 = _state$modalState2.service) === null || _state$modalState2 === void 0 ? void 0 : _state$modalState2.value;
		if (!Array.isArray(cartItems) || cartItems.length === 0) {
			var _interaction$utils3, _interaction$utils3$p;
			interaction === null || interaction === void 0 || (_interaction$utils3 = interaction.utils) === null || _interaction$utils3 === void 0 || (_interaction$utils3$p = _interaction$utils3.postMessageToApp) === null || _interaction$utils3$p === void 0 || _interaction$utils3$p.call(_interaction$utils3, {
				module: "cds",
				key: "cartUpdate",
				data: {
					currency_symbol: getSymbolic(),
					total: "0",
					products: [],
					fees: []
				}
			});
		}
		const total = getSumTotal(state.modalState, _objectSpread2({
			isEdit: true,
			ScheduleModule
		}, getDataFromHost()));
		let formatedProducts = [];
		try {
			formatedProducts = formatProducts(cartItems, state.modalState, false, true, true);
		} catch (error) {
			console.error(error);
		}
		console.log("formatedProducts", total, formatedProducts);
		let fees = [];
		let products = [];
		for (const item of formatedProducts) {
			var _origin$discount_list;
			const { id, name, image, origin_total, total, num, note, _origin } = item;
			_origin === null || _origin === void 0 || (_origin$discount_list = _origin.discount_list) === null || _origin$discount_list === void 0 || _origin$discount_list.forEach((dl) => {
				fees.push({
					isReduce: dl.type === "good_pass",
					title: translation(dl === null || dl === void 0 ? void 0 : dl.discount.title),
					price: dl.amount,
					type: dl.type
				});
			});
			let msg = "";
			try {
				var _engineContext$appHel2;
				msg = formatProductMessage(_objectSpread2(_objectSpread2({}, item), {}, { currency_symbol: getSymbolic() }), (_engineContext$appHel2 = engineContext.appHelper) === null || _engineContext$appHel2 === void 0 ? void 0 : _engineContext$appHel2.utils);
			} catch (error) {
				console.error(error);
			}
			let _item = {
				productID: id,
				title: name,
				cover: image,
				price: total,
				buyCount: num,
				productFormatMessage: msg,
				note
			};
			if (origin_total !== total) _item.modifyPrice = origin_total;
			products.push(_item);
		}
		console.log("formatedProducts", (_locales$getText = locales.getText("pisell2.product.card.cart-items")) === null || _locales$getText === void 0 ? void 0 : _locales$getText(products.length));
		if (products.length > 0) {
			var _locales$getText2;
			fees.unshift({
				title: locales.getText("pisell2.product.card.subtotal"),
				price: total.productAmount,
				type: "subtotal",
				message: (_locales$getText2 = locales.getText("pisell2.product.card.cart-items")) === null || _locales$getText2 === void 0 ? void 0 : _locales$getText2(products.length)
			});
		}
		console.log("start post message, config:", {
			module: "cds",
			key: "cartUpdate",
			data: {
				currency_symbol: getSymbolic(),
				total: total.productAmount,
				products,
				fees
			}
		});
		interaction === null || interaction === void 0 || (_interaction$utils4 = interaction.utils) === null || _interaction$utils4 === void 0 || (_interaction$utils4$p = _interaction$utils4.postMessageToApp) === null || _interaction$utils4$p === void 0 || _interaction$utils4$p.call(_interaction$utils4, {
			module: "cds",
			key: "cartUpdate",
			data: {
				currency_symbol: getSymbolic(),
				total: total.expectAmount,
				products,
				fees
			}
		});
	}, [state === null || state === void 0 || (_state$modalState3 = state.modalState) === null || _state$modalState3 === void 0 || (_state$modalState3 = _state$modalState3.service) === null || _state$modalState3 === void 0 ? void 0 : _state$modalState3.value]);
	/**
	* 设置弹窗内的状态
	*/
	const _setModalState = (props) => {
		var _newVal$service2;
		console.log("同步state到外层", props);
		let newVal = _objectSpread2({}, props);
		if (newVal.service) {
			var _newVal$service;
			newVal.service.value = (newVal === null || newVal === void 0 || (_newVal$service = newVal.service) === null || _newVal$service === void 0 ? void 0 : _newVal$service.value) || [];
		}
		console.log(newVal === null || newVal === void 0 || (_newVal$service2 = newVal.service) === null || _newVal$service2 === void 0 ? void 0 : _newVal$service2.value, "newVal.service.value");
		setState({ modalState: _objectSpread2(_objectSpread2({}, state.modalState), newVal) });
	};
	const _setDataChange = (date, dateString, isTimeChange) => {
		if (state.modalState.disabledEdit) return;
		_setListState({ params: _objectSpread2(_objectSpread2({}, state.list.params), {}, { booking_time_start_between: formatDateToStr([date.startOf(isTimeChange ? "minute" : "day"), date.endOf(isTimeChange ? "minute" : "day")]) }) });
		_setModalState({ date: _objectSpread2(_objectSpread2({}, state.modalState.date), {}, {
			value: date,
			edit: true
		}) });
		if (isTimeChange && getProductsRef.current) _getProducts(date);
		setTimeout(() => {}, 100);
	};
	const _setShopOpeningHours = () => {
		var _getData, _store$getState4;
		let time = (getData === null || getData === void 0 || (_getData = getData("operating_day_boundary")) === null || _getData === void 0 ? void 0 : _getData.time) || (store === null || store === void 0 || (_store$getState4 = store.getState) === null || _store$getState4 === void 0 || (_store$getState4 = _store$getState4.call(store)) === null || _store$getState4 === void 0 || (_store$getState4 = _store$getState4.global) === null || _store$getState4 === void 0 || (_store$getState4 = _store$getState4.shopDetail) === null || _store$getState4 === void 0 || (_store$getState4 = _store$getState4.operating_day_boundary) === null || _store$getState4 === void 0 ? void 0 : _store$getState4.time);
		if (time) localStorage.setItem("shopOpeningHours", time);
	};
	const _getAddTimeProducts = function() {
		var _ref = _asyncToGenerator(function* () {
			const data = yield getServices({
				skip: 1,
				num: 500,
				extension_type: ["product_add_time"]
			});
			setState({ addTimeProducts: (data === null || data === void 0 ? void 0 : data.list) || [] });
		});
		return function _getAddTimeProducts() {
			return _ref.apply(this, arguments);
		};
	}();
	/**
	* 获取board配置
	*/
	const _getBoardConfig = function() {
		var _ref2 = _asyncToGenerator(function* () {
			const { bookingConfigParams } = state;
			let isHasCache = false;
			if (_isFirstLoadBoardConfigRef.current && osKey) {
				const cachedBoardConfig = getBoardConfigCache(osKey);
				if (cachedBoardConfig) {
					var _cachedBoardConfig$co;
					isHasCache = true;
					setState({ bookingConfig: cachedBoardConfig });
					console.log("[BoardConfigCache] 使用缓存数据展示");
					if (cachedBoardConfig === null || cachedBoardConfig === void 0 || (_cachedBoardConfig$co = cachedBoardConfig.config) === null || _cachedBoardConfig$co === void 0 || (_cachedBoardConfig$co = _cachedBoardConfig$co.information_tab) === null || _cachedBoardConfig$co === void 0 || (_cachedBoardConfig$co = _cachedBoardConfig$co.appointment_card) === null || _cachedBoardConfig$co === void 0 ? void 0 : _cachedBoardConfig$co.quick_time) _getAddTimeProducts();
				}
				_isFirstLoadBoardConfigRef.current = false;
			}
			try {
				const data = yield getBookingConfig(_objectSpread2({}, bookingConfigParams));
				if (!isHasCache) setState({ bookingConfig: data });
				if (osKey && data) {
					setBoardConfigCache(osKey, data);
					console.log("[BoardConfigCache] 已更新缓存");
				}
			} catch (error) {
				console.error("[BoardConfigCache] 获取配置失败:", error);
			}
		});
		return function _getBoardConfig() {
			return _ref2.apply(this, arguments);
		};
	}();
	const _addVisibilityListener = (callback) => {
		const handleVisibilityChange = () => {
			if (!document.hidden) callback();
		};
		document.addEventListener("visibilitychange", handleVisibilityChange);
		return () => {
			document.removeEventListener("visibilitychange", handleVisibilityChange);
		};
	};
	const _setListState = (data, cb) => {
		setState({ list: _objectSpread2(_objectSpread2({}, state.list), data) }, () => {
			cb === null || cb === void 0 || cb();
		});
	};
	const _getInitState = (resetProps = {}) => {
		const { modalState } = state;
		let initState = JSON.parse(JSON.stringify(_initStateRef.current || {}));
		let _state = _objectSpread2(_objectSpread2({}, initState), resetProps);
		let _modalState = _objectSpread2({}, modalState);
		for (let key in _modalState) {
			if (key === "notes") {
				_modalState[key].orderNote = initState.modalState[key].orderNote;
				_modalState[key].internalNotes = initState.modalState[key].internalNotes;
			} else if (typeof _modalState[key] === "object") {
				if (key !== "date") {
					var _initState$modalState;
					_modalState[key].value = (_initState$modalState = initState.modalState[key]) === null || _initState$modalState === void 0 ? void 0 : _initState$modalState.value;
				}
			}
			if (typeof _modalState[key] === "object") {
				if (_modalState[key].showModal) _modalState[key].showModal = initState.modalState[key].showModal;
				if (_modalState[key].addModal) _modalState[key].addModal = initState.modalState[key].addModal;
				if (_modalState[key].editModal) _modalState[key].editModal = initState.modalState[key].editModal;
				if (_modalState[key].edit) _modalState[key].edit = false;
				if (_modalState[key].load) _modalState[key].load = initState.modalState[key].load;
			}
		}
		_modalState.service.value = [];
		_modalState.service.cacheItem = null;
		_modalState.service.addTimeModal = false;
		_modalState.service.changeService = false;
		_modalState.disabledEdit = initState.modalState.disabledEdit;
		_modalState.channelDisabledEdit = initState.modalState.channelDisabledEdit;
		_modalState.appointment_status = initState.modalState.appointment_status;
		_state.modalState = _modalState;
		return _state;
	};
	const _getBookingType = (record) => {
		const { type } = state;
		if (record.parent_id > 0 && record.item_type !== "recurring_booking" && !type) return "pisell2";
		return "pisell1";
	};
	const _scrollToBooking = (bookingId) => {
		if (bookingId || state.bookingId) {
			var _dom$scrollIntoView;
			const dom = document.getElementById(bookingId || state.bookingId);
			dom === null || dom === void 0 || (_dom$scrollIntoView = dom.scrollIntoView) === null || _dom$scrollIntoView === void 0 || _dom$scrollIntoView.call(dom, {
				block: "center",
				behavior: "smooth"
			});
		}
	};
	/**
	* 初始化预约数据
	*
	*/
	const _initBookingData = (type, data) => {
		let initState = _getInitState({
			bookingDetail: null,
			bookingConfig: state.bookingConfig,
			renderType: state.renderType,
			isShowDeposit: state.isShowDeposit,
			openRebook: state.openRebook,
			disableEventBookingEdit: state.disableEventBookingEdit,
			isShowInfo: state.isShowInfo,
			persistent: state.persistent,
			list: state.list,
			intervalSetTime: state.intervalSetTime,
			createCount: state.createCount,
			bookingFunctions: state.bookingFunctions,
			isParallelResourcesBooking: state.isParallelResourcesBooking
		});
		if (type === "edit") {
			initState.bookingDetail = data;
			initState.modalState = _formatBookingDetail(data, state.modalState);
		}
		if (type === "create") {
			var _data$serviceParams, _data$params;
			if (data === null || data === void 0 || (_data$serviceParams = data.serviceParams) === null || _data$serviceParams === void 0 ? void 0 : _data$serviceParams.start_date) {
				var _data$serviceParams2;
				initState.modalState.date.value = dayjs(data === null || data === void 0 || (_data$serviceParams2 = data.serviceParams) === null || _data$serviceParams2 === void 0 ? void 0 : _data$serviceParams2.start_date);
				sessionStorage.setItem("pisell2.booking.serviceParams", JSON.stringify(data));
			} else {
				var _store$getState5;
				let timezone = store === null || store === void 0 || (_store$getState5 = store.getState) === null || _store$getState5 === void 0 || (_store$getState5 = _store$getState5.call(store)) === null || _store$getState5 === void 0 || (_store$getState5 = _store$getState5.global) === null || _store$getState5 === void 0 || (_store$getState5 = _store$getState5.globalConfig) === null || _store$getState5 === void 0 ? void 0 : _store$getState5.timezone;
				initState.modalState.date.value = dayjs.tz(/* @__PURE__ */ new Date(), timezone);
				sessionStorage.removeItem("pisell2.booking.serviceParams");
			}
			if (data === null || data === void 0 || (_data$params = data.params) === null || _data$params === void 0 ? void 0 : _data$params.customer) initState.modalState.client.value = data === null || data === void 0 ? void 0 : data.params.customer;
			if (data === null || data === void 0 ? void 0 : data.eventBookingServiceParams) {}
		}
		console.log(initState, "initState");
		setState(_objectSpread2(_objectSpread2({}, initState), {}, {
			[state.renderType === "eventBooking" ? "eventOpen" : "open"]: true,
			bookingId: state.bookingId
		}));
	};
	const _rebook = useMemoizedFn(() => {
		var _state$bookingConfig2;
		let date = getNextTimeSlice(((_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.value) || 10);
		setState({ rebookState: _objectSpread2(_objectSpread2({}, state.rebookState), {}, {
			open: true,
			date
		}) });
	});
	/**
	* 获取预约详情
	*
	*/
	const _getBookingDetail = function() {
		var _ref3 = _asyncToGenerator(function* (bookingId) {
			const { renderType, openRebook } = state;
			setState({ loading: true });
			let data = yield (renderType === "eventBooking" ? getEventBookingDetail : getBookingDetail)(bookingId || state.bookingId, {});
			if (renderType === "eventBooking") data = _objectSpread2(_objectSpread2({}, data), {}, { bookings: _objectSpread2(_objectSpread2({}, data.bookings), {}, { list: [data.bookings] }) });
			console.log("getBookingDetail", data);
			_initBookingData("edit", data);
			if (openRebook) setTimeout(() => {
				_rebook();
			});
		});
		return function _getBookingDetail(_x) {
			return _ref3.apply(this, arguments);
		};
	}();
	/**
	* 打开模态框
	*
	*/
	const _openModal = (props) => {
		const { bookingId, serviceParams, params, eventBookingServiceParams, renderType = "booking", openRebook, isParallelResourcesBooking = true } = props || {};
		setState({ isShowInfo: false });
		const _isTerminal = isTerminal();
		const defaultInit = () => {
			if (renderType === "eventBooking") _getBoardConfig();
			if (bookingId) _getBookingDetail(bookingId);
			else _initBookingData("create", {
				serviceParams,
				params,
				eventBookingServiceParams
			});
		};
		const isOpen = state.open;
		setState({
			[renderType === "eventBooking" ? "eventOpen" : "open"]: true,
			bookingId: bookingId || 0,
			renderType,
			openRebook,
			isParallelResourcesBooking,
			disableEventBookingEdit: eventBookingServiceParams === null || eventBookingServiceParams === void 0 ? void 0 : eventBookingServiceParams.disableEventBookingEdit,
			modalState: _objectSpread2(_objectSpread2({}, state.modalState), {}, { eventOtherParams: eventBookingServiceParams }),
			isShowInfo: !_isTerminal,
			persistent: storage.get(`drawer-booking`) === "true" ? true : _isTerminal
		}, () => {
			console.log(isOpen, "isOpen");
			if (isOpen) setTimeout(() => {
				setState({ isShowInfo: true });
			});
			defaultInit();
		});
	};
	(function() {
		var _ref4 = _asyncToGenerator(function* (detail) {
			var _Toast$loading;
			Toast === null || Toast === void 0 || (_Toast$loading = Toast.loading) === null || _Toast$loading === void 0 || _Toast$loading.call(Toast, locales.getText("pisell2.ticket-booking.loading"), 6e4);
			let result = {};
			try {
				result = JSON.parse(detail) || {};
			} catch (err) {}
			if (!(result === null || result === void 0 ? void 0 : result.value)) {
				message === null || message === void 0 || message.error(locales.getText("pisell2.ticket-booking.appointment-not-found"));
				Toast === null || Toast === void 0 || Toast.hide();
				return;
			}
			const objDetail = yield getOrderInfoByCode({ code: result.value });
			Toast === null || Toast === void 0 || Toast.hide();
			if (!(objDetail === null || objDetail === void 0 ? void 0 : objDetail.order_id) || (objDetail === null || objDetail === void 0 ? void 0 : objDetail.event_id) === 0) {
				message === null || message === void 0 || message.error(locales.getText("pisell2.ticket-booking.appointment-not-found"));
				return;
			}
			if (_getBookingType(objDetail) === "pisell1") {
				setState({ confirmOpen: true });
				return;
			}
			_scrollToBooking(objDetail.order_id);
			_openModal({
				bookingId: objDetail.order_id,
				id: objDetail.event_id
			});
		});
		return function _scanBookingDetailResult(_x2) {
			return _ref4.apply(this, arguments);
		};
	})();
	/**
	* 执行动作, 触发2.0页面外部的动作
	*
	* @param props 动作属性
	*/
	const _onAction = useMemoizedFn((props) => {
		if (props === "init") {
			_getBookingDetail(state.bookingId);
			return;
		}
		action === null || action === void 0 || action(props);
	});
	const _setActiveTab = (key) => {};
	const _initFn = (callback, open) => {
		setState(_objectSpread2(_objectSpread2({}, _getInitState({
			bookingDetail: null,
			bookingConfig: state.bookingConfig,
			renderType: state.renderType,
			isShowDeposit: state.isShowDeposit,
			disableEventBookingEdit: state.disableEventBookingEdit,
			list: state.list,
			createCount: state.createCount,
			bookingFunctions: state.bookingFunctions,
			isParallelResourcesBooking: state.isParallelResourcesBooking
		})), {}, {
			shop_discount: "0",
			loading: false,
			open: open !== null && open !== void 0 ? open : false,
			eventOpen: false,
			isShowInfo: false,
			bookingId: 0
		}), () => {
			callback === null || callback === void 0 || callback();
		});
	};
	const _callback = useMemoizedFn((data, type) => {
		var _shopDiscount$clear2, _pisellFloatingPanelR;
		if (isTerminal() && type === "checkout") return;
		shopDiscount === null || shopDiscount === void 0 || (_shopDiscount$clear2 = shopDiscount.clear) === null || _shopDiscount$clear2 === void 0 || _shopDiscount$clear2.call(shopDiscount);
		if (data === null || data === void 0 ? void 0 : data.afterCloseUpdate) return _callbackFnRef.current = () => {
			lowcodeRef === null || lowcodeRef === void 0 || lowcodeRef.onChange(_objectSpread2({ type: "refresh" }, data));
		};
		const { bookingId, renderType } = state;
		let cb;
		if (bookingId && renderType !== "eventBooking") cb = () => {
			_openModal({ bookingId });
		};
		if (!bookingId) _setIntervalTime(true);
		if ((_pisellFloatingPanelR = pisellFloatingPanelRef.current) === null || _pisellFloatingPanelR === void 0 ? void 0 : _pisellFloatingPanelR.getIsOpen()) {
			var _pisellFloatingPanelR2;
			(_pisellFloatingPanelR2 = pisellFloatingPanelRef.current) === null || _pisellFloatingPanelR2 === void 0 || _pisellFloatingPanelR2.refresh();
		}
		_initFn(cb);
	});
	const _refreshData = useMemoizedFn(() => {
		if (lowcodeRef) lowcodeRef.onChange({ type: "refresh" });
	});
	const _clearAllValue = useMemoizedFn(() => {
		setState({ modalState: _getInitState().modalState });
	});
	const currentDate = useMemo(() => {
		var _state$modalState4;
		return (_state$modalState4 = state.modalState) === null || _state$modalState4 === void 0 || (_state$modalState4 = _state$modalState4.date) === null || _state$modalState4 === void 0 || (_state$modalState4 = _state$modalState4.value) === null || _state$modalState4 === void 0 ? void 0 : _state$modalState4.format("YYYY-MM-DD");
	}, [(_state$modalState5 = state.modalState) === null || _state$modalState5 === void 0 || (_state$modalState5 = _state$modalState5.date) === null || _state$modalState5 === void 0 ? void 0 : _state$modalState5.value]);
	const floatButtons = useMemo(() => {
		return [{
			icon: /* @__PURE__ */ React.createElement(Iconfont, { type: "pisell2-person" }),
			key: "dashboard",
			onClick: () => {
				var _pisellFloatingPanelR3;
				(_pisellFloatingPanelR3 = pisellFloatingPanelRef.current) === null || _pisellFloatingPanelR3 === void 0 || _pisellFloatingPanelR3.open();
			}
		}];
	}, []);
	const onMaskClick = useMemoizedFn(() => {
		setActiveBookingId(0);
	});
	const handleCreateClick = useMemoizedFn(() => {
		var _pisellFloatingPanelR4;
		onMaskClick();
		(_pisellFloatingPanelR4 = pisellFloatingPanelRef.current) === null || _pisellFloatingPanelR4 === void 0 || _pisellFloatingPanelR4.close();
	});
	const handleBookingClick = useMemoizedFn((booking) => {
		if (activeBookingId) {
			var _closeRef$current;
			onMaskClick();
			(_closeRef$current = closeRef.current) === null || _closeRef$current === void 0 || _closeRef$current.call(closeRef, "pisell2");
		} else {
			var _booking$order, _booking$order2;
			setTimeout(() => {
				setActiveBookingId(booking.order.id);
			});
			const time = /* @__PURE__ */ new Date();
			closeRef.current = action({
				type: "pisell1.bookingDetail",
				data: {
					component_type: getBookingType(booking),
					booking_id: booking.order.id,
					type: booking.parent_id === 0 ? "list" : "detail",
					id: booking.id,
					isParallelResourcesBooking: getIsParallelResourcesBooking(booking),
					preliminaryBookingDetail: {
						customer: booking === null || booking === void 0 || (_booking$order = booking.order) === null || _booking$order === void 0 ? void 0 : _booking$order.customer,
						id: booking.order.id,
						order_sales_channel: booking === null || booking === void 0 || (_booking$order2 = booking.order) === null || _booking$order2 === void 0 ? void 0 : _booking$order2.order_sales_channel,
						bookings: {
							booking_id: booking === null || booking === void 0 ? void 0 : booking.booking_id,
							appointment_status: booking === null || booking === void 0 ? void 0 : booking.appointment_status,
							list: [{
								start_date: booking === null || booking === void 0 ? void 0 : booking.start_date,
								start_time: booking === null || booking === void 0 ? void 0 : booking.start_time
							}]
						}
					}
				},
				callback: (params) => {
					if ((/* @__PURE__ */ new Date()).getTime() - time.getTime() < 500) return;
					if (params.type === "close") {
						_clearAllValue();
						onMaskClick();
					}
					if (params.type === "refresh") {
						var _pisellFloatingPanelR5;
						(_pisellFloatingPanelR5 = pisellFloatingPanelRef.current) === null || _pisellFloatingPanelR5 === void 0 || _pisellFloatingPanelR5.refresh();
					}
				}
			});
		}
	});
	const memoGlobalState = useMemo(() => {
		return _objectSpread2(_objectSpread2({}, state.modalState), {}, {
			hideCreateText: true,
			amountSymbol: state.amountSymbol,
			bookingConfig: state.bookingConfig,
			bookingDetail: state.bookingDetail,
			bookingId: state.bookingId,
			bookingStatus: state.bookingStatus,
			apis: serve_exports,
			modalOpen: state.open,
			onRebook: _rebook,
			addTimeProducts: state.addTimeProducts,
			isBookingCreatePage: true,
			closeAutoOpenService: true,
			renderType: "booking",
			action: _onAction,
			callback: _callback,
			locale: engineProps.locale,
			refreshData: _refreshData,
			setActiveTab: _setActiveTab,
			clearAllValue: _clearAllValue,
			drawerMask: true,
			isBookingTicket2: true,
			isParallelResourcesBooking: state.isParallelResourcesBooking,
			setIntervalTime: _setIntervalTime,
			onQrCodeClick: () => {
				console.log("onQrCodeClick");
				bookingTicket === null || bookingTicket === void 0 || bookingTicket.activateCamera();
			}
		});
	}, [
		state.modalState,
		state.amountSymbol,
		state.bookingConfig,
		state.bookingDetail,
		state.bookingId,
		serve_exports,
		state.open,
		state.bookingStatus,
		state.addTimeProducts,
		state.isParallelResourcesBooking,
		engineProps.locale
	]);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { className: "ticket-booking-left-panel" }, /* @__PURE__ */ React.createElement("div", { className: "ticket-booking-left-panel-content" }, /* @__PURE__ */ React.createElement(AddServiceVariant, {
		onPrerenderComplete,
		globalState: _objectSpread2(_objectSpread2({}, state.modalState), {}, {
			amountSymbol: state.amountSymbol,
			bookingConfig: state.bookingConfig,
			bookingDetail: state.bookingDetail,
			bookingId: state.bookingId,
			bookingStatus: state.bookingStatus,
			apis: serve_exports,
			action: _onAction,
			callback: _callback,
			locale: engineProps.locale,
			modalOpen: state.open,
			onRebook: _rebook,
			refreshData: _refreshData,
			setActiveTab: _setActiveTab,
			addTimeProducts: state.addTimeProducts,
			isBookingCreatePage: true,
			closeAutoOpenService: true,
			productExtensionType: state.productExtensionType,
			isBookingTicket2: true
		}),
		setGlobalState: _setModalState,
		onGetProductsReady: handleGetProductsReady,
		productDisplayConfig
	}), isShowFloatButtons && /* @__PURE__ */ React.createElement(FloatButtons, { items: floatButtons })), isShowTimeBar && /* @__PURE__ */ React.createElement(TimeBar, {
		setNowTime: _getProducts,
		onCreateClick: handleCreateClick,
		setGlobalState: setState,
		globalState: state,
		onDateChange: (...args) => {
			_onDateChange(...args);
		},
		onDateTimeChange: (...args) => {
			_setDataChange(...args, true);
		},
		setIntervalTime: _setIntervalTime,
		locale: engineProps.locale
	})), /* @__PURE__ */ React.createElement("div", { style: {
		flexShrink: 0,
		width: 400
	} }, /* @__PURE__ */ React.createElement(APP, {
		key: state.createCount,
		globalState: memoGlobalState,
		setGlobalState: _setModalState,
		setState,
		modules: {
			client: 1,
			date: 0,
			service: 1,
			holder: 1,
			note: 1
		}
	})), /* @__PURE__ */ React.createElement(pisellFloatingPanel_default, {
		bookingId: activeBookingId,
		ref: pisellFloatingPanelRef,
		currentDate,
		onBookingClick: handleBookingClick
	}), /* @__PURE__ */ React.createElement(PisellModal.Information, {
		open: showTerminalUpgradeModal,
		title: locales.getText("pisell2.ticket-booking.terminal-upgrade-title"),
		describe: locales.getText("pisell2.ticket-booking.terminal-upgrade-description"),
		okText: locales.getText("pisell2.ticket-booking.terminal-upgrade-ok"),
		cancelText: locales.getText("pisell2.ticket-booking.terminal-upgrade-cancel"),
		closable: true,
		onOk: () => setShowTerminalUpgradeModal(false),
		onCancel: () => setShowTerminalUpgradeModal(false)
	}));
};
//#endregion
export { _formatBookingDetail, TicketBooking as default };
