const require_runtime = require("../../../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_utils = require("../../../../plus/clientName/utils.js");
const require_utils$1 = require("../../utils.js");
const require_model = require("../../info/model.js");
const require_useEngineContext = require("../../../../hooks/useEngineContext.js");
const require_useTranslationOriginal = require("../../../../hooks/useTranslationOriginal.js");
const require_IsActiveContext = require("../../../ticketBooking/context/IsActiveContext.js");
const require_useCustomer = require("../../../ticketBooking/hooks/pisellos/useCustomer.js");
const require_locales = require("./locales.js");
const require_index = require("../../../../plus/clientCard/index.js");
const require_index$1 = require("../../../../plus/clinetSearch/index.js");
const require_useScanCustomer = require("../../../ticketBooking/hooks/pisellos/useScanCustomer.js");
const require_utils$2 = require("./utils.js");
const require_serve = require("../serve.js");
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_utils = require("@pisell/utils");
let lodash = require("lodash");
let _pisell_materials = require("@pisell/materials");
let ahooks = require("ahooks");
require("./index.less");
//#region src/components/booking/info2/cartClientCard/index.tsx
const CartClientCard = (0, react.forwardRef)(({ clientCardProps = {}, beforeSwitchModalOpen, onClientChange }, ref) => {
	var _context$appHelper, _state$bookingConfig2, _state$client2;
	const clientSearchRef = (0, react.useRef)(null);
	const [searchModalVisible, setSearchModalVisible] = (0, react.useState)(false);
	const [switchModalVisible, setSwitchModalVisible] = (0, react.useState)(false);
	const [pendingCustomer, setPendingCustomer] = (0, react.useState)(null);
	const { state, dispatch } = (0, react.useContext)(require_model.Context);
	const translationOriginal = require_useTranslationOriginal.default();
	const [keyword, setKeyword] = (0, react.useState)("");
	const keywordRef = (0, react.useRef)("");
	const isActive = require_IsActiveContext.useIsActive();
	const [resultLoading, setResultLoading] = (0, react.useState)(false);
	keywordRef.current = keyword;
	const Toast = (0, _pisell_materials.useToast)();
	const { openScan, closeScan } = require_useScanCustomer.default();
	const context = require_useEngineContext.default();
	_pisell_utils.locales.init(require_locales.default, ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.utils) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.storage) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.get("umi_locale")) || "en");
	const boardConfig = (0, react.useMemo)(() => {
		var _state$bookingConfig;
		return (state === null || state === void 0 || (_state$bookingConfig = state.bookingConfig) === null || _state$bookingConfig === void 0 || (_state$bookingConfig = _state$bookingConfig.config) === null || _state$bookingConfig === void 0 || (_state$bookingConfig = _state$bookingConfig.basic) === null || _state$bookingConfig === void 0 ? void 0 : _state$bookingConfig.appointment_subject) || {};
	}, [state === null || state === void 0 || (_state$bookingConfig2 = state.bookingConfig) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.config) === null || _state$bookingConfig2 === void 0 ? void 0 : _state$bookingConfig2.basic]);
	const { customers, loading, pagination, changePage, selectCustomer, addCustomerToFirst, initLoad, hasMore, loadMore } = require_useCustomer.useCustomer({ changeCustomerToGlobalState: (0, ahooks.useMemoizedFn)((value) => {
		var _state$client, _state$service;
		const beforeValue = state === null || state === void 0 || (_state$client = state.client) === null || _state$client === void 0 ? void 0 : _state$client.value;
		dispatch({
			type: "setClient",
			payload: {
				value,
				edit: true
			}
		});
		if ((beforeValue === null || beforeValue === void 0 ? void 0 : beforeValue.id) === (value === null || value === void 0 ? void 0 : value.id)) return;
		if (state === null || state === void 0 || (_state$service = state.service) === null || _state$service === void 0 || (_state$service = _state$service.value) === null || _state$service === void 0 ? void 0 : _state$service.length) dispatch({
			type: "setService",
			payload: { value: state.service.value.map((item) => require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, item), {}, { _extend: require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, item._extend), {}, { holder_id: [] }) })) }
		});
	}) });
	const selectedCustomer = (_state$client2 = state.client) === null || _state$client2 === void 0 ? void 0 : _state$client2.value;
	const handleSearchClient = function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (keyword) {
			var _clientSearchRef$curr, _clientSearchRef$curr2;
			yield initLoad(keyword, boardConfig === null || boardConfig === void 0 ? void 0 : boardConfig.form_id);
			(_clientSearchRef$curr = clientSearchRef.current) === null || _clientSearchRef$curr === void 0 || (_clientSearchRef$curr2 = _clientSearchRef$curr.resetScrollPosition) === null || _clientSearchRef$curr2 === void 0 || _clientSearchRef$curr2.call(_clientSearchRef$curr);
		});
		return function handleSearchClient(_x) {
			return _ref.apply(this, arguments);
		};
	}();
	const _debouncedSearch = (0, ahooks.useDebounceFn)(function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (_keyword, formId) {
			var _clientSearchRef$curr3, _clientSearchRef$curr4;
			yield initLoad(keyword, formId);
			(_clientSearchRef$curr3 = clientSearchRef.current) === null || _clientSearchRef$curr3 === void 0 || (_clientSearchRef$curr4 = _clientSearchRef$curr3.resetScrollPosition) === null || _clientSearchRef$curr4 === void 0 || _clientSearchRef$curr4.call(_clientSearchRef$curr3);
		});
		return function(_x2, _x3) {
			return _ref2.apply(this, arguments);
		};
	}(), { wait: 500 });
	(0, react.useEffect)(() => {
		_debouncedSearch.run(keyword, boardConfig === null || boardConfig === void 0 ? void 0 : boardConfig.form_id);
	}, [keyword, boardConfig === null || boardConfig === void 0 ? void 0 : boardConfig.form_id]);
	(0, react.useEffect)(() => {
		if (state.action) state.action({
			type: "pisell1.registerPlugin",
			data: { pluginList: ["CustomerDetailPlugin"] }
		});
	}, []);
	const handleScanCustomer = (customer) => {
		if (customer === null || customer === void 0 ? void 0 : customer.scanCode) setKeyword(customer.scanCode);
	};
	(0, react.useEffect)(() => {
		if (searchModalVisible) openScan(handleScanCustomer);
		else {
			closeScan();
			if (keywordRef.current) setKeyword("");
		}
	}, [searchModalVisible, initLoad]);
	const handleAddClient = () => {
		setSearchModalVisible(true);
	};
	const handleChangeClient = (data) => {
		setSearchModalVisible(true);
	};
	const handleRemoveClient = (data) => {
		selectCustomer(null);
	};
	const handleViewClient = (data) => {
		const newSelectedCustomer = (0, lodash.cloneDeep)(selectedCustomer);
		state.action({
			type: "pisell1.handleOpenCustomerModal",
			data: { id: state.client.value.id },
			callback: (data) => {
				console.log("data>>>>>", data);
				selectCustomer(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, newSelectedCustomer || {}), {}, {
					display_name: (data === null || data === void 0 ? void 0 : data.display_name) || "",
					email: (data === null || data === void 0 ? void 0 : data.email) || "",
					phone: (data === null || data === void 0 ? void 0 : data.phone) || "",
					nickname: (data === null || data === void 0 ? void 0 : data.nickname) || "",
					country_calling_code: (data === null || data === void 0 ? void 0 : data.country_calling_code) || "",
					first_name: (data === null || data === void 0 ? void 0 : data.first_name) || "",
					last_name: (data === null || data === void 0 ? void 0 : data.last_name) || "",
					contacts_info: (data === null || data === void 0 ? void 0 : data.contacts_info) || null
				}));
				if (JSON.stringify((newSelectedCustomer === null || newSelectedCustomer === void 0 ? void 0 : newSelectedCustomer.contacts_info) || {}) !== JSON.stringify((data === null || data === void 0 ? void 0 : data.contacts_info) || {})) dispatch({
					type: "setContactsInfo",
					payload: {
						value: (data === null || data === void 0 ? void 0 : data.contacts_info) || {},
						client_id: data === null || data === void 0 ? void 0 : data.id
					}
				});
				handleSearchClient("");
			}
		});
	};
	const handleModalCancel = () => {
		setSearchModalVisible(false);
	};
	const handleAddClientSuccess = (record, isChecked) => {
		addCustomerToFirst(record);
		if (isChecked) {
			selectCustomer(record);
			setSearchModalVisible(false);
		}
	};
	const resultProps = (0, react.useMemo)(() => {
		return {
			loading,
			onChange: (pagination) => {
				changePage(pagination.current, pagination.pageSize);
			},
			pagination: {
				pageSize: pagination.pageSize,
				current: pagination.page,
				total: pagination.total,
				size: "default",
				showSizeChanger: false
			}
		};
	}, [pagination, loading]);
	const handleSetClient = (0, ahooks.useMemoizedFn)(function() {
		var _ref3 = require_asyncToGenerator._asyncToGenerator(function* (record, options) {
			var _options$fullData, _options$fullData2;
			if (require_utils$1.isWalkIn(selectedCustomer === null || selectedCustomer === void 0 ? void 0 : selectedCustomer.id) && (options === null || options === void 0 || (_options$fullData = options.fullData) === null || _options$fullData === void 0 ? void 0 : _options$fullData.searchType) === "walletPass" && (options === null || options === void 0 || (_options$fullData2 = options.fullData) === null || _options$fullData2 === void 0 ? void 0 : _options$fullData2.scanCode)) {
				var _options$fullData3;
				window.dispatchEvent(new CustomEvent("onScanWallPassCode", { detail: { code: options === null || options === void 0 || (_options$fullData3 = options.fullData) === null || _options$fullData3 === void 0 ? void 0 : _options$fullData3.scanCode } }));
				return;
			}
			if (require_utils$1.isWalkIn(selectedCustomer === null || selectedCustomer === void 0 ? void 0 : selectedCustomer.id)) {
				var _Toast$success;
				selectCustomer(record);
				setSearchModalVisible(false);
				Toast === null || Toast === void 0 || (_Toast$success = Toast.success) === null || _Toast$success === void 0 || _Toast$success.call(Toast, _pisell_utils.locales.getText("pisell2.text.add-client-success"));
				return;
			}
			if ((selectedCustomer === null || selectedCustomer === void 0 ? void 0 : selectedCustomer.id) === (record === null || record === void 0 ? void 0 : record.id)) {
				setSearchModalVisible(false);
				return;
			}
			if (beforeSwitchModalOpen) try {
				if ((yield beforeSwitchModalOpen()) === false) return;
			} catch (error) {
				console.error("beforeSwitchModalOpen callback error:", error);
				return;
			}
			setPendingCustomer(record);
			setSwitchModalVisible(true);
		});
		return function(_x4, _x5) {
			return _ref3.apply(this, arguments);
		};
	}());
	const handleConfirmSwitch = () => {
		if (pendingCustomer) selectCustomer(pendingCustomer);
		setSwitchModalVisible(false);
		setPendingCustomer(null);
		setSearchModalVisible(false);
		onClientChange === null || onClientChange === void 0 || onClientChange(pendingCustomer);
	};
	const handleCancelSwitch = () => {
		setSwitchModalVisible(false);
		setPendingCustomer(null);
	};
	(0, react.useMemo)(() => {
		if (isActive) require_utils$2.setHandleSetClient(handleSetClient);
	}, [isActive]);
	const tags = (0, react.useMemo)(() => {
		var _latest_wallet_detail;
		if (!selectedCustomer) return;
		const { latest_wallet_detail } = selectedCustomer;
		const _name = latest_wallet_detail === null || latest_wallet_detail === void 0 || (_latest_wallet_detail = latest_wallet_detail.wallet) === null || _latest_wallet_detail === void 0 ? void 0 : _latest_wallet_detail.name;
		if (_name) return [{
			children: translationOriginal(_name),
			color: "gold"
		}];
	}, [selectedCustomer]);
	(0, react.useImperativeHandle)(ref, () => ({ handleSetClient }));
	const handleRowClick = (0, ahooks.useMemoizedFn)(function() {
		var _ref4 = require_asyncToGenerator._asyncToGenerator(function* (record, options) {
			try {
				if ((state === null || state === void 0 ? void 0 : state.isFranchisee) && (record === null || record === void 0 ? void 0 : record.is_franchisor_customer) == 1) {
					setResultLoading(true);
					let franchiseeCustomerId = record === null || record === void 0 ? void 0 : record.franchisee_customer_id;
					if (!franchiseeCustomerId) {
						const res = yield require_serve.getFranchiseeCustomer({ franchisor_customer_id: record.id });
						franchiseeCustomerId = res === null || res === void 0 ? void 0 : res.franchisee_customer_id;
					}
					if (franchiseeCustomerId) {
						var _listRes$list;
						const listRes = yield require_serve.getCustomerList({
							sort_by: "id",
							with: [
								"latestWalletDetail.wallet",
								"contactsInfo",
								"formRecord"
							],
							search_wallet_flag: 1,
							search_wallet_pass_flag: 1,
							skip: 1,
							num: 20,
							customer_ids: [franchiseeCustomerId]
						});
						if (listRes === null || listRes === void 0 || (_listRes$list = listRes.list) === null || _listRes$list === void 0 ? void 0 : _listRes$list.length) yield handleSetClient(listRes === null || listRes === void 0 ? void 0 : listRes.list[0], options);
					}
					return;
				}
				yield handleSetClient(record, options);
			} catch (error) {
				console.error("handleRowClick error:", error);
			} finally {
				setResultLoading(false);
			}
		});
		return function(_x6, _x7) {
			return _ref4.apply(this, arguments);
		};
	}());
	return /* @__PURE__ */ react.default.createElement(react.default.Fragment, null, /* @__PURE__ */ react.default.createElement(require_index.default, {
		dataSource: selectedCustomer,
		onAddClient: handleAddClient,
		onChangeClient: handleChangeClient,
		onRemoveClient: handleRemoveClient,
		onViewClient: handleViewClient,
		style: require_objectSpread2._objectSpread2({
			border: "solid",
			borderColor: "#D0D5DD",
			borderWidth: "1px",
			minHeight: 64,
			display: "flex",
			boxSizing: "border-box",
			height: 64
		}, clientCardProps.style || {}),
		avatar: require_objectSpread2._objectSpread2({
			size: "lg",
			useTextAvatar: !(selectedCustomer === null || selectedCustomer === void 0 ? void 0 : selectedCustomer.cover)
		}, clientCardProps.avatar || {}),
		tag: { placement: "inline" },
		tags,
		dropdown: clientCardProps.dropdown
	}), /* @__PURE__ */ react.default.createElement(require_index$1.default, {
		ref: clientSearchRef,
		loading,
		dataSource: customers,
		onSearch: handleSearchClient,
		keyword,
		onKeywordChange: (_keyword) => {
			setKeyword(_keyword);
		},
		onRowClick: handleRowClick,
		containerProps: {
			open: searchModalVisible,
			onCancel: handleModalCancel,
			destroyOnClose: true,
			width: 880
		},
		isShowNewButton: false,
		resultProps,
		onAddClient: handleAddClientSuccess,
		onLoadMore: loadMore,
		hasMore,
		state,
		resultLoading
	}), /* @__PURE__ */ react.default.createElement(_pisell_materials.PisellModal, {
		className: "cart-client-card_switch-modal",
		open: switchModalVisible,
		okText: _pisell_utils.locales.getText("pisell2.text.switch-account"),
		cancelText: _pisell_utils.locales.getText("pisell2.text.cancel"),
		onOk: handleConfirmSwitch,
		onCancel: handleCancelSwitch,
		closable: false,
		header: null,
		footerDivider: false,
		destroyOnClose: true
	}, /* @__PURE__ */ react.default.createElement("div", { style: {
		textAlign: "center",
		fontWeight: 600,
		paddingTop: 24
	} }, _pisell_utils.locales.getText("pisell2.text.cart-client-card")(require_utils.getClientName(pendingCustomer)))));
});
//#endregion
exports.default = CartClientCard;
