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 { getResourceTimeIsUsable } from "../../utilsByBooking.js";
import { flexibleObj, getDiscountTime, getNowTime, isNowTime, isWalkIn } from "../../../utils.js";
import { addTimeRowKey, getAddTimeSplits, isUsableProduct } from "./utils.js";
import { isBooking4Shop } from "../../../info/utils.js";
import { Context } from "../../../info/model.js";
import useEngineContext from "../../../../../hooks/useEngineContext.js";
import CompensatedPisellContainer from "../../../../../pro/compensatedPisellContainer/index.js";
import withResponsive from "../../../../../responsive/withResponsive.js";
import BrowserSelect from "../../../components/browserSelect/index.js";
import footer_default from "../../../components/footer/index.js";
import { getAddTimeProducts, saveAddTimeProduct, saveAddTimeProduct2 } from "./serve.js";
import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import { Alert, Button, Skeleton, message } from "antd";
import { createArray, formatAmount, formatDate, locales } from "@pisell/utils";
import classNames from "classnames";
import ArrowLeft from "@pisell/icon/es/ArrowLeft";
import "../../../components/drawer/index.less";
import { useDebounceFn, useUpdateEffect } from "ahooks";
import "../../../info/service/addTimeModal/index.less";
//#region src/components/booking/info2/service/addTimeModal/index.tsx
const numberList = createArray(100, (d, i) => {
	return {
		label: i + 1,
		value: i + 1
	};
});
const AddTimeModal = (props) => {
	var _context$appHelper, _state$bookingConfig2, _state$service, _currentTimeItem$stat, _currentProduct$add_t;
	const { variant } = props;
	const { state, dispatch } = useContext(Context);
	const [isEdit, setIsEdit] = useState(false);
	const loadingRef = useRef(false);
	const [loading, setLoading] = useState("");
	const [recordKey, setRecordKey] = useState("");
	const [number, setNumber] = useState(1);
	const originServices = useRef([]);
	const [renderList, setRenderList] = useState([]);
	const context = useEngineContext();
	const { interaction, isWebPos } = (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils;
	const isPhoneVariant = variant === "phone";
	const statusMap = {
		available: {
			label: locales.getText("page.booking.text.available"),
			color: "#079455"
		},
		fully_booked: {
			label: locales.getText("page.booking.text.fully-booked"),
			color: "#DC6803"
		},
		unavailable: {
			label: locales.getText("page.booking.text.unavailable"),
			color: "#98A2B3"
		}
	};
	const updateServices = useDebounceFn(() => {
		createNewServices();
	}, { wait: 200 });
	const transaction_habit_selection = 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 = useMemo(() => {
		return addTimeRowKey.getValue(recordKey).product_id;
	}, [recordKey]);
	const currentTime = useMemo(() => {
		return addTimeRowKey.getValue(recordKey).time || "";
	}, [recordKey]);
	const currentProduct = useMemo(() => {
		return (renderList || []).find((d) => d.id == currentProductId);
	}, [renderList, currentProductId]);
	const currentTimeItem = 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 = useMemo(() => {
		var _state$service$cacheI;
		const resource = (_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.resource;
		let arr = [];
		for (let form_id in resource) arr = [...arr, ...resource[form_id].map((d) => {
			var _state$service$cacheI2;
			return (_state$service$cacheI2 = state.service.cacheItem) === null || _state$service$cacheI2 === void 0 || (_state$service$cacheI2 = _state$service$cacheI2._data) === null || _state$service$cacheI2 === void 0 || (_state$service$cacheI2 = _state$service$cacheI2.resourceMaps) === null || _state$service$cacheI2 === void 0 || (_state$service$cacheI2 = _state$service$cacheI2[form_id]) === null || _state$service$cacheI2 === void 0 || (_state$service$cacheI2 = _state$service$cacheI2.renderListMaps) === null || _state$service$cacheI2 === void 0 ? void 0 : _state$service$cacheI2[d.relation_id];
		})];
		return arr.filter(Boolean);
	}, [(_state$service = state.service) === null || _state$service === void 0 || (_state$service = _state$service.cacheItem) === null || _state$service === void 0 || (_state$service = _state$service._extend) === null || _state$service === void 0 ? void 0 : _state$service.resource]);
	console.log(currentResource, "currentResource");
	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.length) return { status: statusMap.unavailable };
		try {
			let _extend = _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 = flexibleObj.add(_extend.duration, time);
			if (isNowTime(_extend.start_time)) _extend.start_time = getNowTime();
			_extend.startDate.format("hh:mm A");
			let endText = _extend.endDate.format("hh:mm A");
			if (_extend.endDate.isAfter(_extend.startDate, "day")) endText = locales.getText("pisell1.text.tomorrow") + endText;
			let errorList = [];
			for (let resourceItem of currentResource) {
				var _res$_extend;
				if (!((_res$_extend = getResourceTimeIsUsable(resourceItem === null || resourceItem === void 0 ? void 0 : resourceItem.times.find((_time) => _time.item_id === resourceItem.id), _objectSpread2(_objectSpread2({}, state.service.cacheItem), {}, { _extend: _objectSpread2(_objectSpread2({}, state.service.cacheItem._extend), _extend) }), resourceItem)._extend) === null || _res$_extend === void 0 ? void 0 : _res$_extend.isUsable)) errorList.push(resourceItem);
			}
			if (errorList.length) return {
				status: statusMap.unavailable,
				message: `${errorList.map((d) => d.labelText).join(", ")} ${locales.getText("pisell2.text.status.service-error-2")}`
			};
		} catch (err) {}
		return { status: statusMap.available };
	};
	const _getAddTimeProducts = function() {
		var _ref = _asyncToGenerator(function* () {
			var _state$client, _state$client2;
			const data = yield getAddTimeProducts({
				skip: 1,
				num: 500,
				open_quotation: 1,
				schedule_date: state.date.value.format("YYYY-MM-DD"),
				customer_id: 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,
				retry: {
					count: 3,
					delay: 500
				}
			});
			return (data === null || data === void 0 ? void 0 : data.list) || [];
		});
		return function _getAddTimeProducts() {
			return _ref.apply(this, arguments);
		};
	}();
	const getTimeProducts = function() {
		var _ref2 = _asyncToGenerator(function* () {
			setLoading("list");
			let list = (yield _getAddTimeProducts()).map((d) => {
				let isUsable = isUsableProduct(d.add_time, state.service.cacheItem);
				return _objectSpread2(_objectSpread2({}, d), {}, {
					usable: isUsable,
					times: isUsable ? getAddTimeSplits(d, state.service.cacheItem).map((time) => {
						return _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(addTimeRowKey.create(productId, time));
			updateServices.run();
		} catch (err) {}
	};
	useUpdateEffect(() => {
		if (state.service.addTimeModal) {
			getTimeProducts();
			loadingRef.current = false;
			originServices.current = state.service;
		} else updateServices.run();
	}, [state.service.addTimeModal]);
	const onSelectItem = (pItem, item) => {
		setRecordKey(addTimeRowKey.create(pItem.id, item.value));
		setIsEdit(true);
		updateServices.run();
	};
	const newService = 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 = _objectSpread2({}, state.service.cacheItem._extend);
		let relation_products = [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 = flexibleObj.add(_extend.duration, relation_product.product_add_schedule_time);
		if (isNowTime(_extend.start_time)) start_time = 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,
			resources: _extend.event_resources,
			metadata: _extend.metadata
		};
	}, [
		currentTime,
		state.service.cacheItem,
		currentProduct,
		number,
		currentTimeItem
	]);
	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 = () => {
		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 = _objectSpread2({}, d);
				if (_item._extend.id === (newService === null || newService === void 0 ? void 0 : newService.id)) _item = _objectSpread2(_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 = _asyncToGenerator(function* () {
			if (isWebPos) {
				state === null || state === void 0 || state.action("init");
				state === null || state === void 0 || state.callback({}, "save");
				state.action({
					type: "pisell1.handleOpenPayment",
					data: { order: { id: state.bookingId } },
					callback: (res) => {
						var _res$data;
						if (res === null || res === void 0 || (_res$data = res.data) === null || _res$data === void 0 ? void 0 : _res$data.isCallbackFromToast) return;
						state === null || state === void 0 || state.callback({}, "save");
					}
				});
				return;
			}
			/** 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 }
				});
			}
			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 = _asyncToGenerator(function* () {
			if (isEdit) yield handleSave("checkout");
			goCheckout();
		});
		return function handleCheckout() {
			return _ref4.apply(this, arguments);
		};
	}();
	const handleSave = function() {
		var _ref5 = _asyncToGenerator(function* (loadingType = "save") {
			var _context$appHelper2, _context$appHelper2$g, _context$appHelper$ut, _context$appHelper$ut2, _context$appHelper$ut3;
			if (currentTime === null) return;
			if (loadingRef.current) return;
			loadingRef.current = true;
			setLoading(loadingType);
			const api = isBooking4Shop(((_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 || (_context$appHelper2 = _context$appHelper2.utils) === null || _context$appHelper2 === void 0 || (_context$appHelper2$g = _context$appHelper2.getData) === null || _context$appHelper2$g === void 0 ? void 0 : _context$appHelper2$g.call(_context$appHelper2, "shop_id")) || ((_context$appHelper$ut = context.appHelper.utils.store) === null || _context$appHelper$ut === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut.getState) === null || _context$appHelper$ut2 === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut2.call(_context$appHelper$ut)) === null || _context$appHelper$ut2 === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut2.global) === null || _context$appHelper$ut2 === void 0 || (_context$appHelper$ut2 = _context$appHelper$ut2.globalConfig) === null || _context$appHelper$ut2 === void 0 ? void 0 : _context$appHelper$ut2.id), state.renderType, (_context$appHelper$ut3 = context.appHelper.utils) === null || _context$appHelper$ut3 === void 0 ? void 0 : _context$appHelper$ut3.businessUtils) ? saveAddTimeProduct2 : saveAddTimeProduct;
			try {
				yield api({
					orderId: state.bookingId,
					params: _objectSpread2(_objectSpread2({}, newService), {}, { _extend: void 0 })
				});
				loadingRef.current = false;
			} catch (err) {
				loadingRef.current = false;
			}
			setLoading("");
			message.success(locales.getText("page.booking.text.add-time-success"));
			onCancel();
			if (loadingType === "checkout") return;
			state === null || state === void 0 || state.action("init");
			state === null || state === void 0 || state.callback({}, "save");
		});
		return function handleSave() {
			return _ref5.apply(this, arguments);
		};
	}();
	useEffect(() => {
		if (!state.modalOpen && !state.isEditTicketMode) onCancel();
	}, [state.modalOpen, state.isEditTicketMode]);
	const onCancel = () => {
		setIsEdit(false);
		setRecordKey("");
		resetService();
		setTimeout(() => {
			dispatch({
				type: "setService",
				payload: { addTimeModal: false }
			});
		}, 50);
	};
	const updateTime = useMemo(() => {
		if (!newService) return "";
		let startTime = newService.start_time;
		let endTime = newService.end_time;
		let hours = getDiscountTime(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 = formatDate(`${newService.start_date} ${newService.start_time}`, format);
			endTime = formatDate(`${newService.end_date} ${newService.end_time}`, format);
		}
		return `${locales.getText("page.booking.text.update-time")}: ${startTime} ~ ${endTime} (${hours})`;
	}, [newService, state.locale]);
	return /* @__PURE__ */ React.createElement(CompensatedPisellContainer, {
		renderType: "drawer",
		props: {
			open: state.service.addTimeModal,
			placement: isPhoneVariant ? "bottom" : "right",
			width: isPhoneVariant ? "100%" : "600px",
			height: isPhoneVariant ? "95vh" : void 0,
			rootClassName: "booking-server-wrap",
			className: "pisell-lowcode__booking-drawer",
			onClose: onCancel,
			closable: false,
			title: false,
			push: false,
			mask: false,
			bodyStyle: {
				padding: 0,
				position: "relative"
			},
			footerStyle: { padding: "10px 32px 20px" },
			footer: /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.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.createElement(Alert, {
				message: currentTimeItem.status.message,
				type: "warning",
				showIcon: true,
				style: { marginBottom: 12 }
			}) : null, newService ? /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-add-time-summary-wrap" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-add-time-summary" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-add-time-summary-time" }, updateTime), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-add-time-summary-total" }, locales.getText("pisell1.text.subtotal"), ":", " ", formatAmount((currentTimeItem.price || 0) * number, 2, state.amountSymbol))), (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.createElement("div", { className: "pisell-lowcode__booking-add-time-quantity-wrap" }, /* @__PURE__ */ React.createElement("span", { className: "pisell-lowcode__booking-add-time-quantity" }, locales.getText("page.booking.text.quantity")), " ", /* @__PURE__ */ React.createElement(BrowserSelect, {
				value: number,
				onChange: (e) => {
					setNumber(Number(e.target.value));
					updateServices.run();
				},
				className: "pisell-lowcode__booking-add-time-quantity-select",
				options: numberList
			}))) : null), /* @__PURE__ */ React.createElement(footer_default, {
				state,
				dispatch,
				source: "addTime",
				buttons: [/* @__PURE__ */ React.createElement(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"
				}, locales.getText("pisell2.text.checkout")), /* @__PURE__ */ React.createElement(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");
					}
				}, locales.getText("pisell2.text.save"))]
			}))
		}
	}, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-drawer-title-wrap" }, /* @__PURE__ */ React.createElement("div", {
		className: "pisell-lowcode__booking-drawer-title-line",
		onClick: onCancel
	}, /* @__PURE__ */ React.createElement("span", { className: "pisell-lowcode__booking-drawer-back" }, /* @__PURE__ */ React.createElement(ArrowLeft, null)), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-drawer-title pisell-lowcode__booking-drawer-title-no-wrap" }, locales.getText("page.booking.text.add-time")))), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-add-time-body" }, /* @__PURE__ */ React.createElement(Skeleton, {
		loading: loading === "list",
		active: true,
		round: true
	}, /* @__PURE__ */ React.createElement("div", { className: "" }, renderList.map((d) => {
		return /* @__PURE__ */ React.createElement("div", { className: "" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-add-time-hours" }, d.title), d.times ? /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-add-time-child-card-list" }, d.times.map((child) => {
			var _child$status, _child$status2;
			return /* @__PURE__ */ React.createElement("div", {
				className: classNames("pisell-lowcode__booking-add-time-child-card", { "pisell-lowcode__booking-add-time-child-card-active": recordKey === addTimeRowKey.create(d.id, child.value) }),
				onClick: () => {
					if (!child.value) return;
					onSelectItem(d, child);
				}
			}, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-add-time-child-card-left" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-add-time-child-card-left-time" }, child.label), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-add-time-child-card-left-price" }, formatAmount(child.price, 2, state.amountSymbol))), /* @__PURE__ */ React.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.createElement("div", { className: "" })));
};
AddTimeModal.displayName = "AddTimeModal";
var addTimeModal_default = React.memo(withResponsive(AddTimeModal));
//#endregion
export { addTimeModal_default as default };
