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 { _objectWithoutProperties } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import useEngineContext from "../../../../hooks/useEngineContext.js";
import SearchSection from "../../../../pro/comprehensiveSearch/components/searchSection/index.js";
import { ClientSelector } from "../../../../plus/saleDetail/components/Client/ClientSelector.js";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { locales } from "@pisell/utils";
import { Icon, useToast } from "@pisell/materials";
import { useDebounceFn } from "ahooks";
import "./index.less";
//#region src/components/checkout/components/SearchAndClientModule/index.tsx
const _excluded = ["customer"];
const DEFAULT_CUSTOMER_LIST_STATE = {
	list: [],
	pagination: {
		page: 1,
		pageSize: 20,
		total: 0
	},
	hasMore: false
};
function readCustomerListFromResult(result) {
	var _result$data;
	const data = (_result$data = result === null || result === void 0 ? void 0 : result.data) !== null && _result$data !== void 0 ? _result$data : result;
	if (Array.isArray(data)) return data;
	if (Array.isArray(data === null || data === void 0 ? void 0 : data.list)) return data.list;
	if (Array.isArray(data === null || data === void 0 ? void 0 : data.customerList)) return data.customerList;
	if (Array.isArray(result === null || result === void 0 ? void 0 : result.list)) return result.list;
	if (Array.isArray(result === null || result === void 0 ? void 0 : result.customerList)) return result.customerList;
	return [];
}
function readCustomerListState(baseSales) {
	var _baseSales$getCustome, _baseSales$getCustome2, _state$total, _baseSales$hasMoreCus;
	if (!baseSales) return DEFAULT_CUSTOMER_LIST_STATE;
	const state = ((_baseSales$getCustome = baseSales.getCustomerState) === null || _baseSales$getCustome === void 0 ? void 0 : _baseSales$getCustome.call(baseSales)) || {};
	const fallbackList = ((_baseSales$getCustome2 = baseSales.getCustomers) === null || _baseSales$getCustome2 === void 0 ? void 0 : _baseSales$getCustome2.call(baseSales)) || [];
	const list = state.customerList || state.list || state.customers || fallbackList;
	const page = state.currentPage || state.page || 1;
	const pageSize = state.pageSize || 20;
	const total = (_state$total = state.total) !== null && _state$total !== void 0 ? _state$total : list.length;
	const hasMore = typeof state.hasMore === "boolean" ? state.hasMore : Boolean((_baseSales$hasMoreCus = baseSales.hasMoreCustomers) === null || _baseSales$hasMoreCus === void 0 ? void 0 : _baseSales$hasMoreCus.call(baseSales));
	return {
		list,
		pagination: {
			page,
			pageSize,
			total
		},
		hasMore
	};
}
function mergeCustomerListResult(baseSales, result) {
	var _ref, _result$total, _result$data2;
	const nextState = readCustomerListState(baseSales);
	const resultList = readCustomerListFromResult(result);
	if (!resultList.length) return nextState;
	return _objectSpread2(_objectSpread2({}, nextState), {}, {
		list: resultList,
		pagination: _objectSpread2(_objectSpread2({}, nextState.pagination), {}, { total: (_ref = (_result$total = result === null || result === void 0 ? void 0 : result.total) !== null && _result$total !== void 0 ? _result$total : result === null || result === void 0 || (_result$data2 = result.data) === null || _result$data2 === void 0 ? void 0 : _result$data2.total) !== null && _ref !== void 0 ? _ref : nextState.pagination.total })
	});
}
function readCurrentCustomer(baseSales, propClient) {
	var _baseSales$getCustome3, _baseSales$getOrderCu, _baseSales$getOrderSn;
	if ((propClient === null || propClient === void 0 ? void 0 : propClient.id) || (propClient === null || propClient === void 0 ? void 0 : propClient.customer_id) || (propClient === null || propClient === void 0 ? void 0 : propClient.display_name) || (propClient === null || propClient === void 0 ? void 0 : propClient.name)) return propClient;
	return (baseSales === null || baseSales === void 0 || (_baseSales$getCustome3 = baseSales.getCustomer) === null || _baseSales$getCustome3 === void 0 ? void 0 : _baseSales$getCustome3.call(baseSales)) || (baseSales === null || baseSales === void 0 || (_baseSales$getOrderCu = baseSales.getOrderCustomerSnapshot) === null || _baseSales$getOrderCu === void 0 ? void 0 : _baseSales$getOrderCu.call(baseSales)) || (baseSales === null || baseSales === void 0 || (_baseSales$getOrderSn = baseSales.getOrderSnapshot) === null || _baseSales$getOrderSn === void 0 || (_baseSales$getOrderSn = _baseSales$getOrderSn.call(baseSales)) === null || _baseSales$getOrderSn === void 0 || (_baseSales$getOrderSn = _baseSales$getOrderSn.tempOrder) === null || _baseSales$getOrderSn === void 0 || (_baseSales$getOrderSn = _baseSales$getOrderSn._extend) === null || _baseSales$getOrderSn === void 0 ? void 0 : _baseSales$getOrderSn.customerSnapshot) || propClient || null;
}
function extractContactsInfo(customer) {
	const contactsInfo = customer === null || customer === void 0 ? void 0 : customer.contacts_info;
	if (!contactsInfo) return null;
	return contactsInfo.value || contactsInfo;
}
const SearchAndClientModule = (props) => {
	var _context$appHelper2, _context$appHelper4;
	const { disabledSwitch, clientInfo, onSearch, onClientChange, baseSales: propBaseSales, baseSalesModuleName } = props;
	const [value, setValue] = useState("");
	const [loading, setLoading] = useState(false);
	const [customerLoading, setCustomerLoading] = useState(false);
	const [customerLoadingMore, setCustomerLoadingMore] = useState(false);
	const [customerListState, setCustomerListState] = useState(DEFAULT_CUSTOMER_LIST_STATE);
	const [customerVersion, setCustomerVersion] = useState(0);
	const clientSelectorRef = useRef(null);
	const context = useEngineContext();
	const Toast = useToast();
	const baseSales = useMemo(() => {
		var _context$appHelper, _context$appHelper$ge;
		if (propBaseSales) return propBaseSales;
		if (!baseSalesModuleName) return null;
		return ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.utils) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.pisellos) === null || _context$appHelper === void 0 || (_context$appHelper$ge = _context$appHelper.getModule) === null || _context$appHelper$ge === void 0 ? void 0 : _context$appHelper$ge.call(_context$appHelper, baseSalesModuleName)) || null;
	}, [
		baseSalesModuleName,
		(_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 || (_context$appHelper2 = _context$appHelper2.utils) === null || _context$appHelper2 === void 0 ? void 0 : _context$appHelper2.pisellos,
		propBaseSales
	]);
	const syncCustomerListState = useCallback((result) => {
		setCustomerListState(result ? mergeCustomerListResult(baseSales, result) : readCustomerListState(baseSales));
	}, [baseSales]);
	const refreshCustomerSnapshot = useCallback(() => {
		setCustomerVersion((current) => current + 1);
	}, []);
	const currentClient = useMemo(() => readCurrentCustomer(baseSales, clientInfo), [
		baseSales,
		clientInfo,
		customerVersion
	]);
	const handleSearch = useDebounceFn(function() {
		var _ref2 = _asyncToGenerator(function* (keyword) {
			if (!!keyword) {
				setLoading(true);
				try {
					const res = yield onSearch === null || onSearch === void 0 ? void 0 : onSearch(keyword);
					if (!(res === null || res === void 0 ? void 0 : res.data) || Array.isArray(res.data) && res.data.length === 0) {
						var _Toast$info;
						Toast === null || Toast === void 0 || (_Toast$info = Toast.info) === null || _Toast$info === void 0 || _Toast$info.call(Toast, locales.getText("pisell2.checkout.wallet-pass-module.no-result"));
						return;
					}
					if ("type" in res && res.type == "walletCode") {
						var _clientSelectorRef$cu, _clientSelectorRef$cu2;
						if (disabledSwitch) {
							var _Toast$info2;
							Toast === null || Toast === void 0 || (_Toast$info2 = Toast.info) === null || _Toast$info2 === void 0 || _Toast$info2.call(Toast, locales.getText("pisell2.checkout.client-card.tip.partially-paid"));
							return;
						}
						const _res$data = res.data, { customer } = _res$data, rest = _objectWithoutProperties(_res$data, _excluded);
						if (!customer) {
							var _Toast$info3;
							Toast === null || Toast === void 0 || (_Toast$info3 = Toast.info) === null || _Toast$info3 === void 0 || _Toast$info3.call(Toast, locales.getText("pisell2.checkout.wallet-pass-module.no-result"));
							return;
						}
						let _customer = _objectSpread2(_objectSpread2({}, customer), {}, { latest_wallet_detail: rest });
						(_clientSelectorRef$cu = clientSelectorRef.current) === null || _clientSelectorRef$cu === void 0 || (_clientSelectorRef$cu2 = _clientSelectorRef$cu.handleSetClient) === null || _clientSelectorRef$cu2 === void 0 || _clientSelectorRef$cu2.call(_clientSelectorRef$cu, _customer, { sameClientTip: locales.getText("pisell2.checkout.client-card.tip.same-client") });
					}
					setValue("");
				} catch (error) {} finally {
					setLoading(false);
				}
			}
		});
		return function(_x) {
			return _ref2.apply(this, arguments);
		};
	}(), {
		wait: 300,
		leading: true
	});
	const uniqueId = () => {
		return Date.now().toString().slice(-4);
	};
	useEffect(() => {
		var _baseSales$scanUniver;
		const actions = baseSales === null || baseSales === void 0 || (_baseSales$scanUniver = baseSales.scanUniversalListener) === null || _baseSales$scanUniver === void 0 ? void 0 : _baseSales$scanUniver.call(baseSales, (data) => {
			console.log("handle scan universal resp", data);
			if (data.status === "failed") {
				Toast.fail(locales.getText("pisell2.text.scan-global-failed"));
				return;
			}
			if (data.scanCode) {
				setValue(data.scanCode);
				setTimeout(() => {
					handleSearch.run(data.scanCode);
				});
			}
		}, `wallet_scan_${uniqueId()}`);
		return () => {
			var _actions$remove;
			if (typeof actions === "function") {
				actions();
				return;
			}
			actions === null || actions === void 0 || (_actions$remove = actions.remove) === null || _actions$remove === void 0 || _actions$remove.call(actions);
		};
	}, [baseSales, handleSearch]);
	useEffect(() => {
		syncCustomerListState();
		refreshCustomerSnapshot();
	}, [syncCustomerListState, refreshCustomerSnapshot]);
	useEffect(() => {
		if (!(baseSales === null || baseSales === void 0 ? void 0 : baseSales.effectsOn)) return;
		const offListUpdate = baseSales.effectsOn("onCustomerListUpdate", () => {
			syncCustomerListState();
		});
		const offListReset = baseSales.effectsOn("onCustomerListReset", () => {
			syncCustomerListState();
		});
		const offCustomerChange = baseSales.effectsOn("onOrderCustomerChange", () => {
			refreshCustomerSnapshot();
		});
		return () => {
			[
				offListUpdate,
				offListReset,
				offCustomerChange
			].forEach((off) => {
				var _off$remove;
				if (typeof off === "function") {
					off();
					return;
				}
				off === null || off === void 0 || (_off$remove = off.remove) === null || _off$remove === void 0 || _off$remove.call(off);
			});
		};
	}, [
		baseSales,
		refreshCustomerSnapshot,
		syncCustomerListState
	]);
	const dropdownProps = useMemo(() => {
		const icon = /* @__PURE__ */ React.createElement(Icon, {
			type: "pisell2-switch-horizontal-01",
			size: 24,
			style: { color: "#667085" }
		});
		let _props = { buttonProps: {
			icon,
			size: "default"
		} };
		if (disabledSwitch === true) _props = {
			open: false,
			buttonProps: {
				icon,
				size: "default",
				onClick: () => {
					var _Toast$info4;
					Toast === null || Toast === void 0 || (_Toast$info4 = Toast.info) === null || _Toast$info4 === void 0 || _Toast$info4.call(Toast, locales.getText("pisell2.checkout.client-card.tip.partially-paid"));
				},
				style: { cursor: "not-allowed" }
			}
		};
		return _props;
	}, [Toast, disabledSwitch]);
	const handleSearchClient = useCallback(function() {
		var _ref3 = _asyncToGenerator(function* (keyword, options) {
			if (!baseSales) return;
			if ((options === null || options === void 0 ? void 0 : options.showLoading) !== false) setCustomerLoading(true);
			try {
				var _baseSales$getCustome4;
				syncCustomerListState(baseSales.resetAndLoadCustomers ? yield baseSales.resetAndLoadCustomers({ search: keyword || void 0 }) : yield (_baseSales$getCustome4 = baseSales.getCustomerList) === null || _baseSales$getCustome4 === void 0 ? void 0 : _baseSales$getCustome4.call(baseSales, {
					search: keyword || void 0,
					skip: 1,
					num: customerListState.pagination.pageSize
				}));
			} finally {
				setCustomerLoading(false);
			}
		});
		return function(_x2, _x3) {
			return _ref3.apply(this, arguments);
		};
	}(), [
		baseSales,
		customerListState.pagination.pageSize,
		syncCustomerListState
	]);
	const handleLoadMoreCustomers = useCallback(_asyncToGenerator(function* () {
		if (!baseSales || customerLoadingMore) return;
		setCustomerLoadingMore(true);
		try {
			var _baseSales$loadMoreCu;
			syncCustomerListState(yield (_baseSales$loadMoreCu = baseSales.loadMoreCustomers) === null || _baseSales$loadMoreCu === void 0 ? void 0 : _baseSales$loadMoreCu.call(baseSales));
		} finally {
			setCustomerLoadingMore(false);
		}
	}), [
		baseSales,
		customerLoadingMore,
		syncCustomerListState
	]);
	const handleChangeCustomerPage = useCallback(function() {
		var _ref4 = _asyncToGenerator(function* (page, pageSize) {
			if (!baseSales) return;
			setCustomerLoading(true);
			try {
				var _baseSales$changeCust;
				syncCustomerListState(yield (_baseSales$changeCust = baseSales.changeCustomerPage) === null || _baseSales$changeCust === void 0 ? void 0 : _baseSales$changeCust.call(baseSales, page, pageSize));
			} finally {
				setCustomerLoading(false);
			}
		});
		return function(_x4, _x5) {
			return _ref4.apply(this, arguments);
		};
	}(), [baseSales, syncCustomerListState]);
	const handleSelectCustomer = useCallback(function() {
		var _ref5 = _asyncToGenerator(function* (customer) {
			var _baseSales$setActiveC2, _baseSales$updateTemp2;
			if (!baseSales) {
				onClientChange === null || onClientChange === void 0 || onClientChange(customer);
				return;
			}
			if (customer) {
				var _baseSales$setActiveC;
				if (baseSales.setOrderCustomer) baseSales.setOrderCustomer(customer);
				else {
					var _baseSales$updateTemp;
					(_baseSales$updateTemp = baseSales.updateTempOrderCustomer) === null || _baseSales$updateTemp === void 0 || _baseSales$updateTemp.call(baseSales, customer);
				}
				(_baseSales$setActiveC = baseSales.setActiveCustomer) === null || _baseSales$setActiveC === void 0 || _baseSales$setActiveC.call(baseSales, customer);
			} else if (baseSales.clearOrderCustomer) baseSales.clearOrderCustomer();
			else if (baseSales.updateTempOrderCustomer) baseSales.updateTempOrderCustomer({
				customer_id: null,
				customer_name: "",
				phone: "",
				email: ""
			});
			else {
				var _baseSales$setOrderCu;
				(_baseSales$setOrderCu = baseSales.setOrderCustomer) === null || _baseSales$setOrderCu === void 0 || _baseSales$setOrderCu.call(baseSales, null);
			}
			if (!customer) (_baseSales$setActiveC2 = baseSales.setActiveCustomer) === null || _baseSales$setActiveC2 === void 0 || _baseSales$setActiveC2.call(baseSales, null);
			(_baseSales$updateTemp2 = baseSales.updateTempOrderContactsInfo) === null || _baseSales$updateTemp2 === void 0 || _baseSales$updateTemp2.call(baseSales, extractContactsInfo(customer));
			refreshCustomerSnapshot();
			onClientChange === null || onClientChange === void 0 || onClientChange(customer);
		});
		return function(_x6) {
			return _ref5.apply(this, arguments);
		};
	}(), [
		baseSales,
		onClientChange,
		refreshCustomerSnapshot
	]);
	const handleAddCustomerToFirst = useCallback((customer) => {
		var _baseSales$addCustome;
		baseSales === null || baseSales === void 0 || (_baseSales$addCustome = baseSales.addCustomerToFirst) === null || _baseSales$addCustome === void 0 || _baseSales$addCustome.call(baseSales, customer);
		syncCustomerListState();
	}, [baseSales, syncCustomerListState]);
	const handleOpenCustomerDetail = useCallback((customer, onSuccess) => {
		var _context$appHelper3, _customer$id;
		const action = (_context$appHelper3 = context.appHelper) === null || _context$appHelper3 === void 0 || (_context$appHelper3 = _context$appHelper3.utils) === null || _context$appHelper3 === void 0 ? void 0 : _context$appHelper3.action;
		const customerId = (_customer$id = customer === null || customer === void 0 ? void 0 : customer.id) !== null && _customer$id !== void 0 ? _customer$id : customer === null || customer === void 0 ? void 0 : customer.customer_id;
		if (!action || !customerId) return;
		action({
			type: "pisell1.handleOpenCustomerModal",
			data: { id: customerId },
			callback: onSuccess
		});
	}, [(_context$appHelper4 = context.appHelper) === null || _context$appHelper4 === void 0 || (_context$appHelper4 = _context$appHelper4.utils) === null || _context$appHelper4 === void 0 ? void 0 : _context$appHelper4.action]);
	return /* @__PURE__ */ React.createElement("div", {
		className: "checkout-search-client-module",
		style: {
			display: "flex",
			gap: 8
		}
	}, /* @__PURE__ */ React.createElement(SearchSection, {
		value,
		onChange: setValue,
		loading,
		style: { flex: 1 },
		placeholder: locales.getText("pisell2.checkout.search-section.placeholder"),
		searchButtonProps: {
			placement: "inside",
			style: {
				height: 36,
				padding: 8,
				minWidth: 76
			}
		},
		cameraButtonProps: { icon: ["pisell2-camera-01", "pisell2-qr-code-02"] },
		onSearch: () => handleSearch.run(value)
	}), /* @__PURE__ */ React.createElement(ClientSelector, {
		ref: clientSelectorRef,
		value: currentClient,
		list: customerListState.list,
		loading: customerLoading,
		loadingMore: customerLoadingMore,
		hasMore: customerListState.hasMore,
		pagination: customerListState.pagination,
		onSearch: handleSearchClient,
		onLoadMore: handleLoadMoreCustomers,
		onChangePage: handleChangeCustomerPage,
		onSelect: handleSelectCustomer,
		onAddToFirst: handleAddCustomerToFirst,
		onOpenCustomerDetail: handleOpenCustomerDetail,
		disabledSwitch,
		clientCardProps: {
			style: {
				width: 326,
				minHeight: 48,
				height: 48,
				padding: "4px 8px",
				borderColor: "#D0D5DD"
			},
			avatar: { size: "sm" },
			dropdown: dropdownProps
		}
	}));
};
//#endregion
export { SearchAndClientModule as default };
