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 useEngineContext from "../../../../../hooks/useEngineContext.js";
import { updateDeviceProfile } from "../../serve.js";
import { useTranslation } from "../../hooks.js";
import { unsavedChangesConfirm } from "../UnsavedConfirmModal/index.js";
import { toUpdatePayload } from "./utils.js";
import BasicForm from "./BasicForm.js";
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Alert, Button, Spin, message } from "antd";
import { locales } from "@pisell/utils";
import { PisellMenu } from "@pisell/materials";
import { ArrowLeftOutlined } from "@ant-design/icons";
import "./index.less";
//#region src/plus/saasDevice/deviceProfile/components/ProfileSetting/index.tsx
const _excluded = ["id"];
const getText = locales.getText;
const LowCodePage$1 = (props) => {
	var _context$appHelper;
	const { id } = props, others = _objectWithoutProperties(props, _excluded);
	const { RenderLowCodeByKey, getRenderLowCodeByKey } = ((_context$appHelper = useEngineContext().appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	const Com = getRenderLowCodeByKey ? getRenderLowCodeByKey === null || getRenderLowCodeByKey === void 0 ? void 0 : getRenderLowCodeByKey() : RenderLowCodeByKey;
	if (!Com) return /* @__PURE__ */ React.createElement("div", null, "RenderLowCodeByKey is not found");
	return /* @__PURE__ */ React.createElement(Com, _objectSpread2(_objectSpread2({}, others), {}, {
		id,
		key: id
	}));
};
const BASIC_KEY = "basic";
const ProfileSetting = (props) => {
	var _context$appHelper2, _context$appHelper2$g, _model$data;
	const context = useEngineContext();
	const app = (context === null || context === void 0 || (_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 || (_context$appHelper2 = _context$appHelper2.utils) === null || _context$appHelper2 === void 0 || (_context$appHelper2$g = _context$appHelper2.getApp) === null || _context$appHelper2$g === void 0 ? void 0 : _context$appHelper2$g.call(_context$appHelper2)) || {};
	const { record, deviceModel, deviceType, scene = "profile", onBack } = props;
	const translation = useTranslation();
	const [model, setModel] = useState(deviceModel);
	const [typeItem, setTypeItem] = useState();
	const [bootstrapping, setBootstrapping] = useState(true);
	useEffect(() => {
		if (!record) return;
		_asyncToGenerator(function* () {
			try {
				if (deviceType) setTypeItem(deviceType);
				if (deviceModel) setModel(deviceModel);
			} catch (error) {
				app.logger.addLog({
					type: "error",
					title: "加载配置模板上下文失败",
					metadata: error
				});
			} finally {
				setBootstrapping(false);
			}
		})();
	}, []);
	const profileStructure = model === null || model === void 0 || (_model$data = model.data) === null || _model$data === void 0 ? void 0 : _model$data.profile_structure;
	const extraTabs = useMemo(() => {
		var _profileStructure$tab;
		return (profileStructure === null || profileStructure === void 0 ? void 0 : profileStructure.required) ? [...(_profileStructure$tab = profileStructure.tabs) !== null && _profileStructure$tab !== void 0 ? _profileStructure$tab : []].sort((a, b) => {
			var _a$sort, _b$sort;
			return ((_a$sort = a === null || a === void 0 ? void 0 : a.sort) !== null && _a$sort !== void 0 ? _a$sort : 0) - ((_b$sort = b === null || b === void 0 ? void 0 : b.sort) !== null && _b$sort !== void 0 ? _b$sort : 0);
		}) : [];
	}, [profileStructure]);
	const menuItems = useMemo(() => [{
		key: BASIC_KEY,
		label: getText("pisell2.saas.device-profile.setting.menu.basic")
	}, ...(extraTabs === null || extraTabs === void 0 ? void 0 : extraTabs.map((t, i) => ({
		key: `tab-${i}`,
		label: translation(t.title) || `Tab ${i + 1}`
	}))) || []], [extraTabs]);
	const [activeKey, setActiveKey] = useState(BASIC_KEY);
	const formRef = useRef(null);
	const [dirty, setDirty] = useState(false);
	const [saving, setSaving] = useState(false);
	const [displayName, setDisplayName] = useState(record === null || record === void 0 ? void 0 : record.name);
	if (!record) return null;
	const title = translation(displayName) || record.code;
	const subtitle = getText("pisell2.saas.device-profile.setting.subtitle");
	const switchKey = (next) => {
		if (next === activeKey) return;
		if (dirty && activeKey === BASIC_KEY) {
			unsavedChangesConfirm(() => {
				setDirty(false);
				setActiveKey(next);
			});
			return;
		}
		setActiveKey(next);
	};
	const handleBack = () => {
		if (dirty) {
			unsavedChangesConfirm(() => {
				setDirty(false);
				onBack();
			});
			return;
		}
		onBack();
	};
	const handleSave = function() {
		var _ref = _asyncToGenerator(function* () {
			if (!formRef.current) return;
			try {
				const values = yield formRef.current.getValues();
				setSaving(true);
				yield updateDeviceProfile(record.id, toUpdatePayload(values));
				setDisplayName(values.name);
				message.success(getText("pisell2.saas.device-profile.message.updateSuccess"));
				setDirty(false);
			} catch (error) {
				if (error && error.errorFields) return;
				app.logger.addLog({
					type: "error",
					title: "更新配置模板失败",
					metadata: error
				});
			} finally {
				setSaving(false);
			}
		});
		return function handleSave() {
			return _ref.apply(this, arguments);
		};
	}();
	const activeTab = activeKey === BASIC_KEY ? null : extraTabs[Number(activeKey.replace("tab-", ""))];
	return /* @__PURE__ */ React.createElement("div", { className: "saas-device-profile-setting" }, /* @__PURE__ */ React.createElement("div", { className: "saas-device-profile-setting__header" }, /* @__PURE__ */ React.createElement("div", { className: "saas-device-profile-setting__header-left" }, /* @__PURE__ */ React.createElement(Button, {
		type: "text",
		icon: /* @__PURE__ */ React.createElement(ArrowLeftOutlined, null),
		onClick: handleBack
	}), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "saas-device-profile-setting__title" }, title), subtitle ? /* @__PURE__ */ React.createElement("div", { className: "saas-device-profile-setting__subtitle" }, subtitle) : null))), /* @__PURE__ */ React.createElement("div", { className: "saas-device-profile-setting__alert-wrap" }, /* @__PURE__ */ React.createElement(Alert, {
		type: "warning",
		showIcon: true,
		message: getText("pisell2.saas.device-profile.setting.saveWarning")
	})), /* @__PURE__ */ React.createElement("div", { className: "saas-device-profile-setting__main" }, /* @__PURE__ */ React.createElement("div", { className: "saas-device-profile-setting__menu-card" }, /* @__PURE__ */ React.createElement(PisellMenu, {
		mode: "inline",
		theme: "light",
		dataSource: menuItems,
		selectedKeys: [activeKey],
		onSelect: ({ key }) => switchKey(String(key))
	})), /* @__PURE__ */ React.createElement("div", {
		className: "saas-device-profile-setting__content-card",
		style: { padding: activeKey === BASIC_KEY ? "24px" : 0 }
	}, bootstrapping ? /* @__PURE__ */ React.createElement("div", { className: "saas-device-profile-setting__loading-wrap" }, /* @__PURE__ */ React.createElement(Spin, null)) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", { style: { display: activeKey === BASIC_KEY ? "block" : "none" } }, /* @__PURE__ */ React.createElement("div", { className: "saas-device-profile-setting__section" }, /* @__PURE__ */ React.createElement("div", { className: "saas-device-profile-setting__section-title" }, getText("pisell2.saas.device-profile.setting.section.basicInfo")), /* @__PURE__ */ React.createElement("div", { className: "saas-device-profile-setting__subtitle" }, getText("pisell2.saas.device-profile.setting.section.basicInfoDesc"))), /* @__PURE__ */ React.createElement(BasicForm, {
		ref: formRef,
		mode: "edit",
		deviceType: typeItem,
		deviceModels: model ? [model] : [],
		initialValue: record,
		onDirty: () => setDirty(true)
	}), /* @__PURE__ */ React.createElement("div", { className: "saas-device-profile-setting__save-actions" }, /* @__PURE__ */ React.createElement(Button, {
		type: "primary",
		size: "large",
		loading: saving,
		onClick: handleSave
	}, getText("pisell2.saas.device-profile.common.save")))), activeKey !== BASIC_KEY && activeTab ? /* @__PURE__ */ React.createElement(LowCodePage$1, {
		id: activeTab === null || activeTab === void 0 ? void 0 : activeTab.page_id,
		scene,
		sceneRequestId: record === null || record === void 0 ? void 0 : record.id
	}) : null))));
};
//#endregion
export { ProfileSetting as default };
