import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import useEngineContext from "../../../hooks/useEngineContext.js";
import ClientName from "../../clientName/index.js";
import { PAYMENT_STATUS_COLOR_MAP, getPaymentStatusMap } from "../config/order.js";
import { createNoteApis } from "../serve.js";
import { BOOKING_STATUS_COLOR_MAP, getBookingHeaderLabels, getBookingPlatformMap, getBookingStatusMap, getFilterButtonList, getSortList } from "../config/booking.js";
import { BUSINESS_COLOR_MAP, getBusinessLabelMap } from "../config/index.js";
import { Tag as Tag$1, buildDateTime, formatAmount as formatAmount$1, formatPhone, getDisplayLines, normalizeList, parseJson, textStyles } from "./perspectiveUtils.js";
import BookingNotesPreview from "../components/BookingNotesPreview.js";
import BookingFormsPreview from "../components/BookingFormsPreview.js";
import React, { useCallback, useMemo } from "react";
import { locales } from "@pisell/utils";
import { PisellDateTimeDisplay, PisellTimeRangeDisplay } from "@pisell/materials";
//#region src/plus/pisellSalesManagement/hooks/useBookingPerspective.tsx
function getBookingType(record) {
	var _record$order$metadat, _record$metadata;
	if ((record === null || record === void 0 || (_record$order$metadat = record.order.metadata) === null || _record$order$metadat === void 0 ? void 0 : _record$order$metadat.appointment_structure_version) === "2.0") return "pisell2";
	if (record === null || record === void 0 || (_record$metadata = record.metadata) === null || _record$metadata === void 0 ? void 0 : _record$metadata.multiple_resource_flag) return "pisell2";
	if (record.parent_id > 0 && record.item_type !== "recurring_booking") return "pisell2";
	return "pisell1";
}
const useBookingPerspective = (params) => {
	var _context$appHelper, _context$engine;
	const context = useEngineContext();
	const utils = context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils;
	/** 监听 locale，切换语言时重新计算 label/filter/sort 等文案 */
	const locale = context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale;
	/**
	* 静态部分：label maps、uniqueTables 等重计算量大的数据，
	* 仅在 relationTables 变化时重新计算。
	*/
	const staticData = useMemo(() => {
		const BOOKING_STATUS_LABEL_MAP = getBookingStatusMap();
		const BOOKING_PLATFORM_LABEL_MAP = getBookingPlatformMap();
		const PAYMENT_STATUS_LABEL_MAP = getPaymentStatusMap();
		const BUSINESS_LABEL_MAP = getBusinessLabelMap();
		const bookingLabels = getBookingHeaderLabels();
		const { relationTables } = params || {};
		return {
			BOOKING_STATUS_LABEL_MAP,
			BOOKING_PLATFORM_LABEL_MAP,
			PAYMENT_STATUS_LABEL_MAP,
			BUSINESS_LABEL_MAP,
			bookingLabels,
			uniqueTables: (relationTables || []).filter((item) => [
				"appointment_booking",
				"ticket",
				"party_room",
				"therapist",
				"table-order",
				"voucher_ticket",
				"mobile_order"
			].includes(item.relation_type)).reduce((pre, cur) => {
				if (!pre.some((obj) => obj.form_id === cur.form_id)) pre.push(cur);
				return pre;
			}, [])
		};
	}, [params === null || params === void 0 ? void 0 : params.relationTables, locale]);
	const buildColumns = useCallback((ctx) => {
		const { BOOKING_STATUS_LABEL_MAP, BOOKING_PLATFORM_LABEL_MAP, PAYMENT_STATUS_LABEL_MAP, BUSINESS_LABEL_MAP, bookingLabels, uniqueTables } = staticData;
		return [
			{
				title: bookingLabels.bookingBrief,
				key: "booking_brief",
				width: 188,
				render: (_, record) => {
					var _record$order, _record$order2, _record$order3;
					const startAt = buildDateTime(record === null || record === void 0 ? void 0 : record.start_date, record === null || record === void 0 ? void 0 : record.start_time) || (record === null || record === void 0 ? void 0 : record.start_at);
					const status = record === null || record === void 0 ? void 0 : record.appointment_status;
					const statusLabel = BOOKING_STATUS_LABEL_MAP[status] || status || "-";
					const statusColor = BOOKING_STATUS_COLOR_MAP[status] || "";
					const orderNote = record === null || record === void 0 || (_record$order = record.order) === null || _record$order === void 0 ? void 0 : _record$order.note;
					const internalNotes = record === null || record === void 0 ? void 0 : record.notes;
					const noteApis = createNoteApis(record === null || record === void 0 || (_record$order2 = record.order) === null || _record$order2 === void 0 ? void 0 : _record$order2.id);
					return /* @__PURE__ */ React.createElement("div", { className: "pisell-sales-grid-booking-brief" }, /* @__PURE__ */ React.createElement(ClientName, { dataSource: record === null || record === void 0 || (_record$order3 = record.order) === null || _record$order3 === void 0 ? void 0 : _record$order3.customer }), startAt ? /* @__PURE__ */ React.createElement(PisellDateTimeDisplay, {
						value: startAt,
						layout: "inline",
						textAlign: "left",
						timeFormat: { padHour: true },
						dateFormat: {
							order: "DMY",
							showYear: false,
							shortMonth: true,
							showRelativeDay: true,
							useCommaBeforeYear: false
						},
						fields: { fieldOrder: [
							"time",
							"weekday",
							"date"
						] }
					}) : null, /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(Tag$1, { style: {
						backgroundColor: statusColor,
						whiteSpace: "nowrap",
						border: "none",
						fontWeight: 500
					} }, statusLabel)), /* @__PURE__ */ React.createElement(BookingNotesPreview, {
						dataSource: {
							note: orderNote,
							internalNotes,
							apis: noteApis,
							bookingId: record === null || record === void 0 ? void 0 : record.id,
							onChange: (value, type, noteType) => {
								ctx.refresh();
							}
						},
						labels: {
							orderNote: bookingLabels.orderNote,
							internalNote: bookingLabels.internalNote,
							more: bookingLabels.more
						},
						style: { maxWidth: 132 }
					}));
				}
			},
			{
				title: bookingLabels.serviceTime,
				key: "service_time",
				align: "center",
				width: 165,
				render: (_, record) => {
					const startAt = buildDateTime(record === null || record === void 0 ? void 0 : record.start_date, record === null || record === void 0 ? void 0 : record.start_time) || (record === null || record === void 0 ? void 0 : record.start_at);
					const endAt = buildDateTime(record === null || record === void 0 ? void 0 : record.end_date, record === null || record === void 0 ? void 0 : record.end_time) || (record === null || record === void 0 ? void 0 : record.end_at);
					if (!startAt || !endAt) return null;
					return /* @__PURE__ */ React.createElement("div", { style: { textAlign: "center" } }, /* @__PURE__ */ React.createElement(PisellTimeRangeDisplay, {
						startAt,
						endAt
					}));
				},
				uniformCompare: (_, record) => {
					const { start_date = "", start_time = "", end_date = "", end_time = "" } = record;
					return `${start_date}${start_time}${end_date}${end_time}`;
				}
			},
			{
				title: bookingLabels.customer,
				key: "customer",
				align: "center",
				width: 150,
				uniformCompare: (_, record) => {
					const value = record.order;
					const customer = value === null || value === void 0 ? void 0 : value.customer;
					if (!customer) return "-";
					const guestCode = customer === null || customer === void 0 ? void 0 : customer.guest_code;
					if (guestCode) return `${guestCode}`;
					if (customer.user_id === 1) return "walk-in";
					return customer;
				},
				render: (_, record) => {
					const value = record.order;
					const customer = value === null || value === void 0 ? void 0 : value.customer;
					if (customer === null || customer === void 0 ? void 0 : customer.guest_code) return /* @__PURE__ */ React.createElement("div", { style: {
						display: "flex",
						flexDirection: "column",
						alignItems: "center",
						textAlign: "center"
					} }, /* @__PURE__ */ React.createElement("div", { style: { fontWeight: "bold" } }, bookingLabels.guest));
					const lines = getDisplayLines([formatPhone((customer === null || customer === void 0 ? void 0 : customer.phone) || (record === null || record === void 0 ? void 0 : record.phone), (customer === null || customer === void 0 ? void 0 : customer.country_calling_code) || (record === null || record === void 0 ? void 0 : record.country_calling_code)), customer === null || customer === void 0 ? void 0 : customer.email]);
					return /* @__PURE__ */ React.createElement("div", { style: {
						display: "flex",
						flexDirection: "column",
						alignItems: "center",
						textAlign: "center"
					} }, /* @__PURE__ */ React.createElement(ClientName, {
						dataSource: customer,
						style: { fontSize: 14 }
					}), lines.map((line, index) => /* @__PURE__ */ React.createElement("div", {
						key: `${line}-${index}`,
						style: textStyles.text
					}, line)));
				}
			},
			{
				title: bookingLabels.contact,
				key: "contact",
				align: "center",
				width: 150,
				uniformCompare: (_, record) => {
					const value = record.order;
					const contactValue = value === null || value === void 0 ? void 0 : value.contacts_info;
					if (!contactValue) return "-";
					return contactValue;
				},
				render: (_, record) => {
					const value = record.order;
					const contactValue = value === null || value === void 0 ? void 0 : value.contacts_info;
					if (!contactValue) return "-";
					const lines = getDisplayLines([formatPhone(contactValue === null || contactValue === void 0 ? void 0 : contactValue.phone), contactValue === null || contactValue === void 0 ? void 0 : contactValue.email]);
					return /* @__PURE__ */ React.createElement("div", { style: {
						display: "flex",
						flexDirection: "column",
						alignItems: "center",
						textAlign: "center"
					} }, /* @__PURE__ */ React.createElement(ClientName, {
						dataSource: contactValue,
						style: { fontSize: 14 }
					}), lines.map((line, index) => /* @__PURE__ */ React.createElement("div", {
						key: `${line}-${index}`,
						style: textStyles.text
					}, line)));
				}
			},
			{
				title: bookingLabels.holder,
				dataIndex: "holder_data",
				key: "holder_data",
				align: "center",
				width: 110,
				uniformCompare: (value, record) => {
					if (!value) return "-";
					return value;
				},
				render: (value, record) => {
					var _holderValue$data;
					if (!value) return "-";
					const holderValue = Array.isArray(value) ? value[0] : value;
					if (!holderValue) return "-";
					let holderPhone;
					const customerPhone = ((_holderValue$data = holderValue.data) === null || _holderValue$data === void 0 ? void 0 : _holderValue$data.customer_phone) || holderValue.customer_phone;
					if (customerPhone) holderPhone = formatPhone(customerPhone);
					const lines = getDisplayLines([holderPhone]);
					return /* @__PURE__ */ React.createElement("div", { style: {
						display: "flex",
						flexDirection: "column",
						alignItems: "center",
						textAlign: "center"
					} }, /* @__PURE__ */ React.createElement(ClientName, {
						dataSource: { display_name: holderValue.main_field || record.holder_name || "" },
						style: { fontSize: 14 }
					}), lines.map((line, index) => /* @__PURE__ */ React.createElement("div", {
						key: `${line}-${index}`,
						style: _objectSpread2(_objectSpread2({}, textStyles.text), {}, { whiteSpace: "nowrap" })
					}, line)));
				}
			},
			{
				title: bookingLabels.services,
				key: "services",
				align: "center",
				width: 120,
				render: (_, record) => {
					const items = normalizeList(parseJson(record === null || record === void 0 ? void 0 : record.order_detail));
					const displayItems = items.slice(0, 3);
					const moreCount = items.length - displayItems.length;
					const lines = displayItems.map((item) => {
						const title = utils.translation(item.product_title);
						const qty = item === null || item === void 0 ? void 0 : item.product_quantity;
						if (!title) return null;
						return qty ? `${title} x${qty}` : String(title);
					}).filter((item) => item);
					if (moreCount > 0) lines.push(`+${moreCount} ${bookingLabels.more}`);
					if (lines.length === 0) return null;
					return /* @__PURE__ */ React.createElement("div", { style: {
						display: "flex",
						flexDirection: "column",
						alignItems: "center",
						textAlign: "center"
					} }, lines.map((line, index) => /* @__PURE__ */ React.createElement("div", {
						key: `${line}-${index}`,
						style: textStyles.text
					}, line)));
				},
				uniformCompare: (_value, record) => {
					return (record === null || record === void 0 ? void 0 : record.order_detail) || "";
				}
			},
			{
				title: bookingLabels.pax,
				dataIndex: "number",
				key: "number",
				align: "center",
				width: 110,
				render: (_, record) => {
					const count = record === null || record === void 0 ? void 0 : record.number;
					return /* @__PURE__ */ React.createElement("span", { style: _objectSpread2(_objectSpread2({}, textStyles.text), {}, { textAlign: "center" }) }, count !== null && count !== void 0 ? count : "-");
				}
			},
			{
				title: bookingLabels.resource,
				dataIndex: "relation_form_name",
				key: "relation_form_name",
				align: "center",
				width: 100,
				render: (value) => {
					if (!value) return "-";
					return /* @__PURE__ */ React.createElement("div", { style: textStyles.text }, value);
				}
			},
			{
				title: bookingLabels.forms,
				key: "appointment_form",
				width: 132,
				align: "center",
				render: (_, record) => {
					var _record$order4;
					return /* @__PURE__ */ React.createElement("div", { style: {
						width: "100%",
						maxWidth: 132,
						margin: "0 auto",
						minWidth: 0
					} }, /* @__PURE__ */ React.createElement(BookingFormsPreview, {
						value: record === null || record === void 0 ? void 0 : record.appointment_form,
						uniqueTables,
						bookingLabels,
						textStyles,
						relationId: record.parent_id || record.id,
						relationType: record.item_type,
						customer: (_record$order4 = record.order) === null || _record$order4 === void 0 ? void 0 : _record$order4.customer
					}));
				}
			},
			{
				title: bookingLabels.orderInfo,
				key: "order_info",
				width: 124,
				align: "center",
				render: (_, record) => {
					const order = (record === null || record === void 0 ? void 0 : record.order) || {};
					const orderCode = order === null || order === void 0 ? void 0 : order.shop_full_order_number;
					const totalAmount = order === null || order === void 0 ? void 0 : order.total_amount;
					const currencySymbol = order === null || order === void 0 ? void 0 : order.currency_symbol;
					const paymentStatus = order === null || order === void 0 ? void 0 : order.payment_status;
					const paymentLabel = PAYMENT_STATUS_LABEL_MAP[paymentStatus] || "-";
					const paymentColor = PAYMENT_STATUS_COLOR_MAP[paymentStatus] || "";
					return /* @__PURE__ */ React.createElement("div", { style: {
						display: "flex",
						flexDirection: "column",
						alignItems: "flex-start"
					} }, /* @__PURE__ */ React.createElement("div", { style: {
						fontWeight: 600,
						textDecoration: "underline",
						color: "var(--theme-color, #7f56d9)"
					} }, orderCode || "-"), totalAmount != null ? /* @__PURE__ */ React.createElement("div", { style: textStyles.text }, formatAmount$1(totalAmount, currencySymbol)) : null, paymentLabel ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(Tag$1, { style: {
						backgroundColor: paymentColor,
						whiteSpace: "nowrap",
						border: "none",
						fontWeight: 500
					} }, paymentLabel)) : null);
				}
			},
			{
				title: bookingLabels.bookingId,
				dataIndex: "booking_id",
				key: "booking_id",
				align: "center",
				width: 120,
				render: (value) => /* @__PURE__ */ React.createElement("span", { style: _objectSpread2(_objectSpread2({}, textStyles.text), {}, {
					textAlign: "center",
					fontSize: 14,
					fontWeight: 400
				}) }, value)
			},
			{
				title: bookingLabels.orderOrigin,
				key: "order_origin",
				width: 160,
				align: "center",
				render: (_, record) => {
					var _record$order5, _record$order6, _record$order7, _record$order8, _record$order9, _record$order10;
					const businessKey = (record === null || record === void 0 || (_record$order5 = record.order) === null || _record$order5 === void 0 ? void 0 : _record$order5.business_code) || (record === null || record === void 0 ? void 0 : record.business_code);
					const businessLabel = BUSINESS_LABEL_MAP[businessKey];
					const channel = BOOKING_PLATFORM_LABEL_MAP[record === null || record === void 0 || (_record$order6 = record.order) === null || _record$order6 === void 0 ? void 0 : _record$order6.order_sales_channel] || BOOKING_PLATFORM_LABEL_MAP[record === null || record === void 0 ? void 0 : record.order_platform] || BOOKING_PLATFORM_LABEL_MAP[record === null || record === void 0 || (_record$order7 = record.order) === null || _record$order7 === void 0 ? void 0 : _record$order7.order_platform] || (record === null || record === void 0 || (_record$order8 = record.order) === null || _record$order8 === void 0 ? void 0 : _record$order8.order_sales_channel) || (record === null || record === void 0 ? void 0 : record.order_platform);
					const device = (record === null || record === void 0 ? void 0 : record.device_name) || (record === null || record === void 0 ? void 0 : record.device) || (record === null || record === void 0 ? void 0 : record.terminal);
					const time = (record === null || record === void 0 ? void 0 : record.created_at) || (record === null || record === void 0 || (_record$order9 = record.order) === null || _record$order9 === void 0 ? void 0 : _record$order9.created_at);
					const actor = (record === null || record === void 0 || (_record$order10 = record.order) === null || _record$order10 === void 0 ? void 0 : _record$order10.create_account) || (record === null || record === void 0 ? void 0 : record.create_account) || (record === null || record === void 0 ? void 0 : record.operator_name);
					const lines = getDisplayLines([channel, device]);
					return /* @__PURE__ */ React.createElement("div", { style: {
						display: "flex",
						flexDirection: "column",
						alignItems: "flex-start"
					} }, businessLabel ? /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement(Tag$1, {
						color: BUSINESS_COLOR_MAP[businessKey],
						style: {
							color: "black",
							fontWeight: 500
						}
					}, businessLabel)) : null, lines.map((line, index) => /* @__PURE__ */ React.createElement("div", {
						key: `${line}-${index}`,
						style: textStyles.text
					}, line)), actor ? /* @__PURE__ */ React.createElement("div", { style: _objectSpread2({
						display: "flex",
						alignItems: "center"
					}, textStyles.text) }, /* @__PURE__ */ React.createElement("span", null, bookingLabels.createdBy, ":"), /* @__PURE__ */ React.createElement(ClientName, {
						dataSource: actor,
						style: { fontSize: 12 }
					})) : null, /* @__PURE__ */ React.createElement(PisellDateTimeDisplay, {
						value: time,
						layout: "inline",
						textAlign: "left",
						timeFormat: { padHour: true },
						dateFormat: {
							order: "DMY",
							showYear: false,
							shortMonth: true,
							showRelativeDay: true,
							useCommaBeforeYear: false
						},
						fields: { fieldOrder: [
							"time",
							"weekday",
							"date"
						] },
						style: { whiteSpace: "nowrap" }
					}));
				}
			},
			{
				title: bookingLabels.updated,
				key: "updated",
				width: 132,
				align: "center",
				render: (_, record) => {
					var _record$order11;
					const time = (record === null || record === void 0 ? void 0 : record.updated_at) || (record === null || record === void 0 || (_record$order11 = record.order) === null || _record$order11 === void 0 ? void 0 : _record$order11.updated_at);
					const lines = getDisplayLines([BOOKING_PLATFORM_LABEL_MAP[record === null || record === void 0 ? void 0 : record.order_platform] || (record === null || record === void 0 ? void 0 : record.order_platform)]);
					return /* @__PURE__ */ React.createElement("div", { style: {
						display: "flex",
						flexDirection: "column",
						alignItems: "flex-start"
					} }, /* @__PURE__ */ React.createElement(PisellDateTimeDisplay, {
						value: time,
						layout: "inline",
						textAlign: "left",
						timeFormat: { padHour: true },
						dateFormat: {
							order: "DMY",
							showYear: false,
							shortMonth: true,
							showRelativeDay: true,
							useCommaBeforeYear: false
						},
						fields: { fieldOrder: [
							"time",
							"weekday",
							"date"
						] },
						style: { whiteSpace: "nowrap" }
					}), lines.map((line, index) => /* @__PURE__ */ React.createElement("div", {
						key: `${line}-${index}`,
						style: textStyles.text
					}, line)));
				}
			}
		];
	}, [staticData]);
	return useMemo(() => ({
		key: "monitor",
		label: "Monitor",
		getChildComponentProps: (ctx) => ({
			grid: {
				bordered: true,
				collapseUniformColumns: true,
				columns: buildColumns(ctx),
				defaultHiddenColumnKeys: ["order_origin", "updated"],
				scroll: {
					x: "max-content",
					autoCalc: true,
					scrollToFirstRowOnChange: true
				},
				rowSelection: false,
				onRow: (record) => ({ onClick: () => {
					var _record$order12, _record$order13;
					if (!record.id) return;
					const time = /* @__PURE__ */ new Date();
					utils === null || utils === void 0 || utils.action({
						type: "pisell1.bookingDetail",
						data: {
							component_type: getBookingType(record),
							booking_id: record.order.id,
							type: record.parent_id === 0 ? "list" : "detail",
							id: record.id,
							isParallelResourcesBooking: record.relation_id === 0 && record.relation_type === "",
							preliminaryBookingDetail: {
								customer: record === null || record === void 0 || (_record$order12 = record.order) === null || _record$order12 === void 0 ? void 0 : _record$order12.customer,
								id: record.order.id,
								order_sales_channel: record === null || record === void 0 || (_record$order13 = record.order) === null || _record$order13 === void 0 ? void 0 : _record$order13.order_sales_channel,
								bookings: {
									booking_id: record === null || record === void 0 ? void 0 : record.booking_id,
									appointment_status: record === null || record === void 0 ? void 0 : record.appointment_status,
									list: [{
										start_date: record === null || record === void 0 ? void 0 : record.start_date,
										start_time: record === null || record === void 0 ? void 0 : record.start_time
									}]
								}
							}
						},
						callback: (cbParams) => {
							const { type } = cbParams || {};
							if (Date.now() - time.getTime() < 500) return;
							if (type === "close") return;
							ctx.refresh();
						}
					});
				} })
			},
			toolBar: {
				search: { showConfirmButton: false },
				sort: { list: getSortList() },
				filter: {
					hiddenQuickFilter: true,
					defaultFilterValue: {
						quickFilter: [],
						otherFilter: getFilterButtonList(),
						values: {}
					}
				},
				quickFilter: {
					hideFilterNamesOnFloorMap: ["booking_time_start_between"],
					filterList: [{
						type: "rangePicker",
						name: "booking_time_start_between",
						key: "bookingTimeStartBetween",
						props: {
							placeholder: locales.getText("pisell2.salesManagement.booking.filter.bookingDate.label"),
							showTime: true
						}
					}]
				}
			},
			batchActionBar: { overflowThreshold: 2 }
		})
	}), [
		buildColumns,
		utils,
		locale
	]);
};
//#endregion
export { useBookingPerspective };
