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 { Context, walkInData } from "../model.js";
import customSelect_default from "../../components/customSelect/index.js";
import { getFranchiseeCustomerInfo, getFranchiseeCustomerList } from "./serve.js";
import { getWaiverTitle } from "../clientVariant/utils.js";
import useGetHolderList from "../hooks/useGetHolderList.js";
import React, { useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
import { Avatar, Button, Dropdown, Spin } from "antd";
import { image, locales } from "@pisell/utils";
import PlusCircle from "@pisell/icon/es/PlusCircle";
import DotsVertical from "@pisell/icon/es/DotsVertical";
import User01 from "@pisell/icon/es/User01";
import "./index.less";
import { useMemoizedFn } from "ahooks";
//#region src/components/booking/info/client/index.tsx
const _excluded = ["customer_id"];
let isLoadClient = false;
const Client = () => {
	var _state$bookingConfig2, _state$client$value2, _state$client4, _state$client$value3, _state$client$value4, _state$client$value5, _state$client$value6, _state$client$value7, _state$client$value8, _state$client$value9, _state$client$value10, _state$client$value11;
	const modalRef = useRef();
	const [loadLoading, setLoadLoading] = useState(false);
	const [loading, setLoading] = useState(false);
	const { state, dispatch } = useContext(Context);
	const [franchiseeLoading, setFranchiseeLoading] = useState(0);
	const getHolders = useGetHolderList(state, dispatch);
	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 [params, setParams] = useState({
		skip: 1,
		num: 10,
		total: 0,
		search: "",
		sort_by: "id"
	});
	const menus = useMemo(() => {
		let list = [
			{
				key: "view",
				label: locales.getText("pisell2.text.view-profile")
			},
			{
				key: "change",
				label: locales.getText("pisell2.text.change-customer")
			},
			{
				key: "remove",
				label: locales.getText("pisell2.text.remove-customer")
			}
		];
		if (state.disabledEdit) list = list.filter((d) => d.key === "view");
		return list;
	}, [state.disabledEdit]);
	const getClients = function() {
		var _ref2 = _asyncToGenerator(function* (_ref) {
			let { customer_id } = _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.getClientsEs;
			const withKey = [...(resetParams === null || resetParams === void 0 ? void 0 : resetParams.with) || []];
			if (!withKey.includes("contactsInfo")) withKey.push("contactsInfo");
			if (!(withKey === null || withKey === void 0 ? void 0 : withKey.includes("formRecord"))) withKey.push("formRecord");
			const data = yield api(_objectSpread2(_objectSpread2(_objectSpread2({}, resetParams), {}, { with: withKey }, !state.isFranchisee ? { _config: { abort: true } } : {}), {}, { relation_form_id: (boardConfig === null || boardConfig === void 0 ? void 0 : boardConfig.form_id) || void 0 }));
			const list = ((data === null || data === void 0 ? void 0 : data.list) || []).map((d) => {
				return _objectSpread2(_objectSpread2({}, d), {}, { id: d.franchisee_customer_id || d.id });
			});
			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 totalList = totalList.concat(list);
			_payload.clients = totalList;
			setParams(_objectSpread2(_objectSpread2(_objectSpread2({}, params), resetParams), {}, { total: (data === null || data === void 0 ? void 0 : data.count) || 0 }));
			dispatch({
				type: "setClient",
				payload: _payload
			});
			setLoading(false);
			setLoadLoading(false);
			isLoadClient = true;
			return {};
		});
		return function getClients(_x) {
			return _ref2.apply(this, arguments);
		};
	}();
	const handleOpenClientModal = () => {
		var _modalRef$current;
		if (state.disabledEdit) return;
		getClients(_objectSpread2(_objectSpread2({}, params), {}, {
			search: "",
			skip: 1
		}));
		(_modalRef$current = modalRef.current) === null || _modalRef$current === void 0 || _modalRef$current.open();
	};
	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]);
	/**
	* @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(_x2) {
			return _ref3.apply(this, arguments);
		};
	}();
	const handleSelectClient = useMemoizedFn(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;
			}
			dispatch({
				type: "setClient",
				payload: {
					value: _objectSpread2(_objectSpread2({}, _value), {}, { name: getNickname(_value) }),
					edit: true
				}
			});
			return new Promise((resolve) => {
				resolve(0);
			});
		});
		return function(_x3) {
			return _ref4.apply(this, arguments);
		};
	}());
	const handleViewClient = () => {
		state.action({
			type: "pisell1.handleOpenCustomerModal",
			data: { id: state.client.value.id },
			callback: (data) => {
				if (state.disabledEdit) return;
				if (data) handleSelectClient([data]);
				getHolders();
				getClients(_objectSpread2(_objectSpread2({}, state.client.clientsParams), {}, {
					search: "",
					customer_id: data === null || data === void 0 ? void 0 : data.id,
					skip: 1,
					sort_by: "id"
				}));
			}
		});
	};
	const handleCreateItem = useMemoizedFn(() => {
		state.action({
			type: "pisell1.handleOpenAddCustomerModal",
			data: {
				showReceiveAddress: false,
				showAcceptsMarketing: false
			},
			callback: (customer_id, params) => {
				var _state$client2, _state$client2$map, _params$, _params$2, _state$client3;
				const waiverForm = ((_state$client2 = state.client) === null || _state$client2 === void 0 || (_state$client2 = _state$client2.clients) === null || _state$client2 === void 0 || (_state$client2 = _state$client2[0].waiver_form) === null || _state$client2 === void 0 || (_state$client2$map = _state$client2.map) === null || _state$client2$map === void 0 ? void 0 : _state$client2$map.call(_state$client2, (item) => _objectSpread2(_objectSpread2({}, item), {}, { is_filled: 0 }))) || [];
				dispatch({
					type: "setClient",
					payload: { 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,
						waiver_form: waiverForm
					})] : [], ...((_state$client3 = state.client) === null || _state$client3 === void 0 ? void 0 : _state$client3.clients) || []] }
				});
			}
		});
	});
	const handleRemoveClient = () => {
		if (state.disabledEdit) return;
		handleSelectClient([walkInData]);
	};
	const menuChange = (e) => {
		({
			view: handleViewClient,
			change: handleOpenClientModal,
			remove: handleRemoveClient
		})[e.key]();
	};
	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]);
	useEffect(() => {
		if (state.action) state.action({
			type: "pisell1.registerPlugin",
			data: { pluginList: ["CustomerDetailPlugin"] }
		});
	}, []);
	const renderList = useMemo(() => {
		return [...state.client.clients];
	}, [state.client.clients]);
	const searchChange = useMemoizedFn((search) => {
		getClients(_objectSpread2({}, _objectSpread2(_objectSpread2({}, params), {}, {
			skip: 1,
			search
		})));
	});
	const 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
	]);
	const customSelect = useMemo(() => {
		console.log("render customSelect");
		return /* @__PURE__ */ React.createElement(customSelect_default, {
			autoFocus: !state.isTerminal,
			modalOpen: state.modalOpen,
			ref: modalRef,
			rowKey: "id",
			options: renderList,
			loading,
			value: [state.client.value],
			onValueChange: handleSelectClient,
			handleCreateItem,
			isPreview: false,
			drawerProps: {
				title: locales.getText("pisell2.text.select-customer"),
				destroyOnClose: true,
				mask: state.drawerMask
			},
			mode: "single",
			createItemText: locales.getText("pisell2.text.create-new-customer"),
			closeCallback: () => {},
			optionRender: (item) => {
				console.log("render_optionRender", item);
				let displayEmail = item === null || item === void 0 ? void 0 : item.email;
				let displayPhone = item === null || item === void 0 ? void 0 : item.phone;
				if (!displayEmail && !displayPhone) {
					var _item$contacts_info, _item$contacts_info2;
					displayEmail = item === null || item === void 0 || (_item$contacts_info = item.contacts_info) === null || _item$contacts_info === void 0 || (_item$contacts_info = _item$contacts_info.value) === null || _item$contacts_info === void 0 ? void 0 : _item$contacts_info.email;
					displayPhone = item === null || item === void 0 || (_item$contacts_info2 = item.contacts_info) === null || _item$contacts_info2 === void 0 || (_item$contacts_info2 = _item$contacts_info2.value) === null || _item$contacts_info2 === void 0 || (_item$contacts_info2 = _item$contacts_info2.phone) === null || _item$contacts_info2 === void 0 ? void 0 : _item$contacts_info2.phone;
				}
				return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Avatar, {
					className: "pisell-lowcode__booking-client-list-item-avatar",
					src: image.ali(item.cover, 100) || void 0,
					icon: /* @__PURE__ */ React.createElement(User01, { className: "pisell-lowcode__booking-client-list-item-avatar-icon" })
				}), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-client-list-item-info" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-client-list-item-info-name" }, getNickname(item)), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-client-list-item-info-desc" }, displayEmail ? /* @__PURE__ */ React.createElement("div", { className: "" }, displayEmail) : null, displayPhone ? /* @__PURE__ */ React.createElement("div", { className: "" }, displayPhone) : null), /* @__PURE__ */ React.createElement("div", {
					className: "pisell-lowcode__booking-client-list-item-info-waiver",
					title: getWaiverTitle(item.waiver_form)
				}, (item.waiver_form || []).map((item) => {
					return /* @__PURE__ */ React.createElement("span", null, item.form_title, ":", item.is_filled ? /* @__PURE__ */ React.createElement("span", { className: "pisell-lowcode__booking-client-list-item-waiver-filled" }, locales.getText("pisell2.text.filled")) : /* @__PURE__ */ React.createElement("span", { className: "pisell-lowcode__booking-client-list-item-waiver-not-filled" }, locales.getText("pisell2.text.not-filled")), ";", " ");
				}))), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-client-list-item-loading" }, /* @__PURE__ */ React.createElement(Spin, { spinning: franchiseeLoading === item.id })));
			},
			searchChange,
			searchValue: params.search,
			loadMore,
			filterItem: (d, search) => {
				return true;
			}
		});
	}, [
		state.isTerminal,
		state.modalOpen,
		(_state$client4 = state.client) === null || _state$client4 === void 0 ? void 0 : _state$client4.value,
		state.drawerMask,
		renderList,
		loading,
		franchiseeLoading,
		params.search,
		loadMore
	]);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
		className: "pisell-lowcode__booking-client",
		onClick: () => {
			if (!isWalkIn$1 || (state === null || state === void 0 ? void 0 : state.disableEventBookingEdit)) return;
			handleOpenClientModal();
		},
		style: state.bookingId ? {} : { marginTop: 12 }
	}, /* @__PURE__ */ React.createElement(Avatar, {
		className: "pisell-lowcode__booking-client-list-item-avatar",
		src: image.ali((_state$client$value3 = state.client.value) === null || _state$client$value3 === void 0 ? void 0 : _state$client$value3.cover, 100),
		icon: /* @__PURE__ */ React.createElement(User01, { className: "pisell-lowcode__booking-client-list-item-avatar-icon" })
	}), /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-client-info" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-client-info-left" }, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-client-info-name" }, getNickname(state.client.value)), isWalkIn$1 ? /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-client-info-desc" }, locales.getText("pisell2.text.leave-empty-for-walk-in")) : /* @__PURE__ */ React.createElement(React.Fragment, null, ((_state$client$value4 = state.client.value) === null || _state$client$value4 === void 0 ? void 0 : _state$client$value4.email) ? /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-client-info-email" }, (_state$client$value5 = state.client.value) === null || _state$client$value5 === void 0 ? void 0 : _state$client$value5.email) : null, ((_state$client$value6 = state.client.value) === null || _state$client$value6 === void 0 ? void 0 : _state$client$value6.phone) ? /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-client-info-phone" }, (_state$client$value7 = state.client.value) === null || _state$client$value7 === void 0 ? void 0 : _state$client$value7.phone) : null, !!((_state$client$value8 = state.client.value) === null || _state$client$value8 === void 0 || (_state$client$value8 = _state$client$value8.waiver_form) === null || _state$client$value8 === void 0 ? void 0 : _state$client$value8.length) && /* @__PURE__ */ React.createElement("div", {
		className: "pisell-lowcode__booking-client-waiver",
		title: getWaiverTitle((_state$client$value9 = state.client.value) === null || _state$client$value9 === void 0 ? void 0 : _state$client$value9.waiver_form)
	}, (_state$client$value10 = state.client.value) === null || _state$client$value10 === void 0 || (_state$client$value10 = _state$client$value10.waiver_form) === null || _state$client$value10 === void 0 || (_state$client$value11 = _state$client$value10.map) === null || _state$client$value11 === void 0 ? void 0 : _state$client$value11.call(_state$client$value10, (item) => {
		return /* @__PURE__ */ React.createElement("span", null, item.form_title, /* @__PURE__ */ React.createElement("span", { className: "pisell-lowcode__booking-client-waiver-colon" }, ":"), item.is_filled ? /* @__PURE__ */ React.createElement("span", { className: "pisell-lowcode__booking-client-waiver-filled" }, locales.getText("pisell2.text.filled")) : /* @__PURE__ */ React.createElement("span", { className: "pisell-lowcode__booking-client-waiver-not-filled" }, locales.getText("pisell2.text.not-filled")), `; `);
	})))), !(state === null || state === void 0 ? void 0 : state.disableEventBookingEdit) && /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-client-info-right" }, isWalkIn$1 ? /* @__PURE__ */ React.createElement(PlusCircle, { className: "pisell-lowcode__booking-client-add-icon" }) : /* @__PURE__ */ React.createElement(Dropdown, {
		menu: {
			items: menus,
			onClick: menuChange
		},
		placement: "bottomRight"
	}, /* @__PURE__ */ React.createElement("div", { className: "pisell-lowcode__booking-client-menu-wrap" }, /* @__PURE__ */ React.createElement(DotsVertical, { className: "pisell-lowcode__booking-client-menu-icon" })))))), customSelect);
};
var client_default = React.memo(Client);
//#endregion
export { client_default as default };
