const require_runtime = require("../../../_virtual/_rolldown/runtime.js");
const require_asyncToGenerator = require("../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js");
const require_useEngineContext = require("../../../hooks/useEngineContext.js");
const require_useLocale = require("../../../hooks/useLocale.js");
const require_index = require("../../../utils/index.js");
const require_index$1 = require("./components/TwoColumnPageLayout/index.js");
const require_index$2 = require("./components/SiderMenuPanel/index.js");
const require_serve = require("./serve.js");
const require_index$3 = require("./components/CreateProfileModal/index.js");
const require_index$4 = require("./components/DeleteProfileModal/index.js");
const require_hooks = require("./hooks.js");
const require_locales = require("./locales.js");
const require_index$5 = require("./components/ProfileSetting/index.js");
let dayjs = require("dayjs");
dayjs = require_runtime.__toESM(dayjs);
let react = require("react");
react = require_runtime.__toESM(react);
let _pisell_utils = require("@pisell/utils");
let _pisell_materials = require("@pisell/materials");
let classnames = require("classnames");
classnames = require_runtime.__toESM(classnames);
let ahooks = require("ahooks");
let _ant_design_icons = require("@ant-design/icons");
require("./index.less");
//#region src/plus/saasDevice/deviceProfile/index.tsx
/** 设备分类顺序（label 改为运行时国际化） */
const KIND_ORDER = [
	"smart",
	"dumb",
	"integrated"
];
const DEFAULT_PAGE_SIZE = 10;
const SaasDeviceProfile = ({ className, style, scene = "profile", showBackButton = false }) => {
	var _context$appHelper, _profileRequest$data2, _context$appHelper3;
	const context = require_useEngineContext.default();
	const locale = require_useLocale.default();
	_pisell_utils.locales.init(require_locales.default, locale || "en");
	const getText = _pisell_utils.locales.getText;
	const translation = require_hooks.useTranslation();
	const utils = (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.utils) || {};
	if (utils === null || utils === void 0 ? void 0 : utils.request) require_index.request.setRequest(utils.request);
	const [siderSearch, setSiderSearch] = (0, react.useState)("");
	const [selectedCode, setSelectedCode] = (0, react.useState)("");
	const [page, setPage] = (0, react.useState)(1);
	const [pageSize, setPageSize] = (0, react.useState)(DEFAULT_PAGE_SIZE);
	const [filters, setFilters] = (0, react.useState)({});
	const [createOpen, setCreateOpen] = (0, react.useState)(false);
	const [duplicateSource, setDuplicateSource] = (0, react.useState)(void 0);
	const [deleteOpen, setDeleteOpen] = (0, react.useState)(false);
	const [deleteRecord, setDeleteRecord] = (0, react.useState)(void 0);
	const [linkedDevices, setLinkedDevices] = (0, react.useState)([]);
	const [modalOpen, setModalOpen] = (0, react.useState)(false);
	const [modalState, setModalState] = (0, react.useState)(null);
	const tableRef = (0, react.useRef)(null);
	const skipNextFetchRef = (0, react.useRef)(false);
	const detailRequest = (0, ahooks.useRequest)(require_serve.getDeviceTypes, { manual: true });
	const profileRequest = (0, ahooks.useRequest)(require_serve.getDeviceProfiles, { manual: true });
	const checkLinkedRequest = (0, ahooks.useRequest)(require_serve.getProfileLinkedDevices, { manual: true });
	const deleteRequest = (0, ahooks.useRequest)(require_serve.deleteDeviceProfile, { manual: true });
	const handleSelectType = (0, react.useCallback)((code) => {
		var _tableRef$current;
		if (!code || code === selectedCode) return;
		skipNextFetchRef.current = true;
		setSelectedCode(code);
		setFilters({});
		setPage(1);
		(_tableRef$current = tableRef.current) === null || _tableRef$current === void 0 || (_tableRef$current = _tableRef$current.formInstance) === null || _tableRef$current === void 0 || _tableRef$current.resetFields([
			["filters", "search"],
			["filters", "model"],
			["filters", "status"]
		]);
		detailRequest.run({
			code,
			with: ["activeModels", "activeModels.activeProfileTemplates"]
		});
		profileRequest.run({
			page: 1,
			size: pageSize,
			type_code: code
		});
	}, [
		selectedCode,
		pageSize,
		detailRequest,
		profileRequest
	]);
	const listRequest = (0, ahooks.useRequest)(() => require_serve.getDeviceTypes(), { onSuccess: (list) => {
		if (!selectedCode && list.length) handleSelectType((list.find((it) => it.status === "active") || list[0]).code);
	} });
	const selectedDetail = (0, react.useMemo)(() => {
		const data = detailRequest.data || [];
		return data.find((it) => it.code === selectedCode) || data[0];
	}, [detailRequest.data, selectedCode]);
	(0, react.useEffect)(() => {
		if (skipNextFetchRef.current) {
			skipNextFetchRef.current = false;
			return;
		}
		if (!selectedCode) return;
		profileRequest.run({
			page,
			size: pageSize,
			type_code: selectedCode,
			model_code: filters.model || void 0,
			status: filters.status || void 0,
			search: filters.search || void 0
		});
	}, [
		selectedCode,
		page,
		pageSize,
		filters
	]);
	const menuItems = (0, react.useMemo)(() => {
		const all = listRequest.data || [];
		const keyword = siderSearch.trim().toLowerCase();
		return KIND_ORDER.map((kind) => {
			const children = all.filter((it) => it.kind === kind).sort((a, b) => a.sort - b.sort).map((it) => ({
				item: it,
				text: translation(it.name)
			})).filter(({ text }) => keyword ? String(text).toLowerCase().includes(keyword) : true).map(({ item, text }) => ({
				key: item.code,
				label: text,
				icon: item.icon ? /* @__PURE__ */ react.default.createElement(_pisell_materials.Icon, { type: item.icon }) : null
			}));
			return {
				key: `group-${kind}`,
				type: "group",
				label: getText(`pisell2.saas.device-profile.kind.${kind}`),
				children
			};
		});
	}, [
		listRequest.data,
		siderSearch,
		translation,
		getText
	]);
	const modelOptions = (0, react.useMemo)(() => ((selectedDetail === null || selectedDetail === void 0 ? void 0 : selectedDetail.active_models) || []).map((m) => ({
		label: translation(m.name),
		value: m.code
	})), [selectedDetail, translation]);
	const modelNameMap = (0, react.useMemo)(() => {
		const map = {};
		((selectedDetail === null || selectedDetail === void 0 ? void 0 : selectedDetail.active_models) || []).forEach((m) => {
			map[m.code] = translation(m.name);
		});
		return map;
	}, [selectedDetail, translation]);
	const tableData = (0, react.useMemo)(() => {
		var _profileRequest$data;
		return (((_profileRequest$data = profileRequest.data) === null || _profileRequest$data === void 0 ? void 0 : _profileRequest$data.list) || []).map((it) => {
			var _selectedDetail$activ;
			return {
				id: it.id,
				name: translation(it.name),
				modelCode: it.model_code,
				modelName: modelNameMap[it.model_code] || it.model_code,
				status: it.status,
				updated_at: it.updated_at,
				_deviceType: selectedDetail,
				_deviceModel: selectedDetail === null || selectedDetail === void 0 || (_selectedDetail$activ = selectedDetail.active_models) === null || _selectedDetail$activ === void 0 ? void 0 : _selectedDetail$activ.find((m) => m.code === (it === null || it === void 0 ? void 0 : it.model_code)),
				_raw: it
			};
		});
	}, [
		profileRequest.data,
		modelNameMap,
		translation
	]);
	const total = ((_profileRequest$data2 = profileRequest.data) === null || _profileRequest$data2 === void 0 ? void 0 : _profileRequest$data2.count) || 0;
	const noop = (0, react.useCallback)((action, record) => {
		console.log("action =>>>>", action, record);
		switch (action) {
			case "edit":
				setModalOpen(true);
				setModalState({
					record,
					deviceModel: record === null || record === void 0 ? void 0 : record._deviceModel,
					deviceType: record === null || record === void 0 ? void 0 : record._deviceType
				});
				break;
			case "copy":
				if (record === null || record === void 0 ? void 0 : record._raw) {
					setDuplicateSource(record._raw);
					setCreateOpen(true);
				}
				break;
			case "delete": {
				var _record$_deviceType;
				const typeKind = (_record$_deviceType = record._deviceType) === null || _record$_deviceType === void 0 ? void 0 : _record$_deviceType.kind;
				if (!record.id || !typeKind) return;
				setDeleteRecord(record);
				setLinkedDevices([]);
				setDeleteOpen(true);
				checkLinkedRequest.runAsync({
					profile_id: record.id,
					type_kind: typeKind,
					with: ["workarea"]
				}).then((list) => setLinkedDevices(list || [])).catch(() => setLinkedDevices([]));
				break;
			}
		}
	}, [checkLinkedRequest]);
	const filterConfig = (0, react.useMemo)(() => ({
		show: true,
		quickFilterMaxLength: 3,
		list: [
			{
				key: "search",
				type: "search",
				name: "search",
				isCustom: true,
				columnKey: "",
				localFilter: false,
				other: {
					size: "large",
					allowClear: true,
					trigger: ["onChange", "onPressEnter"],
					placeholder: getText("pisell2.saas.device-profile.search-profiles"),
					style: { width: 280 }
				}
			},
			{
				key: "model",
				type: "single",
				name: "model",
				isCustom: true,
				columnKey: "",
				localFilter: false,
				other: {
					size: "large",
					allowClear: true,
					placeholder: getText("pisell2.saas.device-profile.filter.all-models"),
					options: modelOptions,
					style: { width: 200 }
				}
			},
			{
				key: "status",
				type: "single",
				name: "status",
				isCustom: true,
				columnKey: "",
				localFilter: false,
				other: {
					size: "large",
					allowClear: true,
					placeholder: getText("pisell2.saas.device-profile.filter.all-status"),
					options: [{
						label: getText("pisell2.saas.device-profile.status.active"),
						value: "active"
					}, {
						label: getText("pisell2.saas.device-profile.status.inactive"),
						value: "inactive"
					}],
					style: { width: 160 }
				}
			}
		]
	}), [getText, modelOptions]);
	const handleValuesChange = (0, react.useCallback)((_changed, values) => {
		const f = (values === null || values === void 0 ? void 0 : values.filters) || {};
		setFilters({
			search: f.search,
			model: f.model,
			status: f.status
		});
		if (values === null || values === void 0 ? void 0 : values.pagination) {
			setPage(values.pagination.page || 1);
			setPageSize(values.pagination.size || DEFAULT_PAGE_SIZE);
		}
	}, []);
	const columns = (0, react.useMemo)(() => [
		{
			title: getText("pisell2.saas.device-profile.column.name"),
			dataIndex: "name",
			key: "name"
		},
		{
			title: getText("pisell2.saas.device-profile.column.device-model"),
			dataIndex: "modelName",
			key: "modelName"
		},
		{
			title: getText("pisell2.saas.device-profile.column.status"),
			dataIndex: "status",
			key: "status",
			width: 120,
			render: (status) => /* @__PURE__ */ react.default.createElement(_pisell_materials.Tag, {
				variant: "solid",
				color: status === "active" ? "green" : "default"
			}, getText(`pisell2.saas.device-profile.status.${status}`))
		},
		{
			title: getText("pisell2.saas.device-profile.column.updated"),
			dataIndex: "updated_at",
			key: "updated_at",
			width: 180,
			render: (text) => text ? (0, dayjs.default)(text).format("DD/MM/YYYY HH:mm") : "-"
		},
		{
			title: getText("pisell2.saas.device-profile.column.actions"),
			key: "actions",
			width: 140,
			render: (record) => /* @__PURE__ */ react.default.createElement(_pisell_materials.Space, { size: 4 }, /* @__PURE__ */ react.default.createElement(_pisell_materials.Button, {
				type: "text",
				icon: /* @__PURE__ */ react.default.createElement(_ant_design_icons.EditOutlined, null),
				onClick: () => noop("edit", record)
			}), /* @__PURE__ */ react.default.createElement(_pisell_materials.Button, {
				type: "text",
				icon: /* @__PURE__ */ react.default.createElement(_ant_design_icons.CopyOutlined, null),
				onClick: () => noop("copy", record)
			}), /* @__PURE__ */ react.default.createElement(_pisell_materials.Button, {
				type: "text",
				danger: true,
				icon: /* @__PURE__ */ react.default.createElement(_ant_design_icons.DeleteOutlined, null),
				onClick: () => noop("delete", record)
			}))
		}
	], [getText, noop]);
	const emptyProfilesText = (0, react.useMemo)(() => {
		const dt = selectedDetail ? translation(selectedDetail.name) : "";
		return getText("pisell2.saas.device-profile.empty.profiles").replace("{DeviceType}", dt || "");
	}, [
		getText,
		selectedDetail,
		translation
	]);
	const reload = () => {
		profileRequest.run({
			page,
			size: pageSize,
			type_code: selectedCode,
			model_code: filters.model || void 0,
			status: filters.status || void 0,
			search: filters.search || void 0
		});
	};
	const handleBack = (0, react.useCallback)(() => {
		var _context$appHelper2, _getApp, _history$goBack;
		const getApp = context === null || context === void 0 || (_context$appHelper2 = context.appHelper) === null || _context$appHelper2 === void 0 || (_context$appHelper2 = _context$appHelper2.utils) === null || _context$appHelper2 === void 0 ? void 0 : _context$appHelper2.getApp;
		const history = getApp === null || getApp === void 0 || (_getApp = getApp()) === null || _getApp === void 0 || (_getApp = _getApp.history) === null || _getApp === void 0 ? void 0 : _getApp.instance;
		history === null || history === void 0 || (_history$goBack = history.goBack) === null || _history$goBack === void 0 || _history$goBack.call(history);
	}, [context === null || context === void 0 || (_context$appHelper3 = context.appHelper) === null || _context$appHelper3 === void 0 ? void 0 : _context$appHelper3.utils]);
	const pageSubTitle = getText("pisell2.saas.device-profile.subtitle");
	const pageTitle = (0, react.useMemo)(() => {
		const title = getText("pisell2.saas.device-profile.title");
		if (!showBackButton) return title;
		return /* @__PURE__ */ react.default.createElement("div", { className: "saas-device-profile__page-heading" }, /* @__PURE__ */ react.default.createElement(_pisell_materials.Button, {
			type: "text",
			icon: /* @__PURE__ */ react.default.createElement(_ant_design_icons.ArrowLeftOutlined, null),
			className: "saas-device-profile__back-button",
			onClick: handleBack,
			size: "large"
		}), /* @__PURE__ */ react.default.createElement("div", { className: "saas-device-profile__page-title" }, /* @__PURE__ */ react.default.createElement("span", null, title), /* @__PURE__ */ react.default.createElement("span", { className: "saas-device-profile__page-subtitle" }, pageSubTitle)));
	}, [
		getText,
		handleBack,
		pageSubTitle,
		showBackButton
	]);
	return /* @__PURE__ */ react.default.createElement("div", {
		className: (0, classnames.default)("saas-device-profile", className),
		style
	}, /* @__PURE__ */ react.default.createElement(require_index$1.default, {
		title: pageTitle,
		subTitle: showBackButton ? void 0 : pageSubTitle,
		sider: /* @__PURE__ */ react.default.createElement(require_index$2.default, {
			title: getText("pisell2.saas.device-profile.device-type"),
			searchable: true,
			searchPlaceholder: getText("pisell2.saas.device-profile.search"),
			onSearch: setSiderSearch,
			items: menuItems,
			selectedKey: selectedCode,
			onSelect: handleSelectType,
			emptyText: getText("pisell2.saas.device-profile.empty.device-types")
		})
	}, /* @__PURE__ */ react.default.createElement(_pisell_materials.Table, {
		ref: tableRef,
		rowKey: "id",
		dataSource: tableData,
		columns,
		loading: detailRequest.loading || profileRequest.loading,
		filter: filterConfig,
		onValuesChange: handleValuesChange,
		scroll: {
			autoCalc: true,
			scrollToFirstRowOnChange: true
		},
		pagination: {
			localPagination: false,
			current: page,
			pageSize,
			total,
			showSizeChanger: true,
			onChange: (p) => {
				setPage(p.page);
				setPageSize(p.size);
			}
		},
		showTitle: false,
		showSubTitle: false,
		actionButtons: [{
			type: "primary",
			icon: /* @__PURE__ */ react.default.createElement(_ant_design_icons.PlusOutlined, null),
			title: getText("pisell2.saas.device-profile.create"),
			onClick: () => setCreateOpen(true),
			disabled: !selectedDetail
		}],
		locale: { emptyText: emptyProfilesText },
		bordered: true
	})), createOpen && /* @__PURE__ */ react.default.createElement(require_index$3.default, {
		open: createOpen,
		mode: duplicateSource ? "duplicate" : "create",
		sourceProfile: duplicateSource,
		deviceType: selectedDetail,
		getText,
		translation,
		onClose: () => {
			setCreateOpen(false);
			setDuplicateSource(void 0);
		},
		onSuccess: () => {
			setCreateOpen(false);
			setDuplicateSource(void 0);
			if (page !== 1) setPage(1);
			else profileRequest.run({
				page: 1,
				size: pageSize,
				type_code: selectedCode,
				model_code: filters.model || void 0,
				status: filters.status || void 0,
				search: filters.search || void 0
			});
		}
	}), deleteOpen && /* @__PURE__ */ react.default.createElement(require_index$4.default, {
		open: deleteOpen,
		loading: checkLinkedRequest.loading,
		submitting: deleteRequest.loading,
		profileName: deleteRecord ? deleteRecord.name : "",
		linkedDevices,
		translation,
		getText,
		onClose: () => {
			setDeleteOpen(false);
			setDeleteRecord(void 0);
			setLinkedDevices([]);
		},
		onConfirm: require_asyncToGenerator._asyncToGenerator(function* () {
			console.log("deleteRecord =>>>>", deleteRecord);
			if (!deleteRecord) return;
			try {
				yield deleteRequest.runAsync(deleteRecord.id);
				(0, _pisell_materials.PisellToast)({
					content: getText("pisell2.saas.device-profile.message.delete-success"),
					duration: 2
				});
				setDeleteOpen(false);
				setDeleteRecord(void 0);
				setLinkedDevices([]);
				reload();
			} catch (e) {}
		})
	}), modalOpen && /* @__PURE__ */ react.default.createElement("div", { className: "saas-device-profile-template-modal" }, /* @__PURE__ */ react.default.createElement(require_index$5.default, {
		record: modalState === null || modalState === void 0 ? void 0 : modalState.record,
		deviceModel: modalState === null || modalState === void 0 ? void 0 : modalState.deviceModel,
		deviceType: modalState === null || modalState === void 0 ? void 0 : modalState.deviceType,
		scene,
		onBack: () => {
			reload();
			setModalOpen(false);
			setModalState(null);
		}
	})));
};
//#endregion
exports.default = SaasDeviceProfile;
