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 { isWalkIn } from "../../../utils.js";
import { walkInData } from "../../model.js";
import { getFranchiseeCustomerInfo, getFranchiseeCustomerList } from "../../client/serve.js";
import useIsLowSpeedNetwork from "./useIsLowSpeedNetwork.js";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Button } from "antd";
import { locales } from "@pisell/utils";
//#region src/components/booking/info/clientVariant/hooks/useClientFn.tsx
const _excluded = ["customer_id", "customer_ids"];
let isLoadClient = false;
const useClientFn = (_params) => {
	var _state$bookingConfig, _state$bookingConfig3, _state$client$value2;
	const { state, setGlobalState, modalRef, onRemoveClient } = _params;
	const [loadLoading, setLoadLoading] = useState(false);
	const [loading, setLoading] = useState(false);
	const [franchiseeLoading, setFranchiseeLoading] = useState(0);
	useIsLowSpeedNetwork();
	const [params, setParams] = useState({
		skip: 1,
		num: 5,
		total: 0,
		search: "",
		with: ["formRecord", "contactsInfo"],
		relation_form_id: 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 || (_state$bookingConfig = _state$bookingConfig.appointment_subject) === null || _state$bookingConfig === void 0 ? void 0 : _state$bookingConfig.form_id
	});
	const paramsRef = useRef(params);
	paramsRef.current = params;
	useEffect(() => {
		setParams((v) => {
			var _state$bookingConfig2;
			return _objectSpread2(_objectSpread2({}, v), {}, { relation_form_id: state === null || state === void 0 || (_state$bookingConfig2 = state.bookingConfig) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.config) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.basic) === null || _state$bookingConfig2 === void 0 || (_state$bookingConfig2 = _state$bookingConfig2.appointment_subject) === null || _state$bookingConfig2 === void 0 ? void 0 : _state$bookingConfig2.form_id });
		});
	}, [state === null || state === void 0 || (_state$bookingConfig3 = state.bookingConfig) === null || _state$bookingConfig3 === void 0 || (_state$bookingConfig3 = _state$bookingConfig3.config) === null || _state$bookingConfig3 === void 0 || (_state$bookingConfig3 = _state$bookingConfig3.basic) === null || _state$bookingConfig3 === void 0 ? void 0 : _state$bookingConfig3.appointment_subject]);
	const stateRef = useRef(state);
	stateRef.current = state;
	const isWalkIn$1 = useMemo(() => {
		var _state$client$value;
		return isWalkIn((_state$client$value = state.client.value) === null || _state$client$value === void 0 ? void 0 : _state$client$value.id);
	}, [(_state$client$value2 = state.client.value) === null || _state$client$value2 === void 0 ? void 0 : _state$client$value2.id]);
	const getClients = function() {
		var _ref2 = _asyncToGenerator(function* (_ref, returnResult) {
			let { customer_id, customer_ids } = _ref, resetParams = _objectWithoutProperties(_ref, _excluded);
			let _setLoading;
			if (resetParams.skip === 1) if (resetParams.search) _setLoading = setLoading;
			else {
				var _state$client;
				_setLoading = isLoadClient || (state === null || state === void 0 || (_state$client = state.client) === null || _state$client === void 0 || (_state$client = _state$client.clients) === null || _state$client === void 0 ? void 0 : _state$client.length) ? () => {} : setLoading;
			}
			else _setLoading = setLoadLoading;
			_setLoading(true);
			const api = state.isFranchisee ? getFranchiseeCustomerList : state.apis.getClients;
			const withKey = [...(resetParams === null || resetParams === void 0 ? void 0 : resetParams.with) || []];
			if (!withKey.includes("contactsInfo")) withKey.push("contactsInfo");
			const data = yield api(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2(_objectSpread2({}, resetParams), resetParams.search ? { num: 10 } : {}), state.isFranchisee ? { franchisee_customer_ids: customer_ids } : { customer_ids }), !state.isFranchisee && !returnResult ? { _config: { abort: true } } : {}), {}, { with: withKey }));
			const list = ((data === null || data === void 0 ? void 0 : data.list) || []).map((d) => {
				var _d$form_record;
				return _objectSpread2(_objectSpread2({}, d), {}, {
					name: getNickname(d),
					id: d.franchisee_customer_id || d.id,
					form_record: ((_d$form_record = d.form_record) === null || _d$form_record === void 0 ? void 0 : _d$form_record.map((item) => _objectSpread2(_objectSpread2(_objectSpread2({}, item), item.data), {}, { form_record_id: item.id }))) || []
				});
			});
			if (returnResult) return list;
			let _payload = { clients: list };
			if (!isWalkIn(customer_id)) {
				const customerItem = list.find((d) => d.id === customer_id);
				if (customerItem) {
					_payload.value = customerItem;
					_payload.edit = true;
				}
			}
			let totalList = [...state.client.clients];
			if (resetParams.skip === 1) totalList = list;
			else list.forEach((item) => {
				const index = totalList.findIndex((old) => old.id === item.id);
				if (index > -1) totalList[index] = item;
				else totalList.push(item);
			});
			_payload.clients = totalList;
			setParams(_objectSpread2(_objectSpread2(_objectSpread2({}, params), resetParams), {}, { total: (data === null || data === void 0 ? void 0 : data.count) || 0 }));
			setGlobalState({ client: _objectSpread2(_objectSpread2({}, stateRef.current.client), _payload) });
			isLoadClient = true;
			setLoading(false);
			setLoadLoading(false);
			return {};
		});
		return function getClients(_x, _x2) {
			return _ref2.apply(this, arguments);
		};
	}();
	const handleOpenClientModal = (val) => {
		var _modalRef$current;
		if (state.disabledEdit) return;
		setClient({ showModal: true });
		getClients(_objectSpread2(_objectSpread2({}, paramsRef.current), {}, {
			search: val || "",
			skip: 1
		}));
		(_modalRef$current = modalRef.current) === null || _modalRef$current === void 0 || _modalRef$current.open();
	};
	const handleViewClient = () => {
		state.action({
			type: "pisell1.handleOpenCustomerModal",
			data: { id: state.client.value.id },
			callback: (data) => {
				if (state.disabledEdit) return;
				if (data === "createBooking") {
					var _window, _window$refreshBookin;
					(_window = window) === null || _window === void 0 || (_window = _window.shopApi) === null || _window === void 0 || (_window = _window.booking) === null || _window === void 0 || (_window$refreshBookin = _window.refreshBookingData) === null || _window$refreshBookin === void 0 || _window$refreshBookin.call(_window);
					return;
				}
				if (data) handleSelectClient([data]);
				getClients(_objectSpread2(_objectSpread2({}, state.client.clientsParams), {}, {
					search: "",
					customer_id: data === null || data === void 0 ? void 0 : data.id,
					skip: 1
				}));
			}
		});
	};
	const menus = useMemo(() => {
		let list = [{
			key: "remove",
			label: locales.getText("pisell2.text.remove-customer")
		}];
		if (state.disabledEdit) list = list.filter((d) => d.key === "view");
		return list;
	}, [state.disabledEdit]);
	const handleRemoveClient = () => {
		if (state.disabledEdit) return;
		handleSelectClient([walkInData]);
		onRemoveClient === null || onRemoveClient === void 0 || onRemoveClient();
	};
	const menuChange = (e) => {
		e.domEvent.stopPropagation();
		({
			view: handleViewClient,
			change: handleOpenClientModal,
			remove: handleRemoveClient
		})[e.key]();
	};
	const setClient = (client) => {
		setGlobalState({ client: _objectSpread2(_objectSpread2({}, stateRef.current.client), client) });
	};
	/**
	* @title: 置换客户id到子店铺
	* @description:
	* @param {number} id
	* @return {*}
	* @Author: zhiwei.Wang
	* @Date: 2024-05-29 17:26
	*/
	const _getFranchiseeCustomerInfo = function() {
		var _ref3 = _asyncToGenerator(function* (customer) {
			try {
				setFranchiseeLoading(customer.id);
				const res = yield getFranchiseeCustomerInfo({ franchisor_customer_id: customer.id });
				setFranchiseeLoading(0);
				return _objectSpread2(_objectSpread2({}, customer), {}, { id: res.franchisee_customer_id });
			} catch (err) {
				setFranchiseeLoading(0);
			}
		});
		return function _getFranchiseeCustomerInfo(_x3) {
			return _ref3.apply(this, arguments);
		};
	}();
	const getNickname = useCallback((item) => {
		if (isWalkIn(item === null || item === void 0 ? void 0 : item.id)) return locales.getText("pisell2.text.select-a-customer");
		const firstLastName = item.first_name || item.last_name ? `${item.first_name} ${item.last_name}` : "";
		return item.name || (item.display_name || "").trim() || (item.nickname || "").trim() || firstLastName.trim() || "";
	}, [locales.localeMap]);
	useEffect(() => {
		if (state.action) state.action({
			type: "pisell1.registerPlugin",
			data: { pluginList: ["CustomerDetailPlugin"] }
		});
	}, []);
	const handleSelectClient = function() {
		var _ref4 = _asyncToGenerator(function* (value) {
			let _value = (value === null || value === void 0 ? void 0 : value[value.length - 1]) || walkInData;
			if (_value.loading) return;
			if (state.isFranchisee && _value.franchisee_customer_id === 0) {
				try {
					_value = yield _getFranchiseeCustomerInfo(_value);
				} catch (err) {}
				if (!_value) return;
			}
			setClient({
				value: _objectSpread2(_objectSpread2({}, _value), {}, { name: getNickname(_value) }),
				edit: true
			});
			return new Promise((resolve) => {
				resolve(0);
			});
		});
		return function handleSelectClient(_x4) {
			return _ref4.apply(this, arguments);
		};
	}();
	const handleCreateItem = (cb) => {
		state.action({
			type: "pisell1.handleOpenAddCustomerModal",
			data: {
				showReceiveAddress: false,
				showAcceptsMarketing: false
			},
			callback: (customer_id, params) => {
				var _params$, _params$2, _state$client2;
				cb === null || cb === void 0 || cb();
				setClient({ clients: [...(params === null || params === void 0 || (_params$ = params[0]) === null || _params$ === void 0 ? void 0 : _params$.customer) ? [_objectSpread2(_objectSpread2({}, params === null || params === void 0 || (_params$2 = params[0]) === null || _params$2 === void 0 ? void 0 : _params$2.customer), {}, {
					id: customer_id,
					form_record: []
				})] : [], ...((_state$client2 = state.client) === null || _state$client2 === void 0 ? void 0 : _state$client2.clients) || []] });
			}
		});
	};
	const searchChange = (search) => {
		getClients(_objectSpread2({}, _objectSpread2(_objectSpread2({}, paramsRef.current), {}, {
			skip: 1,
			search
		})));
	};
	return {
		setClient,
		isWalkIn: isWalkIn$1,
		handleSelectClient,
		menuChange,
		handleViewClient,
		menus,
		handleCreateItem,
		getClients,
		params,
		searchChange,
		loading,
		loadMore: useMemo(() => {
			return state.client.clients.length < params.total || 0 ? /* @__PURE__ */ React.createElement("div", {
				className: "",
				style: {
					textAlign: "center",
					padding: "16px 0"
				}
			}, /* @__PURE__ */ React.createElement(Button, {
				loading: loadLoading,
				onClick: () => {
					getClients(_objectSpread2({}, _objectSpread2(_objectSpread2({}, params), {}, { skip: params.skip + 1 })));
				}
			}, locales.getText("pisell2.text.load-more"))) : null;
		}, [
			loadLoading,
			params,
			state.client.clients.length
		]),
		handleOpenClientModal,
		getNickname,
		franchiseeLoading
	};
};
//#endregion
export { useClientFn as default };
