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 { getClientName } from "../../../../plus/clientName/utils.js";
import { isWalkIn } from "../../utils.js";
import { Context } from "../../info/model.js";
import useEngineContext from "../../../../hooks/useEngineContext.js";
import useTranslationOriginal from "../../../../hooks/useTranslationOriginal.js";
import { useIsActive } from "../../../ticketBooking/context/IsActiveContext.js";
import { useCustomer } from "../../../ticketBooking/hooks/pisellos/useCustomer.js";
import locales_default from "./locales.js";
import ClientCard from "../../../../plus/clientCard/index.js";
import ClientSearch from "../../../../plus/clinetSearch/index.js";
import useScanCustomer from "../../../ticketBooking/hooks/pisellos/useScanCustomer.js";
import { setHandleSetClient } from "./utils.js";
import { getCustomerList, getFranchiseeCustomer } from "../serve.js";
import React, { forwardRef, useContext, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { locales } from "@pisell/utils";
import { cloneDeep } from "lodash";
import { PisellModal, useToast } from "@pisell/materials";
import { useDebounceFn, useMemoizedFn } from "ahooks";
import "./index.less";
//#region src/components/booking/info2/cartClientCard/index.tsx
const CartClientCard = forwardRef(({ clientCardProps = {}, beforeSwitchModalOpen, onClientChange }, ref) => {
	var _context$appHelper, _state$bookingConfig2, _state$client2;
	const clientSearchRef = useRef(null);
	const [searchModalVisible, setSearchModalVisible] = useState(false);
	const [switchModalVisible, setSwitchModalVisible] = useState(false);
	const [pendingCustomer, setPendingCustomer] = useState(null);
	const { state, dispatch } = useContext(Context);
	const translationOriginal = useTranslationOriginal();
	const [keyword, setKeyword] = useState("");
	const keywordRef = useRef("");
	const isActive = useIsActive();
	const [resultLoading, setResultLoading] = useState(false);
	keywordRef.current = keyword;
	const Toast = useToast();
	const { openScan, closeScan } = useScanCustomer();
	const context = useEngineContext();
	locales.init(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 = 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 } = useCustomer({ changeCustomerToGlobalState: 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) => _objectSpread2(_objectSpread2({}, item), {}, { _extend: _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 = _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 = useDebounceFn(function() {
		var _ref2 = _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 });
	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]);
	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);
	};
	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 = cloneDeep(selectedCustomer);
		state.action({
			type: "pisell1.handleOpenCustomerModal",
			data: { id: state.client.value.id },
			callback: (data) => {
				console.log("data>>>>>", data);
				selectCustomer(_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 = 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 = useMemoizedFn(function() {
		var _ref3 = _asyncToGenerator(function* (record, options) {
			var _options$fullData, _options$fullData2;
			if (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 (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, 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);
	};
	useMemo(() => {
		if (isActive) setHandleSetClient(handleSetClient);
	}, [isActive]);
	const tags = 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]);
	useImperativeHandle(ref, () => ({ handleSetClient }));
	const handleRowClick = useMemoizedFn(function() {
		var _ref4 = _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 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 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.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(ClientCard, {
		dataSource: selectedCustomer,
		onAddClient: handleAddClient,
		onChangeClient: handleChangeClient,
		onRemoveClient: handleRemoveClient,
		onViewClient: handleViewClient,
		style: _objectSpread2({
			border: "solid",
			borderColor: "#D0D5DD",
			borderWidth: "1px",
			minHeight: 64,
			display: "flex",
			boxSizing: "border-box",
			height: 64
		}, clientCardProps.style || {}),
		avatar: _objectSpread2({
			size: "lg",
			useTextAvatar: !(selectedCustomer === null || selectedCustomer === void 0 ? void 0 : selectedCustomer.cover)
		}, clientCardProps.avatar || {}),
		tag: { placement: "inline" },
		tags,
		dropdown: clientCardProps.dropdown
	}), /* @__PURE__ */ React.createElement(ClientSearch, {
		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.createElement(PisellModal, {
		className: "cart-client-card_switch-modal",
		open: switchModalVisible,
		okText: locales.getText("pisell2.text.switch-account"),
		cancelText: locales.getText("pisell2.text.cancel"),
		onOk: handleConfirmSwitch,
		onCancel: handleCancelSwitch,
		closable: false,
		header: null,
		footerDivider: false,
		destroyOnClose: true
	}, /* @__PURE__ */ React.createElement("div", { style: {
		textAlign: "center",
		fontWeight: 600,
		paddingTop: 24
	} }, locales.getText("pisell2.text.cart-client-card")(getClientName(pendingCustomer)))));
});
//#endregion
export { CartClientCard as default };
