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 { getNormalAndMultiDayProductPrice } from "../info/service/serve.js";
import { getProductTotalPrice } from "../utils.js";
import useEngineContext from "../../../hooks/useEngineContext.js";
import dayjs from "dayjs";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { locales } from "@pisell/utils";
import Decimal from "decimal.js";
import { PisellModal } from "@pisell/materials";
//#region src/components/booking/hooks/useQuotation.tsx
const formatBundleItemMap = (product) => {
	return product.bundle_group.reduce((pre, cur) => {
		const curObj = {};
		cur.bundle_item.forEach((item) => {
			curObj[item.id] = item;
		});
		return _objectSpread2(_objectSpread2({}, pre), curObj);
	}, {});
};
const formatVariantItemMap = (product) => {
	return ((product === null || product === void 0 ? void 0 : product.variant) || (product === null || product === void 0 ? void 0 : product.variants) || []).reduce((pre, cur) => {
		pre[cur.id] = cur;
		return pre;
	}, {});
};
const calculateTotalPrice = (data) => {
	const _price = data.reduce((total, item) => {
		return total + ((item === null || item === void 0 ? void 0 : item.price) || (item === null || item === void 0 ? void 0 : item.add_price)) * item.num;
	}, 0);
	return parseFloat(_price);
};
const setNewCartValue = (cartValue, newProducts) => {
	if (!newProducts.length) return {
		isChange: false,
		value: cartValue
	};
	let isChange = false;
	let isBundleChange = false;
	let isNotFoundBundle = false;
	const notFoundProducts = [];
	const multiDayPricesCache = /* @__PURE__ */ new Map();
	const value = cartValue.map((item) => {
		var _item$_extend, _item$_extend2, _item$_extend3, _item$_extend4, _item$_extend5, _item$_extend7;
		const itemScheduleDate = ((_item$_extend = item._extend) === null || _item$_extend === void 0 ? void 0 : _item$_extend.startDate) ? dayjs(item._extend.startDate).format("YYYY-MM-DD") : "";
		const newProduct = newProducts.find((newItem) => newItem.id === item.product_id && newItem.schedule_date === itemScheduleDate);
		if (!newProduct) return item;
		let isChangePrice = newProduct.price != item.price;
		const bundleItemMap = formatBundleItemMap(newProduct);
		const variantItemMap = formatVariantItemMap(newProduct);
		const newBundle = (((_item$_extend2 = item._extend) === null || _item$_extend2 === void 0 || (_item$_extend2 = _item$_extend2.other) === null || _item$_extend2 === void 0 ? void 0 : _item$_extend2.bundle) || []).map((bundle) => {
			if (!bundleItemMap[bundle.id]) {
				isNotFoundBundle = true;
				if (!notFoundProducts.some((p) => p._id === bundle._id)) notFoundProducts.push(item);
				return bundle;
			}
			if (bundle.price != bundleItemMap[bundle.id].price) {
				isChangePrice = true;
				isBundleChange = true;
			}
			if (bundleItemMap[bundle.id].price_type === "markdown") bundleItemMap[bundle.id].price = new Decimal(bundleItemMap[bundle.id].price || 0).mul(-1).toNumber();
			const selectBundleInfo = item._extend.other.bundle.find((item) => item.id === bundle.id);
			const optionPrice = calculateTotalPrice((selectBundleInfo === null || selectBundleInfo === void 0 ? void 0 : selectBundleInfo.option) || []);
			const isEditDiscount = item.booking_id && (bundle.discount_list || []).length;
			return _objectSpread2(_objectSpread2({}, bundle), {}, {
				base_price: bundleItemMap[bundle.id].base_price,
				price: isEditDiscount ? bundle.price : new Decimal(bundleItemMap[bundle.id].price || 0).add(optionPrice).toNumber()
			});
		});
		const newVariant = (((_item$_extend3 = item._extend) === null || _item$_extend3 === void 0 || (_item$_extend3 = _item$_extend3.other) === null || _item$_extend3 === void 0 ? void 0 : _item$_extend3.variant) || []).map((variant) => {
			if (!variantItemMap[variant.id]) return variant;
			return _objectSpread2(_objectSpread2({}, variant), {}, {
				price: variantItemMap[variant.id].price,
				base_price: variantItemMap[variant.id].base_price
			});
		});
		if ((_item$_extend4 = item._extend) === null || _item$_extend4 === void 0 ? void 0 : _item$_extend4.groupId) {
			if (!multiDayPricesCache.has(item._extend.groupId)) {
				const productPrices = newProducts.filter((p) => p.id === item.product_id);
				const multiDayPrices = {};
				productPrices.forEach((priceItem) => {
					multiDayPrices[priceItem.schedule_date] = {
						total: Number(priceItem.price),
						origin_total: Number(priceItem.price),
						num: 1,
						quotation_id: priceItem.quotation_id || 0,
						start_date: priceItem.schedule_date,
						end_date: dayjs(priceItem.schedule_date).add(1, "day").format("YYYY-MM-DD")
					};
				});
				multiDayPricesCache.set(item._extend.groupId, multiDayPrices);
			}
			item._extend.multiDayPrices = multiDayPricesCache.get(item._extend.groupId);
		}
		if (!isChangePrice) return item;
		else isChange = true;
		let price = newProduct.price;
		if ((_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) {
			var _variantItemMap$item$, _variantItemMap$item$2, _item$_extend6;
			price = (_variantItemMap$item$ = (_variantItemMap$item$2 = variantItemMap[(_item$_extend6 = item._extend) === null || _item$_extend6 === void 0 || (_item$_extend6 = _item$_extend6.other) === null || _item$_extend6 === void 0 ? void 0 : _item$_extend6.product_variant_id]) === null || _variantItemMap$item$2 === void 0 ? void 0 : _variantItemMap$item$2.price) !== null && _variantItemMap$item$ !== void 0 ? _variantItemMap$item$ : newProduct.price;
		}
		const newItem = _objectSpread2(_objectSpread2({}, item), {}, {
			original_price: newProduct.original_price,
			price,
			base_price: newProduct.base_price,
			_extend: _objectSpread2(_objectSpread2({}, item._extend), {}, {
				price,
				bundle_edit: isBundleChange ? 1 : item._extend.bundle_edit,
				other: _objectSpread2(_objectSpread2({}, item._extend.other), {}, {
					option: (_item$_extend7 = item._extend) === null || _item$_extend7 === void 0 || (_item$_extend7 = _item$_extend7.other) === null || _item$_extend7 === void 0 ? void 0 : _item$_extend7.option,
					bundle: newBundle,
					variant: newVariant || []
				})
			})
		});
		const total = getProductTotalPrice(newItem);
		newItem._extend.total = total;
		newItem._extend.origin_total = total;
		return newItem;
	});
	return {
		isChange,
		value,
		isNotFoundBundle,
		notFoundProducts
	};
};
const useQuotation = (state, dispatch) => {
	var _state$client3;
	const context = useEngineContext();
	const [open, setOpen] = useState(false);
	const [products, setProducts] = useState([]);
	const cartValueRef = useRef(state.service.value || []);
	cartValueRef.current = state.service.value;
	const getCartQuotation = function() {
		var _ref = _asyncToGenerator(function* (params) {
			if (!cartValueRef.current.length) return;
			if (!(params === null || params === void 0 ? void 0 : params.customer_id)) return;
			const queryData = cartValueRef.current.filter((item) => !item.isCustomItem).map((item) => {
				var _item$_extend8;
				return {
					product_id: item.product_id,
					schedule_date: ((_item$_extend8 = item._extend) === null || _item$_extend8 === void 0 ? void 0 : _item$_extend8.startDate) ? dayjs(item._extend.startDate).format("YYYY-MM-DD") : params === null || params === void 0 ? void 0 : params.schedule_date
				};
			});
			if (!queryData.length) return;
			return (yield getNormalAndMultiDayProductPrice({
				customer_id: params === null || params === void 0 ? void 0 : params.customer_id,
				data: queryData
			})).data;
		});
		return function getCartQuotation(_x) {
			return _ref.apply(this, arguments);
		};
	}();
	const currentDate = useMemo(() => {
		return state.date.value.format("YYYY-MM-DD");
	}, [state.date.value]);
	const updateCartQuotation = function() {
		var _ref2 = _asyncToGenerator(function* (params) {
			const data = yield getCartQuotation(params);
			if (!data || !data.length) return;
			const { isChange, value: newCartValue, isNotFoundBundle, notFoundProducts } = setNewCartValue(cartValueRef.current, data);
			if (isNotFoundBundle) {
				setProducts(notFoundProducts);
				setOpen(true);
				return;
			}
			if (!isChange) return;
			dispatch({
				type: "setService",
				payload: {
					value: newCartValue,
					edit: true
				}
			});
		});
		return function updateCartQuotation(_x2) {
			return _ref2.apply(this, arguments);
		};
	}();
	const isEditClientOrDate = useMemo(() => {
		var _state$client, _state$date;
		return (state === null || state === void 0 || (_state$client = state.client) === null || _state$client === void 0 ? void 0 : _state$client.edit) || (state === null || state === void 0 || (_state$date = state.date) === null || _state$date === void 0 ? void 0 : _state$date.edit);
	}, [state]);
	useEffect(() => {
		var _context$appHelper, _context$appHelper$ge, _context$appHelper2, _context$appHelper2$g, _state$client2;
		const isQuotation = context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.utils) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.businessUtils) === null || _context$appHelper === void 0 || (_context$appHelper$ge = _context$appHelper.getAppByModal) === null || _context$appHelper$ge === void 0 ? void 0 : _context$appHelper$ge.call(_context$appHelper, "quotation");
		const isHolidayQuotation = context === null || context === void 0 || (_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 || (_context$appHelper2 = _context$appHelper2.utils) === null || _context$appHelper2 === void 0 || (_context$appHelper2 = _context$appHelper2.businessUtils) === null || _context$appHelper2 === void 0 || (_context$appHelper2$g = _context$appHelper2.getAppByModal) === null || _context$appHelper2$g === void 0 ? void 0 : _context$appHelper2$g.call(_context$appHelper2, "holidayquotation");
		if (!isQuotation && !isHolidayQuotation || !isEditClientOrDate) return;
		updateCartQuotation({
			customer_id: (_state$client2 = state.client) === null || _state$client2 === void 0 || (_state$client2 = _state$client2.value) === null || _state$client2 === void 0 ? void 0 : _state$client2.id,
			schedule_date: currentDate
		});
	}, [
		(_state$client3 = state.client) === null || _state$client3 === void 0 || (_state$client3 = _state$client3.value) === null || _state$client3 === void 0 ? void 0 : _state$client3.id,
		currentDate,
		isEditClientOrDate
	]);
	return { dom: useMemo(() => {
		return /* @__PURE__ */ React.createElement(PisellModal.Information, {
			open,
			platform: "pc",
			title: locales.getText("pisell2.text.quotation.product.change.title"),
			describe: /* @__PURE__ */ React.createElement("div", null, locales.getText("pisell2.text.quotation.product.change.describe"), products.map((item) => /* @__PURE__ */ React.createElement("div", null, item === null || item === void 0 ? void 0 : item.product_title))),
			okText: locales.getText("pisell2.text.ok"),
			closable: true,
			cancelVisible: false,
			onOk: () => setOpen(false),
			onCancel: () => setOpen(false)
		});
	}, [open, products]) };
};
//#endregion
export { useQuotation as default };
