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 { formatOriginalPrice, formatProductBundle, formatProductOption, formatProductPrice, formatSellingPrice, getBundleDiscountList, getMainProductSellingPrice, getSourceProductPrice } from "../components/footer/utils.js";
import { formatProductListByCategory, getIsEject, getIsOnlySession, getMainPrice, getProductTotalPrice, isSessionProduct, request } from "../utils.js";
import Drawer$1 from "../components/drawer/index.js";
import useEngineContext from "../../../hooks/useEngineContext.js";
import TabProduct from "../components/TabProduct/index.js";
import TabPane from "../components/tabPane/index.js";
import { Context, Provider } from "./model.js";
import SelectProductItem from "../components/TabProduct/selectProductItem/index.js";
import EmptyBooking from "../components/emptyBooking/index.js";
import Footer from "../components/footer/index.js";
import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import { Button, Input, Modal, Skeleton } from "antd";
import { getUniqueId, locales } from "@pisell/utils";
import SearchLg from "@pisell/icon/es/SearchLg";
import "./index.less";
//#region src/components/booking/addons/index.tsx
/**
* @title: 添加额外商品
* @description:
* @return {*}
* @Author: zhiwei.Wang
* @Date: 2024-01-30 16:33
*/
const formatProducts = (values) => {
	let arr = [];
	arr = values.map((item) => {
		var _item$_extend, _item$_extend2, _item$_extend3, _item$_extend4, _item$_extend5, _getMainProductSellin;
		const bundleDiscountList = getBundleDiscountList(((_item$_extend = item._extend) === null || _item$_extend === void 0 || (_item$_extend = _item$_extend.other) === null || _item$_extend === void 0 ? void 0 : _item$_extend.bundle) || []);
		const discount_list = [...(item === null || item === void 0 ? void 0 : item.discount_list) || []];
		discount_list.push(...bundleDiscountList);
		return {
			order_detail_id: item.order_detail_id || 0,
			num: item._extend.quantity,
			price: formatProductPrice(item),
			product_id: item.id,
			discount_list: discount_list || [],
			discount_amount: 0,
			product_discount_reason: "",
			is_charge_tax: item.is_charge_tax,
			note: "",
			discountway: "num",
			discount_type: "discount",
			bundle_edit: (_item$_extend2 = item._extend) === null || _item$_extend2 === void 0 ? void 0 : _item$_extend2.bundle_edit,
			product_bundle: formatProductBundle((_item$_extend3 = item._extend) === null || _item$_extend3 === void 0 || (_item$_extend3 = _item$_extend3.other) === null || _item$_extend3 === void 0 ? void 0 : _item$_extend3.bundle),
			"product_option_item": formatProductOption((_item$_extend4 = item._extend) === null || _item$_extend4 === void 0 || (_item$_extend4 = _item$_extend4.other) === null || _item$_extend4 === void 0 ? void 0 : _item$_extend4.option),
			"product_variant_id": ((_item$_extend5 = item._extend) === null || _item$_extend5 === void 0 || (_item$_extend5 = _item$_extend5.other) === null || _item$_extend5 === void 0 ? void 0 : _item$_extend5.product_variant_id) || 0,
			"source_product_price": getSourceProductPrice(item),
			"main_product_selling_price": (_getMainProductSellin = getMainProductSellingPrice(item)) !== null && _getMainProductSellin !== void 0 ? _getMainProductSellin : formatProductPrice(item),
			"calculated_original_price": formatOriginalPrice(item),
			"calculated_selling_price": formatSellingPrice(item),
			"tax_fee": item._extend.tax_fee
		};
	});
	return arr;
};
const restoreProductOtherData = (data) => {
	let detail = data;
	return {
		product_id: detail.product_id,
		option: [],
		bundle: (detail.product_bundle || []).map((bundleItem) => {
			return _objectSpread2(_objectSpread2({}, bundleItem), {}, {
				title: bundleItem.bundle_title,
				group_id: bundleItem.bundle_group_id,
				id: bundleItem.bundle_id,
				product_id: bundleItem.bundle_product_id,
				bundle_variant_id: bundleItem.bundle_variant_id,
				quantity: bundleItem.num,
				option: bundleItem.option.map((optionItem) => {
					return _objectSpread2(_objectSpread2({}, optionItem), {}, {
						name: optionItem.name["auto"],
						quantity: bundleItem.num,
						product_option_item_id: optionItem.option_group_item_id
					});
				})
			});
		}),
		product_variant_id: detail.product_variant_id || 0,
		quantity: Number(detail.product_quantity)
	};
};
const formatProductValues = (data) => {
	return data.map((d) => {
		return _objectSpread2(_objectSpread2({}, d), {}, {
			id: d.product_id,
			title: d.product_title,
			isAddons: true,
			quantity: d.product_quantity,
			cover: d.product_cover,
			price: Number(d.source_product_price),
			_extend: {
				total: Number(d.selling_price),
				origin_total: Number(d.selling_price),
				payment_price: Number(d.payment_price),
				price: Number(d.source_product_price),
				quantity: d.product_quantity,
				bundle_edit: 0,
				other: restoreProductOtherData(d)
			},
			payment_price: Number(d.payment_price)
		});
	});
};
const Addons = Provider((props) => {
	var _context$appHelper, _state$addons2, _state$addons4;
	const { globalState } = props;
	const { state, dispatch } = useContext(Context);
	const [loading, setLoading] = useState(false);
	const [listLoading, setListLoading] = useState(false);
	const [search, setSearch] = useState("");
	const searchRef = useRef();
	const context = useEngineContext();
	const [modal, contextHolder] = Modal.useModal();
	const { isTerminal, interaction } = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	request.setRequest(context.appHelper.utils.request);
	useEffect(() => {
		dispatch({
			type: "setState",
			payload: { setGlobalState: props.setGlobalState }
		});
	}, []);
	useEffect(() => {
		dispatch({
			type: "setState",
			payload: _objectSpread2({}, globalState)
		});
	}, [globalState]);
	/**
	* @title: 获取商品列表和当前的预约商品
	* @description:
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-01-30 16:34
	*/
	const init = () => {
		getAddonsByOrderId();
	};
	useEffect(() => {
		if (isTerminal === null || isTerminal === void 0 ? void 0 : isTerminal()) {
			var _interaction$utils;
			interaction === null || interaction === void 0 || (_interaction$utils = interaction.utils) === null || _interaction$utils === void 0 || _interaction$utils.mountFunction("booking", "refreshBookingDetailAddons", () => {
				init();
			});
		}
	}, [state]);
	/**
	* @title: 通过订单id 获取addons
	* @description:
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-01-30 16:35
	*/
	const getAddonsByOrderId = function() {
		var _ref = _asyncToGenerator(function* () {
			setLoading(true);
			dispatch({
				type: "setAddons",
				payload: {
					value: formatProductValues((yield state.apis.getAddonsByOrderId()) || []),
					load: true,
					edit: false
				}
			});
			setLoading(false);
		});
		return function getAddonsByOrderId() {
			return _ref.apply(this, arguments);
		};
	}();
	/**
	* @title: 获取商品列表
	* @description:
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-01-30 16:36
	*/
	const getProducts = function() {
		var _ref2 = _asyncToGenerator(function* () {
			setListLoading(true);
			let data = yield state.apis.getProducts({
				skip: 1,
				num: 500,
				extension_type: [
					"normal",
					"product_bundle",
					"product_package_ticket",
					"ticket"
				],
				with: ["category"],
				status: "published",
				open_quotation: 1,
				with_schedule: 0,
				with_count: ["bundleGroup", "optionGroup"],
				order_by_string: "sort:desc",
				_config: { useCache: true }
			});
			setListLoading(false);
			dispatch({
				type: "setAddons",
				payload: { originData: (data === null || data === void 0 ? void 0 : data.list) || [] }
			});
		});
		return function getProducts() {
			return _ref2.apply(this, arguments);
		};
	}();
	/**
	* @title: 添加商品
	* @description:
	* @param {any} item
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-01-30 16:36
	*/
	const handleAddProduct = (item, type) => {
		let _list = [...state.addons.value];
		const isSession = isSessionProduct(item);
		const isEject = getIsEject(item, type);
		const isOnlySession = getIsOnlySession(item);
		state.action({
			type: "pisell1.handleOpenProductModal",
			data: {
				id: item.id,
				date: state.date.value.format("YYYY-MM-DD"),
				showConfig: {
					option: true,
					session: isSession,
					variant: true,
					package: true,
					number: true
				},
				isOnlySession,
				is_eject: isEject ? 1 : 0,
				isOS: isSession
			},
			callback: (e, extension_type, detail) => {
				const _detail = detail || item;
				let product = _objectSpread2(_objectSpread2({}, _detail), {}, {
					_id: getUniqueId(),
					isAddons: true,
					_key: e.key,
					_extend: {
						other: e,
						quantity: (e === null || e === void 0 ? void 0 : e.quantity) || 1
					},
					quantity: (e === null || e === void 0 ? void 0 : e.quantity) || 1
				});
				product._extend.price = getMainPrice(product, _detail.price);
				let _total = getProductTotalPrice(product);
				product._extend.total = _total;
				product._extend.origin_total = _total;
				let _item = _list.find((d) => {
					var _d$discount_list;
					return d._extend.other.rowKey === e.rowKey && !d.booking_id && !((_d$discount_list = d.discount_list) === null || _d$discount_list === void 0 ? void 0 : _d$discount_list.length);
				});
				if (_item) _item._extend.quantity = _item._extend.quantity + product.quantity;
				else _list.push(product);
				dispatch({
					type: "setAddons",
					payload: {
						value: _list,
						showModal: false,
						edit: true
					}
				});
			}
		});
	};
	/**
	* @title: 修改商品数量
	* @description:
	* @param {any} e
	* @param {any} item
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-01-30 16:37
	*/
	const onChangeQuantity = (e, item) => {
		let quantity = e.target.value;
		let _list = [...state.addons.value];
		if (quantity == 0) _list = _list.filter((d) => d._id !== item._id);
		else {
			var _item$_extend6;
			let _item = _objectSpread2(_objectSpread2({}, item), {}, { _extend: _objectSpread2(_objectSpread2({}, item._extend), {}, { quantity: Number(e.target.value) }) });
			if (((_item$_extend6 = _item._extend) === null || _item$_extend6 === void 0 ? void 0 : _item$_extend6.bundle_edit) !== void 0) _item._extend.bundle_edit = 1;
			_list = _list.map((d) => d._id === item._id ? _item : d);
		}
		dispatch({
			type: "setAddons",
			payload: {
				value: _list,
				edit: true
			}
		});
	};
	/**
	* @title: 渲染列表, 用于处理 搜索逻辑
	* @description:
	* @param {*} useMemo
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-01-30 16:38
	*/
	const renderList = useMemo(() => {
		var _state$addons;
		let _list = ((_state$addons = state.addons) === null || _state$addons === void 0 ? void 0 : _state$addons.originData) || [];
		const isIncludes = (str) => {
			return str.toLowerCase().indexOf(search.toLowerCase()) !== -1;
		};
		return formatProductListByCategory(_list, search ? (item) => isIncludes(item.title) : void 0);
	}, [search, (_state$addons2 = state.addons) === null || _state$addons2 === void 0 ? void 0 : _state$addons2.originData]);
	const isEdit = useMemo(() => {
		var _state$addons3;
		return state === null || state === void 0 || (_state$addons3 = state.addons) === null || _state$addons3 === void 0 ? void 0 : _state$addons3.edit;
	}, [state === null || state === void 0 || (_state$addons4 = state.addons) === null || _state$addons4 === void 0 ? void 0 : _state$addons4.edit]);
	/**
	* @title: 打开新增弹窗
	* @description:
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-01-30 16:40
	*/
	const handleOpenAdd = () => {
		if (isTerminal === null || isTerminal === void 0 ? void 0 : isTerminal()) {
			var _interaction$utils2, _interaction$utils2$p;
			return interaction === null || interaction === void 0 || (_interaction$utils2 = interaction.utils) === null || _interaction$utils2 === void 0 || (_interaction$utils2$p = _interaction$utils2.postMessageToApp) === null || _interaction$utils2$p === void 0 ? void 0 : _interaction$utils2$p.call(_interaction$utils2, {
				module: "booking",
				key: "edit_order",
				data: { order_id: state.bookingId }
			});
		}
		getProducts();
		setSearch("");
		dispatch({
			type: "setAddons",
			payload: { showModal: true }
		});
		if (!state.isTerminal) setTimeout(() => {
			var _searchRef$current, _searchRef$current$fo;
			(_searchRef$current = searchRef.current) === null || _searchRef$current === void 0 || (_searchRef$current$fo = _searchRef$current.focus) === null || _searchRef$current$fo === void 0 || _searchRef$current$fo.call(_searchRef$current);
		}, 100);
	};
	/**
	* @title: 底部按钮
	* @description:
	* @param {*} useMemo
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-01-30 16:39
	*/
	const _footer = useMemo(() => {
		if (state.disabledEdit) return [];
		return [/* @__PURE__ */ React.createElement(Button, {
			className: "pisell-lowcode__booking-footer-buttons-item",
			type: "default",
			disabled: loading,
			onClick: handleOpenAdd
		}, locales.getText("pisell2.text.add"))];
	}, [
		state,
		isEdit,
		loading
	]);
	const footer = useMemo(() => {
		if (!state.bookingId) return null;
		return /* @__PURE__ */ React.createElement(Footer, {
			state,
			dispatch,
			buttons: _footer,
			source: "addons"
		});
	}, [state, _footer]);
	const editProductDetail = (item) => {
		if (state.disabledEdit) return;
		const isSession = isSessionProduct(item);
		state.action({
			type: "pisell1.handleOpenProductModal",
			data: {
				id: item.id,
				date: state.date.value.format("YYYY-MM-DD"),
				showConfig: {
					option: true,
					session: isSession,
					variant: true,
					package: true,
					number: true
				},
				value: item._extend.other,
				isOS: isSession
			},
			callback: (e, extension_type, detail) => {
				var _product$_extend;
				const _detail = detail || item;
				let product = _objectSpread2(_objectSpread2(_objectSpread2({}, item), _detail), {}, {
					isAddons: true,
					discount_list: [],
					_extend: _objectSpread2(_objectSpread2({}, item._extend), {}, {
						other: e,
						quantity: (e === null || e === void 0 ? void 0 : e.quantity) || 1
					})
				});
				if (((_product$_extend = product._extend) === null || _product$_extend === void 0 ? void 0 : _product$_extend.bundle_edit) !== void 0) product._extend.bundle_edit = 1;
				let _total = getProductTotalPrice(product);
				product._extend.total = _total;
				product._extend.origin_total = _total;
				let _list = [...state.addons.value];
				_list = _list.map((d) => d._id === product._id ? product : d);
				dispatch({
					type: "setAddons",
					payload: {
						value: _list,
						showModal: false,
						edit: true
					}
				});
			}
		});
	};
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(TabPane, {
		loading,
		header: locales.getText("pisell2.text.addons"),
		footer,
		state,
		dispatch,
		source: "addons"
	}, !state.bookingId ? /* @__PURE__ */ React.createElement(EmptyBooking, null) : /* @__PURE__ */ React.createElement(React.Fragment, null, state.addons.value.length ? /* @__PURE__ */ React.createElement("div", {
		className: "",
		style: { margin: "0 -32px" }
	}, state.addons.value.map((d) => {
		return /* @__PURE__ */ React.createElement(SelectProductItem, {
			disabled: state.disabledEdit,
			item: d,
			key: d.id,
			amountSymbol: state.amountSymbol,
			onClick: editProductDetail,
			onChangeQuantity: (e) => {
				onChangeQuantity(e, d);
			}
		});
	})) : /* @__PURE__ */ React.createElement(EmptyBooking, { description: locales.getText("pisell1.text.no-addons") }), /* @__PURE__ */ React.createElement(Drawer$1, {
		titleNoWrap: true,
		open: state.addons.showModal,
		title: locales.getText("pisell2.text.addons"),
		onClose: () => {
			dispatch({
				type: "setAddons",
				payload: { showModal: false }
			});
		},
		rootClassName: "booking-addons-wrap",
		header: /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-service-header" }, /* @__PURE__ */ React.createElement(Input, {
			ref: searchRef,
			prefix: /* @__PURE__ */ React.createElement(SearchLg, null),
			style: {
				marginTop: 16,
				height: 44
			},
			placeholder: locales.getText("pisell2.text.search"),
			allowClear: true,
			value: search,
			onChange: (e) => {
				setSearch(e.target.value);
			}
		}))
	}, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-service-body" }, /* @__PURE__ */ React.createElement(Skeleton, {
		loading: listLoading,
		active: true,
		round: true,
		style: { padding: 20 }
	}, /* @__PURE__ */ React.createElement(TabProduct, {
		scrollDom: ".booking-addons-wrap .pisell-lowcode-drawer-body",
		list: renderList,
		amountSymbol: state.amountSymbol,
		onChange: handleAddProduct
	})))))), contextHolder);
});
//#endregion
export { Addons as default, formatProducts };
