const require_runtime = require("../../_virtual/_rolldown/runtime.js");
const require_objectSpread2 = require("../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js");
const require_asyncToGenerator = require("../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_useEngineContext = require("../../hooks/useEngineContext.js");
const require_withResponsive = require("../../responsive/withResponsive.js");
const require_index = require("../../utils/index.js");
const require_WebPosLoginCpt = require("./WebPosLoginCpt.js");
const require_service = require("./service.js");
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_utils = require("@pisell/utils");
let _pisell_materials = require("@pisell/materials");
//#region src/plus/webPosLogin/WebPosLogin.tsx
const useSearchParams = () => {
	return new URLSearchParams(window.location.search);
};
const WebPosLogin = (props) => {
	var _context$appHelper, _context$appHelper2, _mediaConfig$loginBgM, _context$engine;
	const context = require_useEngineContext.default();
	const { getApp = () => ({}), reloadAfterLogin, pisellos } = (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils;
	const { mediaConfig, isIotLogin } = (_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 ? void 0 : _context$appHelper2.constants;
	const { backgroundImage, step: propsStep = "login", loginSlot, config, variant } = props;
	const [storeList, setStoreList] = (0, react.useState)(() => {
		var _app$storage;
		const app = getApp();
		const storeList = app === null || app === void 0 || (_app$storage = app.storage) === null || _app$storage === void 0 ? void 0 : _app$storage.getStorage("storeList");
		if (!storeList) return [];
		return JSON.parse(storeList);
	});
	console.log("loginSlot", loginSlot);
	const urlStep = useSearchParams().get("step");
	const [step, setStep] = (0, react.useState)(() => {
		if (urlStep && urlStep !== "undefined") return urlStep;
		return props.step || "login";
	});
	const [userInfo, setUserInfo] = (0, react.useState)(() => {
		var _app$storage2;
		const app = getApp();
		const userInfo = (app === null || app === void 0 || (_app$storage2 = app.storage) === null || _app$storage2 === void 0 ? void 0 : _app$storage2.getStorage("userInfo")) || "{}";
		const userInfoObj = JSON.parse(userInfo);
		return {
			name: (userInfoObj === null || userInfoObj === void 0 ? void 0 : userInfoObj.name) || "",
			avatar: (userInfoObj === null || userInfoObj === void 0 ? void 0 : userInfoObj.avatar) || ""
		};
	});
	const [selectedStore, setSelectedStore] = (0, react.useState)(() => {
		var _app$storage3;
		const app = getApp();
		const selectedStore = (app === null || app === void 0 || (_app$storage3 = app.storage) === null || _app$storage3 === void 0 ? void 0 : _app$storage3.getStorage("selectedStore")) || "{}";
		return JSON.parse(selectedStore);
	});
	const [deviceList, setDeviceList] = (0, react.useState)(() => {
		var _app$storage4;
		const app = getApp();
		const deviceList = (app === null || app === void 0 || (_app$storage4 = app.storage) === null || _app$storage4 === void 0 ? void 0 : _app$storage4.getStorage("deviceList")) || "[]";
		return JSON.parse(deviceList);
	});
	const [lastUsedStoreId, setLastUsedStoreId] = (0, react.useState)(() => {
		var _app$storage5, _JSON$parse;
		const app = getApp();
		const lastUsedStore = (app === null || app === void 0 || (_app$storage5 = app.storage) === null || _app$storage5 === void 0 ? void 0 : _app$storage5.getStorage("selectedStore")) || "{}";
		const lastUsedStoreId = ((_JSON$parse = JSON.parse(lastUsedStore)) === null || _JSON$parse === void 0 ? void 0 : _JSON$parse.id) || 0;
		return parseInt(lastUsedStoreId);
	});
	const [lastUsedDeviceId, setLastUsedDeviceId] = (0, react.useState)(() => {
		var _app$storage6, _JSON$parse2;
		const app = getApp();
		const lastUsedDevice = (app === null || app === void 0 || (_app$storage6 = app.storage) === null || _app$storage6 === void 0 ? void 0 : _app$storage6.getStorage("lastUsedDevice")) || "{}";
		const lastUsedDeviceId = ((_JSON$parse2 = JSON.parse(lastUsedDevice)) === null || _JSON$parse2 === void 0 ? void 0 : _JSON$parse2.id) || 0;
		return parseInt(lastUsedDeviceId);
	});
	const [isShowGoBack, setIsShowGoBack] = (0, react.useState)(true);
	require_index.request.setRequest(context.appHelper.utils.request);
	/**
	* 登录成功
	* @param res 登录信息
	*/
	const onLoginSuccess = function() {
		var _ref = require_asyncToGenerator._asyncToGenerator(function* (res) {
			var _app$getPlugin, _app$storage7, _res$account, _res$account2, _app$storage8;
			const app = getApp();
			if (!res) return;
			app === null || app === void 0 || (_app$getPlugin = app.getPlugin("token")) === null || _app$getPlugin === void 0 || _app$getPlugin.set(res === null || res === void 0 ? void 0 : res.authorization);
			app === null || app === void 0 || (_app$storage7 = app.storage) === null || _app$storage7 === void 0 || _app$storage7.setStorage("account", JSON.stringify(require_objectSpread2._objectSpread2(require_objectSpread2._objectSpread2({}, res === null || res === void 0 ? void 0 : res.account), res)));
			setUserInfo({
				name: (res === null || res === void 0 || (_res$account = res.account) === null || _res$account === void 0 ? void 0 : _res$account.name) || "",
				avatar: (res === null || res === void 0 || (_res$account2 = res.account) === null || _res$account2 === void 0 ? void 0 : _res$account2.avatar) || ""
			});
			const tenant = yield require_service.getTenant();
			app === null || app === void 0 || (_app$storage8 = app.storage) === null || _app$storage8 === void 0 || _app$storage8.setStorage("storeList", JSON.stringify(tenant || {}));
			const lastUsedStore = tenant === null || tenant === void 0 ? void 0 : tenant.find((item) => item.id == lastUsedStoreId);
			if ((tenant === null || tenant === void 0 ? void 0 : tenant.length) === 1) yield handleStoreSelect(tenant[0], false);
			else if (lastUsedStore) yield handleStoreSelect(lastUsedStore, false);
			else setStep("store");
			setStoreList(tenant);
		});
		return function onLoginSuccess(_x) {
			return _ref.apply(this, arguments);
		};
	}();
	/**
	* 返回
	*/
	const onBack = () => {
		if (step === "store") setStep("login");
		else if (step === "device") setStep("store");
	};
	/**
	* 选择店铺
	* @param shopInfo 店铺信息
	*/
	const handleStoreSelect = function() {
		var _ref2 = require_asyncToGenerator._asyncToGenerator(function* (shopInfo, isShowGoBack = true) {
			var _shopInfo$tenant, _app$logger;
			const app = getApp();
			if (lastUsedStoreId !== shopInfo.id) {
				var _pisellos$server, _pisellos$server$clea;
				yield (_pisellos$server = pisellos.server) === null || _pisellos$server === void 0 || (_pisellos$server$clea = _pisellos$server.clearAllIndexDB) === null || _pisellos$server$clea === void 0 ? void 0 : _pisellos$server$clea.call(_pisellos$server);
				if (pisellos.server) pisellos.server = null;
			}
			if (isIotLogin) {
				if (lastUsedStoreId !== shopInfo.id) {
					var _app$storage9;
					app === null || app === void 0 || (_app$storage9 = app.storage) === null || _app$storage9 === void 0 || _app$storage9.removeStorage("iotDevice");
				}
			}
			app.storage.setStorage("tenant_domain", shopInfo === null || shopInfo === void 0 || (_shopInfo$tenant = shopInfo.tenant) === null || _shopInfo$tenant === void 0 ? void 0 : _shopInfo$tenant.default_domain);
			app.storage.setStorage("selectedStore", JSON.stringify(shopInfo));
			setLastUsedStoreId(shopInfo.id);
			setSelectedStore(shopInfo);
			app === null || app === void 0 || (_app$logger = app.logger) === null || _app$logger === void 0 || _app$logger.addLog({
				type: "info",
				title: "选择店铺页-点击店铺",
				metadata: shopInfo || {}
			});
			try {
				var _res$mypisell_data, _app$getPlugin2, _res$mypisell_data2, _app$logger2;
				const res = yield require_service.getTenantDetail();
				if (!res) return;
				if (!(res === null || res === void 0 || (_res$mypisell_data = res.mypisell_data) === null || _res$mypisell_data === void 0 ? void 0 : _res$mypisell_data.account_token)) {
					(0, _pisell_materials.PisellToast)({ content: _pisell_utils.locales.getText("webpos-login-store-data-missing") });
					return;
				}
				app === null || app === void 0 || (_app$getPlugin2 = app.getPlugin("token")) === null || _app$getPlugin2 === void 0 || _app$getPlugin2.set(res === null || res === void 0 || (_res$mypisell_data2 = res.mypisell_data) === null || _res$mypisell_data2 === void 0 ? void 0 : _res$mypisell_data2.account_token, "pisellV1Token");
				if (res.nocobase_tenant_token) {
					var _app$getPlugin3;
					app === null || app === void 0 || (_app$getPlugin3 = app.getPlugin("token")) === null || _app$getPlugin3 === void 0 || _app$getPlugin3.set(res.nocobase_tenant_token, "nocobaseToken");
				}
				if (isIotLogin) {
					var _JSON$parse3, _app$storage10;
					if ((_JSON$parse3 = JSON.parse((app === null || app === void 0 || (_app$storage10 = app.storage) === null || _app$storage10 === void 0 ? void 0 : _app$storage10.getStorage("iotDevice")) || "{}")) === null || _JSON$parse3 === void 0 ? void 0 : _JSON$parse3.number) {
						var _useSearchParams;
						const _pageSource = (_useSearchParams = useSearchParams()) === null || _useSearchParams === void 0 ? void 0 : _useSearchParams.get("pageSource");
						console.log(_pageSource, "pageSource");
						if (_pageSource !== "pinLoginStore") {
							var _app$storage11;
							app === null || app === void 0 || (_app$storage11 = app.storage) === null || _app$storage11 === void 0 || _app$storage11.setStorage("isLogin", true);
							reloadAfterLogin === null || reloadAfterLogin === void 0 || reloadAfterLogin();
						} else {
							var _app$history;
							app === null || app === void 0 || (_app$history = app.history) === null || _app$history === void 0 || (_app$history = _app$history.instance) === null || _app$history === void 0 || _app$history.replace("/");
						}
						return;
					}
					setStep("device");
				} else yield getDeviceListFunction();
				setIsShowGoBack(isShowGoBack);
				app === null || app === void 0 || (_app$logger2 = app.logger) === null || _app$logger2 === void 0 || _app$logger2.addLog({
					type: "info",
					title: "选择店铺页-选择店铺成功",
					metadata: res || {}
				});
			} catch (err) {
				var _app$logger3;
				app === null || app === void 0 || (_app$logger3 = app.logger) === null || _app$logger3 === void 0 || _app$logger3.addLog({
					type: "error",
					title: "登录页-选择店铺失败",
					metadata: err || {}
				});
			}
		});
		return function handleStoreSelect(_x2) {
			return _ref2.apply(this, arguments);
		};
	}();
	const getDeviceListFunction = function() {
		var _ref3 = require_asyncToGenerator._asyncToGenerator(function* () {
			var _localStorage, _localStorage$getItem;
			if (isIotLogin) return;
			const app = getApp();
			const localeType = ((_localStorage = localStorage) === null || _localStorage === void 0 || (_localStorage$getItem = _localStorage.getItem) === null || _localStorage$getItem === void 0 ? void 0 : _localStorage$getItem.call(_localStorage, "pisell_app_channel")) || "";
			const res = yield require_service.getDeviceList({
				type: !localeType || localeType === "pos" ? "terminal" : localeType,
				with: ["client"]
			});
			if (!res) return;
			if ((res === null || res === void 0 ? void 0 : res.length) > 0) {
				var _app$logger4;
				app === null || app === void 0 || app.storage.setStorage("deviceList", JSON.stringify(res || []));
				setDeviceList(res);
				setStep("device");
				app === null || app === void 0 || (_app$logger4 = app.logger) === null || _app$logger4 === void 0 || _app$logger4.addLog({
					type: "info",
					title: "选择店铺页-获取设备列表成功-有云端设备",
					metadata: res || {}
				});
			} else {
				var _app$logger5;
				app.storage.setStorage("isLogin", true);
				reloadAfterLogin === null || reloadAfterLogin === void 0 || reloadAfterLogin();
				app === null || app === void 0 || (_app$logger5 = app.logger) === null || _app$logger5 === void 0 || _app$logger5.addLog({
					type: "info",
					title: "选择店铺页-获取设备列表成功-没有云端设备",
					metadata: res || {}
				});
			}
		});
		return function getDeviceListFunction() {
			return _ref3.apply(this, arguments);
		};
	}();
	/**
	* 解除设备绑定
	*/
	const handleDissociateDevice = function() {
		var _ref4 = require_asyncToGenerator._asyncToGenerator(function* () {
			var _app$storage12, _boundCloudDevice$cli;
			const app = getApp();
			const boundCloudDevice = JSON.parse((app === null || app === void 0 || (_app$storage12 = app.storage) === null || _app$storage12 === void 0 ? void 0 : _app$storage12.getStorage("boundCloudDevice")) || "{}");
			if ((boundCloudDevice === null || boundCloudDevice === void 0 ? void 0 : boundCloudDevice.number) && (boundCloudDevice === null || boundCloudDevice === void 0 || (_boundCloudDevice$cli = boundCloudDevice.client) === null || _boundCloudDevice$cli === void 0 ? void 0 : _boundCloudDevice$cli.number)) {
				var _boundCloudDevice$cli2;
				const res = yield require_service.dissociateDevice({
					number: boundCloudDevice === null || boundCloudDevice === void 0 || (_boundCloudDevice$cli2 = boundCloudDevice.client) === null || _boundCloudDevice$cli2 === void 0 ? void 0 : _boundCloudDevice$cli2.number,
					dissociateDeviceNumber: boundCloudDevice === null || boundCloudDevice === void 0 ? void 0 : boundCloudDevice.number
				});
				if (!res) {
					var _app$logger6;
					app === null || app === void 0 || (_app$logger6 = app.logger) === null || _app$logger6 === void 0 || _app$logger6.addLog({
						type: "error",
						title: "选择设备页-解除设备绑定失败"
					});
					return false;
				} else {
					var _app$logger7;
					app === null || app === void 0 || (_app$logger7 = app.logger) === null || _app$logger7 === void 0 || _app$logger7.addLog({
						type: "info",
						title: "选择设备页-解除设备绑定成功",
						metadata: res || {}
					});
					return true;
				}
			}
			return true;
		});
		return function handleDissociateDevice() {
			return _ref4.apply(this, arguments);
		};
	}();
	/**
	* 选择设备
	* @param device 设备信息
	*/
	const handleDeviceSelect = function() {
		var _ref5 = require_asyncToGenerator._asyncToGenerator(function* (device) {
			var _app$locales, _app$logger11;
			const app = getApp();
			app.storage.setStorage("lastUsedDevice", JSON.stringify(device));
			setLastUsedDeviceId(device.id);
			const deviceNumber = device === null || device === void 0 ? void 0 : device.number;
			const language = (app === null || app === void 0 || (_app$locales = app.locales) === null || _app$locales === void 0 ? void 0 : _app$locales.getLocale()) || "en";
			let _device = null;
			try {
				const _deviceOrigin = yield app.plugins.get("device").getDeviceInfo({ language });
				_device = (_deviceOrigin === null || _deviceOrigin === void 0 ? void 0 : _deviceOrigin.data) || null;
				app === null || app === void 0 || app.storage.setStorage("localDevice", JSON.stringify(_device || {}));
			} catch (error) {
				var _app$logger8;
				app === null || app === void 0 || (_app$logger8 = app.logger) === null || _app$logger8 === void 0 || _app$logger8.addLog({
					type: "error",
					title: "选择设备页-获取本机设备信息获取失败"
				});
			}
			if (!_device) {
				var _app$logger9;
				app === null || app === void 0 || (_app$logger9 = app.logger) === null || _app$logger9 === void 0 || _app$logger9.addLog({
					type: "error",
					title: "选择设备页-绑定设备失败-本机设备信息获取失败"
				});
				return;
			} else {
				var _app$logger10;
				app === null || app === void 0 || (_app$logger10 = app.logger) === null || _app$logger10 === void 0 || _app$logger10.addLog({
					type: "info",
					title: "选择设备页-绑定设备-本机设备信息获取成功",
					metadata: _device || {}
				});
			}
			if (!(yield handleDissociateDevice())) return;
			const res = yield require_service.selectDevice(require_objectSpread2._objectSpread2({ deviceNumber }, _device || {}));
			if (!res) return;
			app.storage.setStorage("loginStatus", "success");
			app.storage.setStorage("isLogin", true);
			reloadAfterLogin === null || reloadAfterLogin === void 0 || reloadAfterLogin();
			app === null || app === void 0 || app.storage.setStorage("boundCloudDevice", JSON.stringify(res || {}));
			app.pubsub.publish("dataManager", {
				type: "get",
				key: "DEVICE_NUMBER",
				metadata: { msg: "webpo主动推送" }
			});
			app === null || app === void 0 || (_app$logger11 = app.logger) === null || _app$logger11 === void 0 || _app$logger11.addLog({
				type: "info",
				title: "选择设备页-绑定设备成功",
				metadata: res || {}
			});
		});
		return function handleDeviceSelect(_x3) {
			return _ref5.apply(this, arguments);
		};
	}();
	const handleChangeAccount = () => {
		var _app$getPlugin4, _app$getPlugin5, _app$getPlugin6;
		setStep("login");
		const app = getApp();
		app === null || app === void 0 || (_app$getPlugin4 = app.getPlugin("token")) === null || _app$getPlugin4 === void 0 || _app$getPlugin4.remove();
		app === null || app === void 0 || (_app$getPlugin5 = app.getPlugin("token")) === null || _app$getPlugin5 === void 0 || _app$getPlugin5.remove("pisellV1Token");
		app === null || app === void 0 || (_app$getPlugin6 = app.getPlugin("token")) === null || _app$getPlugin6 === void 0 || _app$getPlugin6.remove("nocobaseToken");
	};
	const handleChangeStore = () => {
		setStep("store");
	};
	const handleIotDeviceLinked = () => {
		var _app$storage13;
		const app = getApp();
		app === null || app === void 0 || (_app$storage13 = app.storage) === null || _app$storage13 === void 0 || _app$storage13.setStorage("isLogin", true);
		reloadAfterLogin === null || reloadAfterLogin === void 0 || reloadAfterLogin();
	};
	const handleIotBack = () => {
		var _useSearchParams2;
		const app = getApp();
		const _pageSource = (_useSearchParams2 = useSearchParams()) === null || _useSearchParams2 === void 0 ? void 0 : _useSearchParams2.get("pageSource");
		console.log(_pageSource, "pageSource");
		if (_pageSource === "pinLoginDevice") {
			var _app$history2, _app$history2$goBack;
			app === null || app === void 0 || (_app$history2 = app.history) === null || _app$history2 === void 0 || (_app$history2 = _app$history2.instance) === null || _app$history2 === void 0 || (_app$history2$goBack = _app$history2.goBack) === null || _app$history2$goBack === void 0 || _app$history2$goBack.call(_app$history2);
		} else setStep("store");
	};
	return /* @__PURE__ */ react.default.createElement(require_WebPosLoginCpt.default, {
		loginConfig: config,
		backgroundImage: backgroundImage || ((_mediaConfig$loginBgM = mediaConfig.loginBgMediaConfig) === null || _mediaConfig$loginBgM === void 0 || (_mediaConfig$loginBgM = _mediaConfig$loginBgM[0]) === null || _mediaConfig$loginBgM === void 0 ? void 0 : _mediaConfig$loginBgM.url),
		brandConfig: mediaConfig.loginMediaConfig,
		step,
		showBackButton: isShowGoBack,
		storeList,
		deviceList,
		userInfo,
		selectedStore,
		lastUsedStoreId,
		lastUsedDeviceId,
		locale: (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",
		loading: false,
		loginSlot,
		variant,
		onStoreSelect: handleStoreSelect,
		onDeviceSelect: handleDeviceSelect,
		onChangeAccount: handleChangeAccount,
		onChangeStore: handleChangeStore,
		onBack,
		onLoginSuccess,
		onIotDeviceLinked: handleIotDeviceLinked,
		onIotBack: handleIotBack
	});
};
WebPosLogin.displayName = "WebPosLogin";
var WebPosLogin_default = require_withResponsive.default(WebPosLogin);
//#endregion
exports.default = WebPosLogin_default;
