import { _objectSpread2 } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _objectWithoutProperties } from "../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import useEngineContext from "../../../hooks/useEngineContext.js";
import { request } from "../../../utils/index.js";
import locales_default from "../locales.js";
import { getAllMembers } from "./serve.js";
import BasicInfoTab from "./BasicInfoTab.js";
import PermissonTab from "./PermissonTab.js";
import ShiftScheduleTab from "./ShiftScheduleTab.js";
import ClockInMethodTab from "./ClockInMethodTab.js";
import CorrectionPolicyTab from "./CorrectionPolicyTab.js";
import React, { createContext, forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { Form, Spin, Tabs } from "antd";
import { locales } from "@pisell/utils";
import { Icon } from "@pisell/materials";
import classNames from "classnames";
import { useRequest } from "ahooks";
import "./index.less";
//#region src/plus/saasAttendance/settings/index.tsx
const _excluded = ["members"];
const TAB_CONFIGS = [
	{
		key: "basic",
		icon: "pisell2-settings-02",
		labelKey: "pisell2.attendance.group-settings.basic-info"
	},
	{
		key: "shift",
		icon: "pisell2-calendar",
		labelKey: "pisell2.attendance.group-settings.shift-schedule"
	},
	{
		key: "clock",
		icon: "pisell2-marker-pin-01",
		labelKey: "pisell2.attendance.group-settings.clock-in-method"
	},
	{
		key: "correction",
		icon: "pisell2-clock",
		labelKey: "pisell2.attendance.group-settings.correction-policy"
	},
	{
		key: "permission",
		icon: "pisell2-user-01",
		labelKey: "pisell2.attendance.group-settings.data-permission"
	}
];
const generateSimpleUUID = () => {
	return Math.random().toString(36).substring(2) + Date.now().toString(36);
};
const settingsContext = createContext({ members: [] });
const Settings = forwardRef((props, ref) => {
	var _context$engine, _context$appHelper;
	const { value, customScrollParent } = props;
	const context = useEngineContext();
	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");
	if (context === null || context === void 0 || (_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.utils) === null || _context$appHelper === void 0 ? void 0 : _context$appHelper.request) request.setRequest(context.appHelper.utils.request);
	const [form] = Form.useForm();
	const [activeKey, setActiveKey] = useState("basic");
	const _uniqueId = useRef(generateSimpleUUID().substring(0, 8)).current;
	const isManualChangeRef = useRef(false);
	useEffect(() => {
		document.body.id = "body";
	}, []);
	const { data: membersResp } = useRequest(getAllMembers, { defaultParams: [{
		page: 1,
		size: 499,
		with: ["account"]
	}] });
	useEffect(() => {
		if (!value) return;
		const valueAny = value;
		const rawMembers = valueAny === null || valueAny === void 0 ? void 0 : valueAny.members;
		const memberIdsFromMembers = Array.isArray(rawMembers) ? Array.from(new Set(rawMembers.map((item) => item === null || item === void 0 ? void 0 : item.tenant_account_id).filter((id) => typeof id === "number" && !Number.isNaN(id)))) : [];
		const existingMemberIds = Array.isArray(valueAny === null || valueAny === void 0 ? void 0 : valueAny.member_ids) ? valueAny.member_ids : [];
		const resolvedMemberIds = existingMemberIds.length > 0 ? existingMemberIds : memberIdsFromMembers;
		const { members } = valueAny, rest = _objectWithoutProperties(valueAny, _excluded);
		form.setFieldsValue(_objectSpread2(_objectSpread2({}, rest), {}, { member_ids: resolvedMemberIds }));
	}, [value, form]);
	const debounceIndicator = useCallback((delay) => {
		isManualChangeRef.current = true;
		const timeoutId = setTimeout(() => {
			isManualChangeRef.current = false;
		}, delay);
		return () => clearTimeout(timeoutId);
	}, []);
	useImperativeHandle(ref, () => _objectSpread2({}, form));
	const switchTab = useCallback((key) => {
		setActiveKey(key);
		debounceIndicator(300);
		let scrollParent = null;
		const formContainer = document.getElementById(`saas-attendance-group-settings-${_uniqueId}`);
		if (typeof customScrollParent === "string") scrollParent = document.querySelector(customScrollParent);
		else scrollParent = customScrollParent || formContainer;
		if (!scrollParent || !formContainer) return;
		const target = document.getElementById(`saas-attendance-settings-section-${_uniqueId}-${key}`);
		if (!target) return;
		const scrollParentRect = scrollParent.getBoundingClientRect();
		if (TAB_CONFIGS.findIndex((item) => item.key === key) === 0) scrollParent.scrollTop = 0;
		else {
			const scrollOffset = target.getBoundingClientRect().top - scrollParentRect.top + scrollParent.scrollTop;
			scrollParent.scrollTop = scrollOffset - 16;
		}
	}, [
		customScrollParent,
		debounceIndicator,
		_uniqueId
	]);
	useEffect(() => {
		let scrollParent = null;
		const formContainer = document.getElementById(`saas-attendance-group-settings-${_uniqueId}`);
		if (typeof customScrollParent === "string") scrollParent = document.querySelector(customScrollParent);
		else scrollParent = customScrollParent || formContainer;
		if (!scrollParent || !formContainer) return;
		const handleScroll = () => {
			if (isManualChangeRef.current) return;
			const tabsWrapper = document.getElementById(`saas-attendance-settings-${_uniqueId}_tabs`);
			const tabsHeight = (tabsWrapper === null || tabsWrapper === void 0 ? void 0 : tabsWrapper.offsetHeight) || 0;
			const checkPoint = scrollParent.getBoundingClientRect().top + tabsHeight + 20;
			let currentKey = "basic";
			for (const config of TAB_CONFIGS) {
				const section = document.getElementById(`saas-attendance-settings-section-${_uniqueId}-${config.key}`);
				if (section) {
					if (section.getBoundingClientRect().top <= checkPoint) currentKey = config.key;
				}
			}
			if (currentKey !== activeKey) setActiveKey(currentKey);
		};
		scrollParent.addEventListener("scroll", handleScroll);
		return () => {
			scrollParent === null || scrollParent === void 0 || scrollParent.removeEventListener("scroll", handleScroll);
		};
	}, [
		customScrollParent,
		_uniqueId,
		activeKey
	]);
	const tabItems = useMemo(() => TAB_CONFIGS.map((config) => ({
		key: config.key,
		label: /* @__PURE__ */ React.createElement("span", { className: "saas-attendance-group-settings__tab-label" }, /* @__PURE__ */ React.createElement(Icon, {
			type: config.icon,
			size: 20
		}), locales.getText(config.labelKey)),
		children: null
	})), []);
	return /* @__PURE__ */ React.createElement(settingsContext.Provider, { value: { members: (membersResp === null || membersResp === void 0 ? void 0 : membersResp.list) || [] } }, /* @__PURE__ */ React.createElement("div", {
		className: classNames("saas-attendance-group-settings", props.className),
		style: props.style
	}, props.loading ? /* @__PURE__ */ React.createElement("div", { className: "saas-attendance-group-settings__loading" }, /* @__PURE__ */ React.createElement(Spin, null)) : null, /* @__PURE__ */ React.createElement("div", {
		className: "saas-attendance-group-settings__tabs-wrapper",
		id: `saas-attendance-settings-${_uniqueId}_tabs`
	}, /* @__PURE__ */ React.createElement(Tabs, {
		activeKey,
		items: tabItems,
		onChange: switchTab,
		renderTabBar: (tabBarProps, DefaultTabBar) => /* @__PURE__ */ React.createElement(DefaultTabBar, tabBarProps)
	})), /* @__PURE__ */ React.createElement(Form, {
		id: `saas-attendance-group-settings-${_uniqueId}`,
		className: "saas-attendance-group-settings__form",
		form,
		layout: "vertical",
		size: "large",
		onValuesChange: props.onValuesChange,
		onFinish: props.onFinish,
		scrollToFirstError: true
	}, /* @__PURE__ */ React.createElement(BasicInfoTab, { id: `saas-attendance-settings-section-${_uniqueId}-basic` }), /* @__PURE__ */ React.createElement(ShiftScheduleTab, { id: `saas-attendance-settings-section-${_uniqueId}-shift` }), /* @__PURE__ */ React.createElement(ClockInMethodTab, {
		form,
		id: `saas-attendance-settings-section-${_uniqueId}-clock`
	}), /* @__PURE__ */ React.createElement(CorrectionPolicyTab, {
		form,
		id: `saas-attendance-settings-section-${_uniqueId}-correction`
	}), /* @__PURE__ */ React.createElement(PermissonTab, { id: `saas-attendance-settings-section-${_uniqueId}-permission` }))));
});
//#endregion
export { Settings as default, settingsContext };
