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 useEngineContext from "../../../../hooks/useEngineContext.js";
import useLoginUser from "../../../../hooks/useLoginUser.js";
import ContactInfoContent from "../../../../plus/contactInfoModal/ContactInfoContent.js";
import { Toast } from "../../utils.js";
import productStockCheckModal_default from "../../../productStockCheckModal/index.js";
import { useAppointmentBookingContext } from "../../context.js";
import { contextUtils, useAppointmentBookingSetting, useShopDiscount } from "../../hooks.js";
import CartItem from "../Cart/Item/index.js";
import { getFormParams } from "./utils.js";
import useCartProductStockCheck from "../../../../hooks/useCartProductStockCheck.js";
import React, { forwardRef, useEffect, useImperativeHandle, useMemo, useRef } from "react";
import { Form } from "antd";
import { isMobile, locales } from "@pisell/utils";
import "./index.less";
//#region src/components/appointmentBooking/components/ConfirmInformation/index.tsx
const ConfirmInformation = forwardRef((props, ref) => {
	var _context$appHelper;
	const hasSubscribedRef = useRef(false);
	const context = useEngineContext();
	const config = (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.constants) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.config) || {};
	const utils = contextUtils();
	const { pubsub } = context.appHelper.utils;
	const { appointmentBooking, summary, isAgreeDepositPolicy, setLoading, carts, setTimes } = useAppointmentBookingContext();
	useShopDiscount();
	const { isRetailTemplate, bookingSetting } = useAppointmentBookingSetting();
	console.log(bookingSetting, "bookingSetting");
	const [form] = Form.useForm();
	const userInfo = useLoginUser();
	const productStockCheckModalRef = useRef(null);
	const { handleContinue, handleReturn, checkProductStock } = useCartProductStockCheck();
	const getContactsInfo = function() {
		var _ref = _asyncToGenerator(function* () {
			let contacts_info = null;
			try {
				var _appointmentBooking$g;
				const res = yield appointmentBooking === null || appointmentBooking === void 0 || (_appointmentBooking$g = appointmentBooking.getContactInfo) === null || _appointmentBooking$g === void 0 ? void 0 : _appointmentBooking$g.call(appointmentBooking, { key: "contacts_info" });
				if ((res === null || res === void 0 ? void 0 : res.code) == 200 && (res === null || res === void 0 ? void 0 : res.data)) contacts_info = res === null || res === void 0 ? void 0 : res.data;
			} catch (error) {
				console.log("error", error);
				contacts_info = null;
			}
			const transfromCountryCallingCode = (code) => {
				if (!code) return "";
				return (code === null || code === void 0 ? void 0 : code.startsWith("+")) ? code : `+${code}`;
			};
			if (contacts_info) {
				const { first_name, last_name, phone, email } = contacts_info || {};
				form.setFieldsValue({
					first_name,
					last_name,
					phone: {
						phone: phone === null || phone === void 0 ? void 0 : phone.phone,
						countryCallingCode: transfromCountryCallingCode(phone === null || phone === void 0 ? void 0 : phone.country_calling_code),
						countryCode: phone === null || phone === void 0 ? void 0 : phone.country_code
					},
					email
				});
			} else {
				console.log("userInfo", userInfo);
				const { first_name, last_name, phone, email, country_calling_code, country_code } = userInfo || {};
				form.setFieldsValue({
					first_name,
					last_name,
					phone: {
						phone,
						countryCallingCode: transfromCountryCallingCode(country_calling_code),
						countryCode: country_code
					},
					email
				});
			}
		});
		return function getContactsInfo() {
			return _ref.apply(this, arguments);
		};
	}();
	useEffect(() => {
		getContactsInfo();
	}, []);
	/**
	* @title: 支付成功回调
	* @description:
	* @param {number} order_id
	* @param {any} amount
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-04-28 13:44
	*/
	const goPaymentFinish = (order_id, amount) => {
		var _utils$history;
		const url = `/payment-finish/success?order_id=${order_id}&amount=${Number(amount)}`;
		utils === null || utils === void 0 || (_utils$history = utils.history) === null || _utils$history === void 0 || _utils$history.replace(url);
		setLoading(false);
	};
	useEffect(() => {
		if (isRetailTemplate) handleForm(false);
	}, [isRetailTemplate]);
	/**
	* @title: 处理零售模版表单
	* @description:
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-05-28 15:42
	*/
	const handleForm = function() {
		var _ref3 = _asyncToGenerator(function* (isSubmit, extraData) {
			var _utils$action;
			const carts = yield appointmentBooking.getCart();
			const key = "isRetailFormSubmit";
			const isRetailFormSubmit = appointmentBooking.getOtherData(key);
			const callback = () => {
				if (isSubmit) onCheckout(extraData);
			};
			if (isRetailFormSubmit) return callback();
			const params = getFormParams(carts);
			utils === null || utils === void 0 || (_utils$action = utils.action) === null || _utils$action === void 0 || _utils$action.call(utils, {
				type: "pisell1.goProductForm",
				data: params,
				callback: function() {
					var _ref2 = _asyncToGenerator(function* (e) {
						if ((e === null || e === void 0 ? void 0 : e.type) !== "close") {
							var _carts$;
							yield appointmentBooking.updateCart({
								_id: carts === null || carts === void 0 || (_carts$ = carts[0]) === null || _carts$ === void 0 ? void 0 : _carts$._id,
								relationForms: e
							});
							appointmentBooking.setOtherData(key, true);
							callback();
						}
						setLoading(false);
					});
					return function callback(_x) {
						return _ref2.apply(this, arguments);
					};
				}()
			});
		});
		return function handleForm(_x2, _x3) {
			return _ref3.apply(this, arguments);
		};
	}();
	/**
	* @title: 执行结算操作
	* @description:
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-05-08 17:32
	*/
	const handleNext = function() {
		var _ref4 = _asyncToGenerator(function* (extraData) {
			var _deposit$protocols;
			const { deposit } = summary;
			if ((deposit === null || deposit === void 0 ? void 0 : deposit.hasDeposit) && (deposit === null || deposit === void 0 || (_deposit$protocols = deposit.protocols) === null || _deposit$protocols === void 0 ? void 0 : _deposit$protocols.length) > 0 && !isAgreeDepositPolicy) return Toast(locales.getText("pisell2.appointment.deposit.agree.policy"));
			setLoading(true);
			if (isRetailTemplate) {
				handleForm(true, extraData);
				return;
			}
			onCheckout(extraData);
		});
		return function handleNext(_x4) {
			return _ref4.apply(this, arguments);
		};
	}();
	/**
	* @title: 结算
	* @description:
	* @return {*}
	* @Author: WangHan
	* @Date: 2025-05-28 15:48
	*/
	const onCheckout = function() {
		var _ref5 = _asyncToGenerator(function* (extraData) {
			try {
				const { deposit } = summary;
				const { data } = yield appointmentBooking.submitOrder(extraData);
				const { is_deposit, deposit_amount, total_amount, order_id } = data || {};
				const _total = is_deposit ? deposit_amount : total_amount;
				if (_total > 0) {
					utils.action({
						type: "pisell1.payment",
						data: _objectSpread2(_objectSpread2({}, data), {}, { total_amount: _total }),
						callback: (e) => {}
					});
					setTimeout(() => {
						setLoading(false);
					}, 200);
				} else {
					if (deposit === null || deposit === void 0 ? void 0 : deposit.hasDeposit) {
						goPaymentFinish(order_id, _total);
						return;
					}
					const freeResult = yield appointmentBooking.getFreeProduct(order_id);
					console.log(freeResult, "freeResult");
					if (freeResult === null || freeResult === void 0 ? void 0 : freeResult.status) goPaymentFinish(order_id, total_amount);
					else Toast(freeResult === null || freeResult === void 0 ? void 0 : freeResult.message);
				}
			} catch (error) {
				if (checkProductStock(productStockCheckModalRef, error === null || error === void 0 ? void 0 : error.data, carts)) {
					setLoading(false);
					return;
				}
				Toast((error === null || error === void 0 ? void 0 : error.message) || "");
				setTimeout(() => {
					setLoading(false);
				}, 50);
			}
		});
		return function onCheckout(_x5) {
			return _ref5.apply(this, arguments);
		};
	}();
	const handleSubmit = function() {
		var _ref6 = _asyncToGenerator(function* () {
			var _utils$businessUtils, _utils$businessUtils$;
			if (utils === null || utils === void 0 || (_utils$businessUtils = utils.businessUtils) === null || _utils$businessUtils === void 0 || (_utils$businessUtils$ = _utils$businessUtils.isGuestUser) === null || _utils$businessUtils$ === void 0 ? void 0 : _utils$businessUtils$.call(_utils$businessUtils)) {
				var _utils$businessUtils2, _utils$businessUtils3;
				if (!hasSubscribedRef.current) {
					pubsub.subscribe("bind.guest.user", handleNext);
					hasSubscribedRef.current = true;
				}
				utils === null || utils === void 0 || (_utils$businessUtils2 = utils.businessUtils) === null || _utils$businessUtils2 === void 0 || (_utils$businessUtils3 = _utils$businessUtils2.openRegisterModal) === null || _utils$businessUtils3 === void 0 || _utils$businessUtils3.call(_utils$businessUtils2, true);
				return;
			}
			let contacts_info = null;
			try {
				if (showContactInfo) {
					var _contacts_info$phone, _contacts_info$phone2, _contacts_info$phone3;
					contacts_info = yield form.validateFields();
					const newPhone = {
						phone: (contacts_info === null || contacts_info === void 0 || (_contacts_info$phone = contacts_info.phone) === null || _contacts_info$phone === void 0 ? void 0 : _contacts_info$phone.phone) || "",
						country_calling_code: (contacts_info === null || contacts_info === void 0 || (_contacts_info$phone2 = contacts_info.phone) === null || _contacts_info$phone2 === void 0 ? void 0 : _contacts_info$phone2.countryCallingCode) || "",
						country_code: (contacts_info === null || contacts_info === void 0 || (_contacts_info$phone3 = contacts_info.phone) === null || _contacts_info$phone3 === void 0 ? void 0 : _contacts_info$phone3.countryCode) || ""
					};
					contacts_info.phone = newPhone;
					if ((contacts_info === null || contacts_info === void 0 ? void 0 : contacts_info.first_name) || (contacts_info === null || contacts_info === void 0 ? void 0 : contacts_info.last_name)) contacts_info.display_name = `${(contacts_info === null || contacts_info === void 0 ? void 0 : contacts_info.first_name) || ""} ${(contacts_info === null || contacts_info === void 0 ? void 0 : contacts_info.last_name) || ""}`;
					else contacts_info.display_name = "";
					console.log("contacts_info", contacts_info);
				}
			} catch (error) {
				console.log("error", error);
				return;
			}
			handleNext({ contacts_info });
		});
		return function handleSubmit() {
			return _ref6.apply(this, arguments);
		};
	}();
	useEffect(() => {
		return () => {
			pubsub.unsubscribe("bind.guest.user", handleNext);
			hasSubscribedRef.current = false;
		};
	}, []);
	useImperativeHandle(ref, () => ({ next: handleSubmit }));
	const showContactInfo = useMemo(() => {
		let visible = false;
		const { showContactInfo: showContactInfoValue, contactInfoSetting } = bookingSetting || {};
		if (showContactInfoValue === 1 || showContactInfoValue === "1") {
			const { showName, showPhone, showEmail } = contactInfoSetting || {};
			if ((showName === 0 || showName === "0") && (showPhone === 0 || showPhone === "0") && (showEmail === 0 || showEmail === "0")) visible = false;
			else visible = true;
		} else visible = false;
		return visible;
	}, [bookingSetting === null || bookingSetting === void 0 ? void 0 : bookingSetting.showContactInfo, bookingSetting === null || bookingSetting === void 0 ? void 0 : bookingSetting.contactInfoSetting]);
	const renderContactInfo = () => {
		const { emailRequired, nameRequired, phoneRequired, showEmail, showName, showPhone } = (bookingSetting === null || bookingSetting === void 0 ? void 0 : bookingSetting.contactInfoSetting) || {};
		if (!showContactInfo) return null;
		return /* @__PURE__ */ React.createElement("div", { className: "appointment-confirm-information-contact-info-wrap" }, /* @__PURE__ */ React.createElement("div", { className: "appointment-confirm-information-contact-info-title" }, locales.getText("pisell2.text.contact-info.title")), /* @__PURE__ */ React.createElement(ContactInfoContent, {
			dataSource: null,
			form,
			config: {
				first_name: {
					visible: showName === 0 ? false : true,
					required: nameRequired === "required" ? true : false
				},
				last_name: {
					visible: showName === 0 ? false : true,
					required: nameRequired === "required" ? true : false
				},
				phone: {
					visible: showPhone === 0 ? false : true,
					required: phoneRequired === "optional" ? false : true
				},
				email: {
					visible: showEmail === 0 ? false : true,
					required: emailRequired === "optional" ? false : true
				}
			}
		}));
	};
	const handleProductStockCheck = (data, type) => {
		(type === "continue" ? handleContinue : handleReturn)({
			cartProducts: carts,
			data,
			callback: (newCart) => {
				if (type === "continue") handleSubmit();
			},
			appointmentBooking,
			setTimes,
			isSkipClearData: !isRetailTemplate
		});
	};
	return /* @__PURE__ */ React.createElement("div", { className: "appointment-confirm-information-wrap" }, isMobile() ? /* @__PURE__ */ React.createElement(CartItem, {
		onNext: handleSubmit,
		renderContactInfo
	}) : showContactInfo ? renderContactInfo() : /* @__PURE__ */ React.createElement("div", { className: "appointment-confirm-information-content" }, /* @__PURE__ */ React.createElement("div", { className: "image" }, /* @__PURE__ */ React.createElement("img", {
		src: `${config === null || config === void 0 ? void 0 : config.awsStatic}/checkout_confirm.png`,
		loading: "lazy"
	})), /* @__PURE__ */ React.createElement("span", { className: "tips" }, locales.getText("pisell2.appointment.tips")), /* @__PURE__ */ React.createElement("span", { className: "tips-content" }, locales.getText("pisell2.appointment.tips.content"))), /* @__PURE__ */ React.createElement(productStockCheckModal_default, {
		ref: productStockCheckModalRef,
		onContinue: (data) => handleProductStockCheck(data, "continue"),
		onReturn: (data) => handleProductStockCheck(data, "return")
	}));
});
//#endregion
export { ConfirmInformation as default };
