import { _asyncToGenerator } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { useVenueBookingSymbol } from "../../hooks.js";
import { useVenueBookingContext } from "../../context.js";
import dayjs from "dayjs";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Form } from "antd";
import { locales } from "@pisell/utils";
//#region src/components/venueBooking/components/Checkout/index.tsx
/**
* venueBooking 结算步骤（Step 3）
* 展示预订明细、客户信息表单、到场须知、金额汇总
* 金额从 viewModel.summary（OS 模块）读取，购物车条目从 viewModel.cartItems 读取
*/
function Checkout() {
	useVenueBookingSymbol();
	const { viewModel, goToStep, updateOrderNote, runModuleAction } = useVenueBookingContext();
	const [contactForm] = Form.useForm();
	const [noteValue, setNoteValue] = useState(String(viewModel.note || ""));
	const lastContactsSignatureRef = useRef("[]");
	const lastNoteRef = useRef(String(viewModel.note || ""));
	useMemo(() => {
		var _viewModel$summary$pr, _viewModel$summary;
		return Number((_viewModel$summary$pr = (_viewModel$summary = viewModel.summary) === null || _viewModel$summary === void 0 ? void 0 : _viewModel$summary.product_amount) !== null && _viewModel$summary$pr !== void 0 ? _viewModel$summary$pr : 0);
	}, [viewModel.summary]);
	useMemo(() => {
		var _ref, _viewModel$summary$to, _viewModel$summary2, _viewModel$summary3;
		return Number((_ref = (_viewModel$summary$to = (_viewModel$summary2 = viewModel.summary) === null || _viewModel$summary2 === void 0 ? void 0 : _viewModel$summary2.total_amount) !== null && _viewModel$summary$to !== void 0 ? _viewModel$summary$to : (_viewModel$summary3 = viewModel.summary) === null || _viewModel$summary3 === void 0 ? void 0 : _viewModel$summary3.expect_amount) !== null && _ref !== void 0 ? _ref : 0);
	}, [viewModel.summary]);
	const venueCartItems = useMemo(() => {
		return (viewModel.cartItems || []).filter((item) => Boolean((item === null || item === void 0 ? void 0 : item.start_date) && (item === null || item === void 0 ? void 0 : item.end_date)));
	}, [viewModel.cartItems]);
	const addonCartItems = useMemo(() => {
		return (viewModel.cartItems || []).filter((item) => !(item === null || item === void 0 ? void 0 : item.start_date) || !(item === null || item === void 0 ? void 0 : item.end_date));
	}, [viewModel.cartItems]);
	useMemo(() => {
		return addonCartItems.reduce((sum, item) => sum + getItemLineTotal(item), 0);
	}, [addonCartItems]);
	const mergedCourtSessionLines = useMemo(() => {
		return venueCartItems.map((item, index) => {
			const resourceName = getVenueResourceName(item);
			const sessionText = getSessionDisplayText(item);
			return `${String(resourceName || `场地 ${index + 1}`)} ${sessionText}`;
		});
	}, [venueCartItems]);
	useMemo(() => ({
		first_name: {
			visible: true,
			required: false
		},
		last_name: {
			visible: true,
			required: false
		},
		phone: {
			visible: true,
			required: false
		},
		email: {
			visible: false,
			required: false
		}
	}), []);
	const syncContactsInfo = useCallback(_asyncToGenerator(function* () {
		const nextContactsInfo = toContactsInfoPayload(contactForm.getFieldsValue());
		const nextSignature = JSON.stringify(nextContactsInfo);
		if (nextSignature === lastContactsSignatureRef.current) return;
		lastContactsSignatureRef.current = nextSignature;
		yield runModuleAction("updateTempOrderContactsInfo", nextContactsInfo);
	}), [contactForm, runModuleAction]);
	useCallback(() => {
		syncContactsInfo();
	}, [syncContactsInfo]);
	const handleNoteBlur = useCallback(_asyncToGenerator(function* () {
		if (noteValue === lastNoteRef.current) return;
		lastNoteRef.current = noteValue;
		yield updateOrderNote(noteValue);
	}), [noteValue, updateOrderNote]);
	useEffect(() => {
		const formValues = toContactFormValues(viewModel.contactsInfo);
		contactForm.setFieldsValue(formValues);
		lastContactsSignatureRef.current = JSON.stringify(toContactsInfoPayload(formValues));
	}, [contactForm, viewModel.contactsInfo]);
	useEffect(() => {
		const nextNote = String(viewModel.note || "");
		setNoteValue(nextNote);
		lastNoteRef.current = nextNote;
	}, [viewModel.note]);
	return /* @__PURE__ */ React.createElement("div", { className: "space-y-3 md:space-y-5" }, /* @__PURE__ */ React.createElement("div", { className: "grid gap-3 md:gap-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] bg-white p-4 shadow-[0_10px_40px_rgba(20,20,20,0.06)] ring-1 ring-black/6 md:rounded-[28px] md:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "flex items-center justify-between gap-3" }, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-[22px] font-extrabold text-zinc-900" }, locales.getText("pisell2.venue.checkout.court.summary") || "场地预订摘要"))), /* @__PURE__ */ React.createElement("div", { className: "mt-5 grid gap-4 md:grid-cols-2" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] bg-[#faf7f4] p-4 ring-1 ring-black/6 md:col-span-2" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-[#a69183]" }, locales.getText("pisell2.venue.checkout.selected.courts") || "已选场地"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 space-y-2 text-[15px] font-semibold text-zinc-900" }, mergedCourtSessionLines.length ? mergedCourtSessionLines.map((line, idx) => /* @__PURE__ */ React.createElement("div", { key: `venue-session-line-${idx}` }, line)) : /* @__PURE__ */ React.createElement("div", null, locales.getText("pisell2.venue.checkout.sessions.empty") || "-"))), addonCartItems.length > 0 ? /* @__PURE__ */ React.createElement("div", { className: "rounded-[22px] bg-[#faf7f4] p-4 ring-1 ring-black/6" }, /* @__PURE__ */ React.createElement("div", { className: "text-sm font-semibold text-[#a69183]" }, locales.getText("pisell2.venue.checkout.addons") || "附加项"), /* @__PURE__ */ React.createElement("div", { className: "mt-3 text-[15px] font-semibold text-zinc-900" }, addonCartItems.map((item, idx) => /* @__PURE__ */ React.createElement("div", { key: `addon-${item.id || idx}` }, item.title || item.name || "-")))) : null)), /* @__PURE__ */ React.createElement("div", { className: "space-y-4" }, /* @__PURE__ */ React.createElement("div", { className: "rounded-[28px] bg-white p-5 shadow-[0_10px_40px_rgba(20,20,20,0.06)] ring-1 ring-black/6 md:p-6" }, /* @__PURE__ */ React.createElement("div", { className: "mt-5 rounded-[22px] bg-[#faf7f4] p-4 ring-1 ring-black/6" }, /* @__PURE__ */ React.createElement("div", { className: "text-lg font-bold text-zinc-900" }, locales.getText("pisell2.venue.checkout.notice") || "备注"), /* @__PURE__ */ React.createElement("textarea", {
		className: "mt-4 min-h-[120px] w-full rounded-[20px] border border-black/10 bg-white px-4 py-4 text-sm outline-none placeholder:text-zinc-400",
		value: noteValue,
		onChange: (e) => setNoteValue(e.target.value),
		placeholder: String(locales.getText("pisell2.venue.note.placeholder") || "特殊要求..."),
		onBlur: () => {
			handleNoteBlur();
		}
	}))))));
}
function normalizeCountryCallingCode(code) {
	const value = String(code || "").trim();
	if (!value) return "";
	return value.startsWith("+") ? value : `+${value}`;
}
function toContactFormValues(contactsInfoList) {
	var _contactInfo$phone, _contactInfo$phone2, _contactInfo$phone3;
	const contactInfo = Array.isArray(contactsInfoList) ? contactsInfoList[0] : null;
	if (!contactInfo || typeof contactInfo !== "object") return {
		first_name: "",
		last_name: "",
		email: "",
		phone: {
			phone: "",
			countryCallingCode: "",
			countryCode: ""
		}
	};
	return {
		first_name: String((contactInfo === null || contactInfo === void 0 ? void 0 : contactInfo.first_name) || ""),
		last_name: String((contactInfo === null || contactInfo === void 0 ? void 0 : contactInfo.last_name) || ""),
		email: String((contactInfo === null || contactInfo === void 0 ? void 0 : contactInfo.email) || ""),
		phone: {
			phone: String((contactInfo === null || contactInfo === void 0 || (_contactInfo$phone = contactInfo.phone) === null || _contactInfo$phone === void 0 ? void 0 : _contactInfo$phone.phone) || ""),
			countryCallingCode: normalizeCountryCallingCode(contactInfo === null || contactInfo === void 0 || (_contactInfo$phone2 = contactInfo.phone) === null || _contactInfo$phone2 === void 0 ? void 0 : _contactInfo$phone2.country_calling_code),
			countryCode: String((contactInfo === null || contactInfo === void 0 || (_contactInfo$phone3 = contactInfo.phone) === null || _contactInfo$phone3 === void 0 ? void 0 : _contactInfo$phone3.country_code) || "")
		}
	};
}
function toContactsInfoPayload(formValues) {
	var _formValues$phone, _formValues$phone2, _formValues$phone3;
	const firstName = String((formValues === null || formValues === void 0 ? void 0 : formValues.first_name) || "").trim();
	const lastName = String((formValues === null || formValues === void 0 ? void 0 : formValues.last_name) || "").trim();
	const email = String((formValues === null || formValues === void 0 ? void 0 : formValues.email) || "").trim();
	const phoneValue = String((formValues === null || formValues === void 0 || (_formValues$phone = formValues.phone) === null || _formValues$phone === void 0 ? void 0 : _formValues$phone.phone) || "").trim();
	const countryCallingCode = String((formValues === null || formValues === void 0 || (_formValues$phone2 = formValues.phone) === null || _formValues$phone2 === void 0 ? void 0 : _formValues$phone2.countryCallingCode) || "").trim();
	const countryCode = String((formValues === null || formValues === void 0 || (_formValues$phone3 = formValues.phone) === null || _formValues$phone3 === void 0 ? void 0 : _formValues$phone3.countryCode) || "").trim();
	if (!Boolean(firstName || lastName || email || phoneValue || countryCallingCode || countryCode)) return [];
	return [{
		first_name: firstName,
		last_name: lastName,
		display_name: `${firstName} ${lastName}`.trim(),
		email,
		phone: {
			phone: phoneValue,
			country_calling_code: countryCallingCode,
			country_code: countryCode
		}
	}];
}
/** 将 i18n 模板中的 `{key}` 替换为对应值（与 venueBooking utils 中 hour.format 用法一致） */
function applyI18nPlaceholders(template, vars) {
	let result = template;
	for (const [key, value] of Object.entries(vars)) result = result.split(`{${key}}`).join(String(value));
	return result;
}
/** 结算页时长文案：走 locales，英文用 min，中文用 分钟 / 分鐘 等 */
function formatCheckoutDurationText(totalMinutes) {
	const hours = Math.floor(totalMinutes / 60);
	const minutes = totalMinutes % 60;
	if (hours > 0 && minutes > 0) return applyI18nPlaceholders(String(locales.getText("pisell2.venue.checkout.duration.hours_minutes") || "{hours}h {minutes}min"), {
		hours,
		minutes
	});
	if (hours > 0) return applyI18nPlaceholders(String(locales.getText("pisell2.venue.checkout.duration.hours") || "{hours}h"), { hours });
	return applyI18nPlaceholders(String(locales.getText("pisell2.venue.checkout.duration.minutes") || "{minutes}min"), { minutes });
}
function getSessionDisplayText(item) {
	const startRaw = String((item === null || item === void 0 ? void 0 : item.start_date) || "");
	const endRaw = String((item === null || item === void 0 ? void 0 : item.end_date) || "");
	const start = dayjs(startRaw);
	const end = dayjs(endRaw);
	if (!start.isValid() || !end.isValid()) return String((item === null || item === void 0 ? void 0 : item.description) || (item === null || item === void 0 ? void 0 : item.subtitle) || "-");
	const durationText = formatCheckoutDurationText(Math.max(0, end.diff(start, "minute")));
	return `${start.format("HH:mm")} ~ ${end.format("HH:mm")} ${start.format("DD/MM/YYYY")} (${durationText})`;
}
function getVenueResourceName(item) {
	var _item$resources;
	const relationFormName = String((item === null || item === void 0 ? void 0 : item.relation_form_name) || "").trim();
	if (relationFormName) return relationFormName;
	const resourceMainField = String((item === null || item === void 0 || (_item$resources = item.resources) === null || _item$resources === void 0 || (_item$resources = _item$resources[0]) === null || _item$resources === void 0 ? void 0 : _item$resources.main_field) || "").trim();
	if (resourceMainField) return resourceMainField;
	const fallbackTitle = String((item === null || item === void 0 ? void 0 : item.title) || (item === null || item === void 0 ? void 0 : item.name) || "").trim();
	if (fallbackTitle) return fallbackTitle;
	return "";
}
function getItemLineTotal(item) {
	const quantity = Number.isNaN(Number(item === null || item === void 0 ? void 0 : item.num)) ? 1 : Math.max(1, Math.floor(Number(item === null || item === void 0 ? void 0 : item.num)));
	const price = Number(item === null || item === void 0 ? void 0 : item.price);
	if (!Number.isNaN(price)) return price * quantity;
	const total = Number(item === null || item === void 0 ? void 0 : item.total);
	if (!Number.isNaN(total)) return total;
	return 0;
}
//#endregion
export { Checkout as default };
