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 PageSetting from "../PageSetting/index.js";
import AuthenticationMethods from "../AuthenticationMethods/index.js";
import CollectInfo from "../CollectInfo/index.js";
import locales_default from "../locales.js";
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Button, Spin, Tabs, Typography, message } from "antd";
import { locales } from "@pisell/utils";
import classNames from "classnames";
import "./index.less";
//#region src/components/authentication/admin/ChannelAuthSetting/OnlineShopAuth/index.tsx
const { Title, Paragraph } = Typography;
const Onlineshopauth = ({ className, style, value, defaultActiveTab, visibleTabs, showRegisterPage = true, onSave }) => {
	var _context$engine;
	const context = useEngineContext();
	const { useParams } = context.appHelper.utils.getApp().history;
	let channel = new URLSearchParams(window.location.search).get("channel") || "";
	const { channel: _channel } = useParams();
	channel = channel || _channel;
	const { request } = context.appHelper.utils.getApp();
	const [loading, setLoading] = useState(true);
	const [channelData, setChannelData] = useState(null);
	const pageSettingRef = useRef(null);
	locales.init(locales_default, (context === null || context === void 0 || (_context$engine = context.engine) === null || _context$engine === void 0 || (_context$engine = _context$engine.props) === null || _context$engine === void 0 ? void 0 : _context$engine.locale) || "en");
	const allTabs = ["pageSetting", "authenticationMethods"];
	const saveData = (data) => {
		request.post(`/api/tenant_channel:update?filter=%7B%22channel_code%22%3A%22${channel}%22%7D`, _objectSpread2(_objectSpread2({}, channelData), {}, { metadata: _objectSpread2(_objectSpread2({}, channelData === null || channelData === void 0 ? void 0 : channelData.metadata), {}, { register_login: data }) }), {
			isNocobase: true,
			headers: { "x-data-source": "pisell2" }
		}).then((res) => {
			message.success(locales.getText("channel.auth.setting.message.saveSuccess"));
		}).catch((error) => {
			console.error("Error fetching tenant data:", error);
			message.error(locales.getText("channel.auth.setting.message.saveError"));
		});
	};
	useEffect(() => {
		if (channel) {
			setLoading(true);
			request.get(`/api/tenant_channel:get?filter=%7B%22channel_code%22%3A%22${channel}%22%7D&appends=channel`, {}, {
				isNocobase: true,
				headers: { "x-data-source": "pisell2" }
			}).then((res) => {
				if (res === null || res === void 0 ? void 0 : res.data) {
					try {
						delete res.data.deleted_at;
					} catch (error) {}
					setChannelData(res === null || res === void 0 ? void 0 : res.data);
				}
				console.log("res_online_shop_auth", res);
				setLoading(false);
			}).catch((error) => {
				console.error("Error fetching tenant data:", error);
				setLoading(false);
			});
		}
	}, [request, channel]);
	const filteredTabsByVisibleTabs = useMemo(() => {
		if (visibleTabs && visibleTabs.length > 0) return allTabs.filter((tab) => visibleTabs.includes(tab));
		return allTabs;
	}, [visibleTabs]);
	const displayTabs = useMemo(() => {
		if (channel === "management") {
			if (filteredTabsByVisibleTabs.includes("pageSetting")) return ["pageSetting"];
			return [];
		}
		return filteredTabsByVisibleTabs;
	}, [channel, filteredTabsByVisibleTabs]);
	const [activeTab, setActiveTab] = useState(useMemo(() => {
		if (defaultActiveTab && displayTabs.includes(defaultActiveTab)) return defaultActiveTab;
		return displayTabs[0] || "pageSetting";
	}, [defaultActiveTab, displayTabs]));
	const [internalValue, setInternalValue] = useState(value || {});
	useEffect(() => {
		if (value) setInternalValue(value);
	}, [value]);
	useEffect(() => {
		var _channelData$metadata;
		if (channelData === null || channelData === void 0 || (_channelData$metadata = channelData.metadata) === null || _channelData$metadata === void 0 ? void 0 : _channelData$metadata.register_login) {
			const { page, auth } = channelData.metadata.register_login;
			const pageSettingValue = {};
			if (page) {
				var _page$register, _page$register2, _page$login$same_as_r, _page$login, _page$login2, _page$login3, _page$login4;
				pageSettingValue.registerPage = {
					backgroundImage: ((_page$register = page.register) === null || _page$register === void 0 ? void 0 : _page$register.background_image_url) || "",
					termsConditions: ((_page$register2 = page.register) === null || _page$register2 === void 0 || (_page$register2 = _page$register2.terms) === null || _page$register2 === void 0 ? void 0 : _page$register2.map((term) => {
						var _term$name, _term$name2, _term$name3, _term$name4, _term$name5, _term$name6;
						return {
							name: {
								original: ((_term$name = term.name) === null || _term$name === void 0 ? void 0 : _term$name.original) || "",
								en: ((_term$name2 = term.name) === null || _term$name2 === void 0 ? void 0 : _term$name2.en) || "",
								"zh-CN": ((_term$name3 = term.name) === null || _term$name3 === void 0 ? void 0 : _term$name3["zh-CN"]) || "",
								"zh-HK": ((_term$name4 = term.name) === null || _term$name4 === void 0 ? void 0 : _term$name4["zh-HK"]) || "",
								ja: ((_term$name5 = term.name) === null || _term$name5 === void 0 ? void 0 : _term$name5["ja"]) || "",
								pt: ((_term$name6 = term.name) === null || _term$name6 === void 0 ? void 0 : _term$name6["pt"]) || ""
							},
							url: term.url || ""
						};
					})) || []
				};
				pageSettingValue.loginPage = {
					sameAsRegister: (_page$login$same_as_r = (_page$login = page.login) === null || _page$login === void 0 ? void 0 : _page$login.same_as_register) !== null && _page$login$same_as_r !== void 0 ? _page$login$same_as_r : true,
					settings: ((_page$login2 = page.login) === null || _page$login2 === void 0 ? void 0 : _page$login2.same_as_register) ? void 0 : {
						backgroundImage: ((_page$login3 = page.login) === null || _page$login3 === void 0 ? void 0 : _page$login3.background_image_url) || "",
						termsConditions: ((_page$login4 = page.login) === null || _page$login4 === void 0 || (_page$login4 = _page$login4.terms) === null || _page$login4 === void 0 ? void 0 : _page$login4.map((term) => {
							var _term$name7, _term$name8, _term$name9, _term$name10, _term$name11, _term$name12;
							return {
								name: {
									original: ((_term$name7 = term.name) === null || _term$name7 === void 0 ? void 0 : _term$name7.original) || "",
									en: ((_term$name8 = term.name) === null || _term$name8 === void 0 ? void 0 : _term$name8.en) || "",
									"zh-CN": ((_term$name9 = term.name) === null || _term$name9 === void 0 ? void 0 : _term$name9["zh-CN"]) || "",
									"zh-HK": ((_term$name10 = term.name) === null || _term$name10 === void 0 ? void 0 : _term$name10["zh-HK"]) || "",
									ja: ((_term$name11 = term.name) === null || _term$name11 === void 0 ? void 0 : _term$name11["ja"]) || "",
									pt: ((_term$name12 = term.name) === null || _term$name12 === void 0 ? void 0 : _term$name12["pt"]) || ""
								},
								url: term.url || ""
							};
						})) || []
					}
				};
			}
			const authenticationMethodsValue = {};
			if (auth) {
				var _auth$method, _auth$method2, _auth$method3, _auth$method4, _auth$method5;
				authenticationMethodsValue.mode = auth.mode || "default";
				authenticationMethodsValue.methods = {};
				if ((_auth$method = auth.method) === null || _auth$method === void 0 ? void 0 : _auth$method.email) {
					var _auth$method$email$en, _auth$method$email$so;
					authenticationMethodsValue.methods.email = {
						enabled: (_auth$method$email$en = auth.method.email.enabled) !== null && _auth$method$email$en !== void 0 ? _auth$method$email$en : true,
						sort: (_auth$method$email$so = auth.method.email.sort) !== null && _auth$method$email$so !== void 0 ? _auth$method$email$so : 0
					};
				}
				if ((_auth$method2 = auth.method) === null || _auth$method2 === void 0 ? void 0 : _auth$method2.phone) {
					var _auth$method$phone$en, _auth$method$phone$so;
					authenticationMethodsValue.methods.phoneNumber = {
						enabled: (_auth$method$phone$en = auth.method.phone.enabled) !== null && _auth$method$phone$en !== void 0 ? _auth$method$phone$en : true,
						sort: (_auth$method$phone$so = auth.method.phone.sort) !== null && _auth$method$phone$so !== void 0 ? _auth$method$phone$so : 1
					};
				}
				if ((_auth$method3 = auth.method) === null || _auth$method3 === void 0 ? void 0 : _auth$method3.facebook) {
					var _auth$method$facebook, _auth$method$facebook2;
					authenticationMethodsValue.methods.facebook = {
						enabled: (_auth$method$facebook = auth.method.facebook.enabled) !== null && _auth$method$facebook !== void 0 ? _auth$method$facebook : true,
						sort: (_auth$method$facebook2 = auth.method.facebook.sort) !== null && _auth$method$facebook2 !== void 0 ? _auth$method$facebook2 : 2
					};
				}
				if ((_auth$method4 = auth.method) === null || _auth$method4 === void 0 ? void 0 : _auth$method4.apple) {
					var _auth$method$apple$en, _auth$method$apple$so;
					authenticationMethodsValue.methods.apple = {
						enabled: (_auth$method$apple$en = auth.method.apple.enabled) !== null && _auth$method$apple$en !== void 0 ? _auth$method$apple$en : true,
						sort: (_auth$method$apple$so = auth.method.apple.sort) !== null && _auth$method$apple$so !== void 0 ? _auth$method$apple$so : 3
					};
				}
				if ((_auth$method5 = auth.method) === null || _auth$method5 === void 0 ? void 0 : _auth$method5.guest) {
					var _auth$method$guest$en, _auth$method$guest$so;
					authenticationMethodsValue.methods.guest = {
						enabled: (_auth$method$guest$en = auth.method.guest.enabled) !== null && _auth$method$guest$en !== void 0 ? _auth$method$guest$en : false,
						sort: (_auth$method$guest$so = auth.method.guest.sort) !== null && _auth$method$guest$so !== void 0 ? _auth$method$guest$so : 4
					};
				}
			}
			setInternalValue({
				pageSetting: pageSettingValue,
				authenticationMethods: authenticationMethodsValue
			});
		}
	}, [channelData]);
	const handlePageSettingChange = useCallback((pageSettingValue) => {
		setInternalValue((prev) => {
			if (JSON.stringify(prev.pageSetting) !== JSON.stringify(pageSettingValue)) return _objectSpread2(_objectSpread2({}, prev), {}, { pageSetting: pageSettingValue });
			return prev;
		});
	}, []);
	const handleAuthenticationMethodsChange = useCallback((authMethodsValue) => {
		setInternalValue((prev) => {
			if (JSON.stringify(prev.authenticationMethods) !== JSON.stringify(authMethodsValue)) return _objectSpread2(_objectSpread2({}, prev), {}, { authenticationMethods: authMethodsValue });
			return prev;
		});
	}, []);
	const handleCollectInfoChange = useCallback((collectInfoValue) => {
		setInternalValue((prev) => {
			if (JSON.stringify(prev.collectInfo) !== JSON.stringify(collectInfoValue)) return _objectSpread2(_objectSpread2({}, prev), {}, { collectInfo: collectInfoValue });
			return prev;
		});
	}, []);
	const transformToNewFormat = (value, currentTab) => {
		const { pageSetting, authenticationMethods } = value;
		const result = {};
		console.log("pageSetting data:", pageSetting);
		const shouldTransformPage = !currentTab || currentTab === "pageSetting";
		const shouldTransformAuth = !currentTab || currentTab === "authenticationMethods";
		if (shouldTransformPage) {
			var _pageSetting$register, _pageSetting$register2, _pageSetting$loginPag, _pageSetting$loginPag2, _pageSetting$loginPag3, _pageSetting$loginPag4, _pageSetting$loginPag5, _pageSetting$loginPag6;
			result.page = {
				register: {
					background_image_url: (pageSetting === null || pageSetting === void 0 || (_pageSetting$register = pageSetting.registerPage) === null || _pageSetting$register === void 0 ? void 0 : _pageSetting$register.backgroundImage) || "",
					terms: (pageSetting === null || pageSetting === void 0 || (_pageSetting$register2 = pageSetting.registerPage) === null || _pageSetting$register2 === void 0 || (_pageSetting$register2 = _pageSetting$register2.termsConditions) === null || _pageSetting$register2 === void 0 ? void 0 : _pageSetting$register2.map((term) => ({
						name: {
							original: term.name.original || "",
							en: term.name.en || "",
							"zh-CN": term.name["zh-CN"] || "",
							"zh-HK": term.name["zh-HK"] || "",
							ja: term.name["ja"] || "",
							pt: term.name["pt"] || ""
						},
						url: term.url || ""
					}))) || []
				},
				login: {
					same_as_register: (_pageSetting$loginPag = pageSetting === null || pageSetting === void 0 || (_pageSetting$loginPag2 = pageSetting.loginPage) === null || _pageSetting$loginPag2 === void 0 ? void 0 : _pageSetting$loginPag2.sameAsRegister) !== null && _pageSetting$loginPag !== void 0 ? _pageSetting$loginPag : true,
					background_image_url: (pageSetting === null || pageSetting === void 0 || (_pageSetting$loginPag3 = pageSetting.loginPage) === null || _pageSetting$loginPag3 === void 0 ? void 0 : _pageSetting$loginPag3.sameAsRegister) ? null : (pageSetting === null || pageSetting === void 0 || (_pageSetting$loginPag4 = pageSetting.loginPage) === null || _pageSetting$loginPag4 === void 0 || (_pageSetting$loginPag4 = _pageSetting$loginPag4.settings) === null || _pageSetting$loginPag4 === void 0 ? void 0 : _pageSetting$loginPag4.backgroundImage) || null,
					terms: (pageSetting === null || pageSetting === void 0 || (_pageSetting$loginPag5 = pageSetting.loginPage) === null || _pageSetting$loginPag5 === void 0 ? void 0 : _pageSetting$loginPag5.sameAsRegister) ? [] : (pageSetting === null || pageSetting === void 0 || (_pageSetting$loginPag6 = pageSetting.loginPage) === null || _pageSetting$loginPag6 === void 0 || (_pageSetting$loginPag6 = _pageSetting$loginPag6.settings) === null || _pageSetting$loginPag6 === void 0 || (_pageSetting$loginPag6 = _pageSetting$loginPag6.termsConditions) === null || _pageSetting$loginPag6 === void 0 ? void 0 : _pageSetting$loginPag6.map((term) => ({
						name: {
							original: term.name.original || "",
							en: term.name.en || "",
							"zh-CN": term.name["zh-CN"] || "",
							"zh-HK": term.name["zh-HK"] || "",
							ja: term.name["ja"] || "",
							pt: term.name["pt"] || ""
						},
						url: term.url || ""
					}))) || []
				}
			};
		}
		if (shouldTransformAuth) {
			var _methods$email$enable, _methods$email, _methods$email$sort, _methods$email2, _methods$phoneNumber$, _methods$phoneNumber, _methods$phoneNumber$2, _methods$phoneNumber2, _methods$facebook$ena, _methods$facebook, _methods$facebook$sor, _methods$facebook2, _methods$apple$enable, _methods$apple, _methods$apple$sort, _methods$apple2, _methods$guest$enable, _methods$guest, _methods$guest$sort, _methods$guest2;
			const methods = (authenticationMethods === null || authenticationMethods === void 0 ? void 0 : authenticationMethods.methods) || {};
			console.log("authenticationMethods:", authenticationMethods);
			console.log("methods config:", methods);
			result.auth = {
				mode: (authenticationMethods === null || authenticationMethods === void 0 ? void 0 : authenticationMethods.mode) || "default",
				method: {
					email: {
						enabled: (_methods$email$enable = (_methods$email = methods.email) === null || _methods$email === void 0 ? void 0 : _methods$email.enabled) !== null && _methods$email$enable !== void 0 ? _methods$email$enable : true,
						sort: (_methods$email$sort = (_methods$email2 = methods.email) === null || _methods$email2 === void 0 ? void 0 : _methods$email2.sort) !== null && _methods$email$sort !== void 0 ? _methods$email$sort : 0
					},
					phone: {
						enabled: (_methods$phoneNumber$ = (_methods$phoneNumber = methods.phoneNumber) === null || _methods$phoneNumber === void 0 ? void 0 : _methods$phoneNumber.enabled) !== null && _methods$phoneNumber$ !== void 0 ? _methods$phoneNumber$ : true,
						sort: (_methods$phoneNumber$2 = (_methods$phoneNumber2 = methods.phoneNumber) === null || _methods$phoneNumber2 === void 0 ? void 0 : _methods$phoneNumber2.sort) !== null && _methods$phoneNumber$2 !== void 0 ? _methods$phoneNumber$2 : 1
					},
					facebook: {
						enabled: (_methods$facebook$ena = (_methods$facebook = methods.facebook) === null || _methods$facebook === void 0 ? void 0 : _methods$facebook.enabled) !== null && _methods$facebook$ena !== void 0 ? _methods$facebook$ena : true,
						sort: (_methods$facebook$sor = (_methods$facebook2 = methods.facebook) === null || _methods$facebook2 === void 0 ? void 0 : _methods$facebook2.sort) !== null && _methods$facebook$sor !== void 0 ? _methods$facebook$sor : 2
					},
					apple: {
						enabled: (_methods$apple$enable = (_methods$apple = methods.apple) === null || _methods$apple === void 0 ? void 0 : _methods$apple.enabled) !== null && _methods$apple$enable !== void 0 ? _methods$apple$enable : true,
						sort: (_methods$apple$sort = (_methods$apple2 = methods.apple) === null || _methods$apple2 === void 0 ? void 0 : _methods$apple2.sort) !== null && _methods$apple$sort !== void 0 ? _methods$apple$sort : 3
					},
					guest: {
						enabled: (_methods$guest$enable = (_methods$guest = methods.guest) === null || _methods$guest === void 0 ? void 0 : _methods$guest.enabled) !== null && _methods$guest$enable !== void 0 ? _methods$guest$enable : false,
						sort: (_methods$guest$sort = (_methods$guest2 = methods.guest) === null || _methods$guest2 === void 0 ? void 0 : _methods$guest2.sort) !== null && _methods$guest$sort !== void 0 ? _methods$guest$sort : 4
					}
				}
			};
		}
		return result;
	};
	const handleSave = function() {
		var _ref = _asyncToGenerator(function* () {
			try {
				var _channelData$metadata2;
				if (activeTab === "pageSetting" && pageSettingRef.current) yield pageSettingRef.current.validateFields();
				const transformedValue = transformToNewFormat(internalValue, activeTab);
				const mergedData = _objectSpread2(_objectSpread2({}, (channelData === null || channelData === void 0 || (_channelData$metadata2 = channelData.metadata) === null || _channelData$metadata2 === void 0 ? void 0 : _channelData$metadata2.register_login) || {}), transformedValue);
				console.log("transformedValue", transformedValue, internalValue);
				console.log("mergedData", mergedData);
				saveData(mergedData);
			} catch (error) {
				console.error("表单校验失败:", error);
				message.error(locales.getText("channel.auth.setting.validation.error"));
			}
		});
		return function handleSave() {
			return _ref.apply(this, arguments);
		};
	}();
	const allTabItems = useMemo(() => ({
		pageSetting: {
			key: "pageSetting",
			label: locales.getText("channel.auth.setting.tab.pageSetting"),
			children: /* @__PURE__ */ React.createElement(PageSetting, {
				ref: pageSettingRef,
				value: internalValue.pageSetting,
				onChange: handlePageSettingChange,
				showRegisterPage,
				showImageUpload: false
			})
		},
		authenticationMethods: {
			key: "authenticationMethods",
			label: locales.getText("channel.auth.setting.tab.authenticationMethods"),
			children: /* @__PURE__ */ React.createElement(AuthenticationMethods, {
				value: internalValue.authenticationMethods,
				onChange: handleAuthenticationMethodsChange
			})
		},
		collectInfo: {
			key: "collectInfo",
			label: locales.getText("channel.auth.setting.tab.collectInfo"),
			children: /* @__PURE__ */ React.createElement(CollectInfo, {
				value: internalValue.collectInfo,
				onChange: handleCollectInfoChange
			})
		}
	}), [
		internalValue.pageSetting,
		internalValue.authenticationMethods,
		internalValue.collectInfo,
		showRegisterPage,
		handlePageSettingChange,
		handleAuthenticationMethodsChange,
		handleCollectInfoChange
	]);
	const tabItems = useMemo(() => {
		return displayTabs.map((tabKey) => allTabItems[tabKey]);
	}, [displayTabs, allTabItems]);
	if (loading) return /* @__PURE__ */ React.createElement("div", {
		className: classNames("channel-auth-setting", className),
		style: _objectSpread2(_objectSpread2({}, style), {}, {
			display: "flex",
			justifyContent: "center",
			alignItems: "center",
			minHeight: "400px"
		})
	}, /* @__PURE__ */ React.createElement(Spin, { size: "large" }));
	return /* @__PURE__ */ React.createElement("div", {
		className: classNames("onlineshopauth", className),
		style
	}, /* @__PURE__ */ React.createElement("div", { className: "onlineshopauth-header" }, /* @__PURE__ */ React.createElement(Title, {
		level: 1,
		className: "onlineshopauth-title"
	}, locales.getText("channel.auth.setting.title")), /* @__PURE__ */ React.createElement(Paragraph, { className: "onlineshopauth-description" }, locales.getText("channel.auth.setting.description"))), /* @__PURE__ */ React.createElement("div", { className: "onlineshopauth-tabs" }, /* @__PURE__ */ React.createElement(Tabs, {
		activeKey: activeTab,
		onChange: setActiveTab,
		items: tabItems
	})), /* @__PURE__ */ React.createElement("div", { className: "onlineshopauth-footer" }, /* @__PURE__ */ React.createElement(Button, {
		type: "primary",
		onClick: handleSave
	}, locales.getText("channel.auth.setting.button.save"))));
};
//#endregion
export { Onlineshopauth as default };
