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 { getProductDetail } from "../../../info/service/serve.js";
import { getMultiDay, getProductExtend, isMultiDayProduct } from "./utils.js";
import { getIsShowNumber } from "../../../../ticketBooking/utils/index.js";
import { concatBookings, createBookingItemsByGroup } from "../../../info/service2/Group/utils.js";
import { isNormalProductByDurationSchedule } from "../../../info/service2/utils.js";
import { formatProductListByCategory, getIsEject, getIsOnlySession, getMainPrice, getProductTotalPrice, isSessionProduct, request } from "../../../utils.js";
import { getIsBundleOrCombination } from "../../../info/utils.js";
import { Context } from "../../../info/model.js";
import Drawer$1 from "../../../components/drawer/index.js";
import useEngineContext from "../../../../../hooks/useEngineContext.js";
import TabProduct from "../../../components/TabProduct/index.js";
import React, { useContext, useEffect, useMemo, useRef, useState } from "react";
import { Input, Skeleton } from "antd";
import { getUniqueId, locales } from "@pisell/utils";
import SearchLg from "@pisell/icon/es/SearchLg";
import { useUpdateEffect } from "ahooks";
import "../../../info/service/addService/index.less";
//#region src/components/booking/info2/service/addService/index.tsx
const shopList = [
	2886,
	4422,
	5538,
	6930,
	6814,
	6813,
	6812,
	6087,
	6303,
	6080,
	6978,
	7386,
	6848,
	6305
];
const Info = (props) => {
	var _state$client2, _state$service3, _state$service5, _state$service6;
	const { onEdit, drawerProps, renderMode } = props;
	const [search, setSearch] = useState("");
	let { state, dispatch } = useContext(Context);
	const [loading, setLoading] = useState(false);
	const searchRef = useRef();
	const context = useEngineContext();
	state = state || (props === null || props === void 0 ? void 0 : props.state);
	dispatch = dispatch || (props === null || props === void 0 ? void 0 : props.dispatch);
	request.setRequest(context.appHelper.utils.request);
	/**
	* @title: 客户id
	* @description:
	* @param {*} useMemo
	* @return {*}
	* @Author: WangHan
	* @Date: 2024-12-24 10:33
	*/
	const customerId = useMemo(() => {
		var _state$client;
		return ((_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]);
	console.log(customerId, "customerIdcustomerId");
	/**
	* @title: 如果商品只有一个, 则自动设置默认商品
	* @description:
	* @param {any} list
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-05-14 13:55
	*/
	const setDefaultService = function() {
		var _ref = _asyncToGenerator(function* (list) {
			if (state.renderType !== "eventBooking") return;
			if (state.bookingId) return;
			if (list.length !== 1) return;
			let _list = [...state.service.value];
			if (_list.length !== 0) return;
			setLoading(true);
			let product = list[0];
			const isBundleOrCombination = getIsBundleOrCombination((yield getProductDetail(product.id, {
				schedule_date: state.date.value.format("YYYY-MM-DD"),
				open_deposit: 1
			})).data);
			setLoading(false);
			if (isBundleOrCombination) return;
			let _item = _objectSpread2(_objectSpread2({}, product), {}, {
				product_id: product.id,
				_id: getUniqueId(),
				_extend: {
					start_date: state.date.value,
					startDate: state.date.value,
					endDate: state.date.value,
					start_time: "00:00:00",
					duration: 10,
					quantity: 1,
					price: product.price,
					total: product.price,
					origin_total: product.price,
					product_name: product.title
				}
			});
			_list.push(_item);
			dispatch({
				type: "setService",
				payload: {
					value: _list,
					edit: true
				}
			});
		});
		return function setDefaultService(_x) {
			return _ref.apply(this, arguments);
		};
	}();
	const getServices = function() {
		var _ref2 = _asyncToGenerator(function* (params) {
			var _state$eventOtherPara, _state$eventOtherPara2;
			setLoading(true);
			if (state.renderType === "eventBooking" && !((_state$eventOtherPara = state.eventOtherParams) === null || _state$eventOtherPara === void 0 || (_state$eventOtherPara = _state$eventOtherPara.productIds) === null || _state$eventOtherPara === void 0 ? void 0 : _state$eventOtherPara.length)) {
				dispatch({
					type: "setService",
					payload: { services: [] }
				});
				setLoading(false);
				return;
			}
			let data = yield state.apis.getServices({
				skip: 1,
				num: 500,
				extension_type: state.renderType === "eventBooking" ? void 0 : [
					"product_appointment",
					"appointment_ticket",
					"service_product",
					"session_product",
					"session_ticket"
				],
				with: ["category", "resourceRelation"],
				ids: state.renderType === "eventBooking" ? (_state$eventOtherPara2 = state.eventOtherParams) === null || _state$eventOtherPara2 === void 0 ? void 0 : _state$eventOtherPara2.productIds : void 0,
				open_quotation: 1,
				with_schedule: 1,
				with_count: ["bundleGroup", "optionGroup"],
				order_by_string: "sort:desc",
				status: "published",
				schedule_date: params === null || params === void 0 ? void 0 : params.schedule_date,
				customer_id: params === null || params === void 0 ? void 0 : params.customer_id
			});
			setLoading(false);
			if (!state.service.addModal) setDefaultService(data === null || data === void 0 ? void 0 : data.list);
			dispatch({
				type: "setService",
				payload: { services: (data === null || data === void 0 ? void 0 : data.list) || [] }
			});
		});
		return function getServices(_x2) {
			return _ref2.apply(this, arguments);
		};
	}();
	const handleSelectService = () => {
		dispatch({
			type: "setService",
			payload: { addModal: 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);
	};
	const handleSelectProduct = (item, type) => {
		var _state$client3;
		if (!isNormalProductByDurationSchedule(item)) {
			var _state$service;
			if (!Array.isArray((_state$service = state.service) === null || _state$service === void 0 ? void 0 : _state$service.resourcesOrigin) || !state.service.resourcesOrigin.length) {
				dispatch({
					type: "setService",
					payload: _objectSpread2(_objectSpread2({}, state.service), {}, { reloadResourceModal: true })
				});
				return;
			}
		}
		const isSession = isSessionProduct(item);
		const isEject = getIsEject(item, type);
		const isOnlySession = getIsOnlySession(item);
		let lock = false;
		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: getIsShowNumber(item, state)
				},
				is_eject: isEject ? 1 : 0,
				isOnlySession,
				isOS: isSession,
				customer_id: (_state$client3 = state.client) === null || _state$client3 === void 0 || (_state$client3 = _state$client3.value) === null || _state$client3 === void 0 ? void 0 : _state$client3.id
			},
			callback: function() {
				var _ref4 = _asyncToGenerator(function* (e, extension_type, detail) {
					if (lock) return;
					lock = true;
					setTimeout(() => {
						lock = false;
					}, 2e3);
					const _detail = detail || item;
					const other = JSON.parse(JSON.stringify(e));
					other.session = e.session;
					let cacheItem = _objectSpread2(_objectSpread2({}, _detail), {}, {
						product_id: item.id,
						_id: getUniqueId(),
						_key: e.key,
						_extend: {
							start_date: state.date.value,
							quantity: (e === null || e === void 0 ? void 0 : e.quantity) || 1,
							product_name: item.title,
							other
						},
						new: 1
					});
					const isMultiDay = isMultiDayProduct(cacheItem);
					if (isMultiDay) cacheItem._extend.end_date = state.date.value.add(1, "day");
					cacheItem._extend.price = getMainPrice(cacheItem, _detail.price);
					let _total = getProductTotalPrice(cacheItem);
					cacheItem._extend.total = _total;
					cacheItem._extend.origin_total = _total;
					debugger;
					if (!!state.service.cacheItem) {
						var _state$service$cacheI;
						cacheItem._id = (_state$service$cacheI = state.service.cacheItem) === null || _state$service$cacheI === void 0 ? void 0 : _state$service$cacheI._id;
						cacheItem.new = 0;
					}
					if (renderMode === "current") cacheItem.currentDefaultTime = state.date.value.format("HH:mm");
					cacheItem = getProductExtend({
						cacheItem,
						state
					});
					const getMultiDayCacheItem = function() {
						var _ref3 = _asyncToGenerator(function* (isConcatBookings) {
							cacheItem = yield getMultiDay({
								start_date: cacheItem._extend.start_date,
								end_date: cacheItem._extend.end_date,
								state,
								cacheItem
							});
							cacheItem = createBookingItemsByGroup(cacheItem);
							if (isConcatBookings) cacheItem = concatBookings(cacheItem);
						});
						return function getMultiDayCacheItem(_x3) {
							return _ref3.apply(this, arguments);
						};
					}();
					if (state.renderType === "eventBooking" || isMultiDay) cacheItem.autoClose = false;
					if (cacheItem.autoClose) {
						cacheItem.autoClose = false;
						let newValue = [...state.service.value];
						if (!newValue.some((item) => item._id === cacheItem._id)) newValue.push(cacheItem);
						else newValue = newValue.map((item) => {
							if (item._id === cacheItem._id) return _objectSpread2(_objectSpread2({}, cacheItem), {}, { new: 0 });
							return item;
						});
						dispatch({
							type: "setService",
							payload: {
								addModal: false,
								value: newValue,
								edit: true,
								changeService: false
							}
						});
					} else {
						var _window$openBookingEd, _window;
						(_window$openBookingEd = (_window = window).openBookingEditModal) === null || _window$openBookingEd === void 0 || _window$openBookingEd.call(_window);
						if (isMultiDay) yield getMultiDayCacheItem(true);
						dispatch({
							type: "setService",
							payload: {
								editModal: true,
								cacheItem,
								addModal: !cacheItem.autoClose,
								changeService: false
							}
						});
						onEdit === null || onEdit === void 0 || onEdit(cacheItem);
					}
				});
				return function callback(_x4, _x5, _x6) {
					return _ref4.apply(this, arguments);
				};
			}()
		});
	};
	const renderList = useMemo(() => {
		var _state$service2;
		let _list = ((_state$service2 = state.service) === null || _state$service2 === void 0 ? void 0 : _state$service2.services) || [];
		const isIncludes = (str) => {
			return str.toLowerCase().indexOf(search.toLowerCase()) !== -1;
		};
		return formatProductListByCategory(_list, search ? (item) => isIncludes(item.title) : void 0);
	}, [search, (_state$service3 = state.service) === null || _state$service3 === void 0 ? void 0 : _state$service3.services]);
	const isService = useMemo(() => {
		return state.service.value.length > 0;
	}, [state.service.value]);
	useEffect(() => {
		var _context$appHelper, _context$appHelper$ge, _context$appHelper$ut, _context$appHelper$ut2, _state$service4;
		if (shopList.includes(((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.utils) === null || _context$appHelper === void 0 || (_context$appHelper$ge = _context$appHelper.getData) === null || _context$appHelper$ge === void 0 ? void 0 : _context$appHelper$ge.call(_context$appHelper, "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.closeAutoOpenService) return;
		if (state.modalOpen && !state.bookingId && state.renderType !== "eventBooking" && ((_state$service4 = state.service) === null || _state$service4 === void 0 || (_state$service4 = _state$service4.value) === null || _state$service4 === void 0 ? void 0 : _state$service4.length) === 0) setTimeout(() => {
			handleSelectService();
		}, 10);
	}, [
		state.modalOpen,
		state.bookingId,
		(_state$service5 = state.service) === null || _state$service5 === void 0 ? void 0 : _state$service5.value
	]);
	const showAddButton = useMemo(() => {
		return !state.disabledEdit && !state.channelDisabledEdit;
	}, [state.disabledEdit, state.channelDisabledEdit]);
	const currentDate = useMemo(() => {
		return state.date.value.format("YYYY-MM-DD");
	}, [state.date.value]);
	useUpdateEffect(() => {
		if (state.service.addModal) {
			getServices({
				schedule_date: currentDate,
				customer_id: customerId
			});
			setSearch("");
		}
	}, [
		state.service.addModal,
		currentDate,
		customerId
	]);
	useEffect(() => {
		if (renderMode === "current") getServices({
			schedule_date: currentDate,
			customer_id: customerId
		});
	}, [
		renderMode,
		currentDate,
		customerId
	]);
	useEffect(() => {
		if (state.renderType === "eventBooking" && state.modalOpen) getServices({
			schedule_date: currentDate,
			customer_id: customerId
		});
	}, [
		state.renderType,
		state.modalOpen,
		currentDate,
		customerId
	]);
	const addButton = useMemo(() => {
		if (state.isBookingCreatePage) return /* @__PURE__ */ React.createElement("div", { style: { height: 20 } });
		return null;
	}, [
		state.renderType,
		showAddButton,
		isService,
		state.service.value,
		loading
	]);
	const isRenderCurrent = useMemo(() => {
		return renderMode === "current";
	}, [renderMode]);
	const 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);
		}
	}));
	const content = /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-service-body" }, /* @__PURE__ */ React.createElement(TabProduct, {
		list: renderList,
		amountSymbol: state.amountSymbol,
		onChange: handleSelectProduct,
		scrollDom: isRenderCurrent ? ".pisell-lowcode__booking-vertical-add-service-wrap" : ".booking-server-wrap .pisell-lowcode-drawer-body "
	}));
	if (isRenderCurrent) return /* @__PURE__ */ React.createElement("div", {
		className: "pisell-lowcode__booking-vertical-add-service-wrap",
		style: {
			width: "100%",
			height: "100%",
			overflow: "auto"
		}
	}, header, content);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, ((_state$service6 = state.service) === null || _state$service6 === void 0 || (_state$service6 = _state$service6.cacheItem) === null || _state$service6 === void 0 ? void 0 : _state$service6.autoClose) && /* @__PURE__ */ React.createElement(Skeleton, {
		loading: true,
		active: true,
		round: true
	}), addButton, /* @__PURE__ */ React.createElement(Drawer$1, _objectSpread2({
		titleNoWrap: true,
		open: state.service.addModal && !state.isBookingCreatePage,
		title: locales.getText("pisell2.text.select-service"),
		rootClassName: "booking-server-wrap",
		onClose: () => {
			dispatch({
				type: "setService",
				payload: {
					addModal: false,
					changeService: false
				}
			});
		},
		header
	}, drawerProps || {}), content));
};
//#endregion
export { Info as default };
