function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
var _excluded = ["members"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : String(i); }
function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }
function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
function _iterableToArrayLimit(r, l) { var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (null != t) { var e, n, i, u, a = [], f = !0, o = !1; try { if (i = (t = t.call(r)).next, 0 === l) { if (Object(t) !== t) return; f = !1; } else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0); } catch (r) { o = !0, n = r; } finally { try { if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return; } finally { if (o) throw n; } } return a; } }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import React, { createContext, forwardRef, useCallback, useEffect, useMemo, useImperativeHandle, useRef, useState } from 'react';
import classNames from 'classnames';
import { Form, Tabs, Spin } from 'antd';
import { Icon } from '@pisell/materials';
import { locales } from '@pisell/utils';
import { useRequest } from 'ahooks';
import useEngineContext from "../../../hooks/useEngineContext";
import { request } from "../../../utils";
import localeTexts from "../locales";
import BasicInfoTab from "./BasicInfoTab";
import ShiftScheduleTab from "./ShiftScheduleTab";
import ClockInMethodTab from "./ClockInMethodTab";
import CorrectionPolicyTab from "./CorrectionPolicyTab";
import { getAllMembers } from "./serve";
import "./index.less";
// Tab 配置
var 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'
}];

// 生成简单的唯一 ID
var generateSimpleUUID = function generateSimpleUUID() {
  return Math.random().toString(36).substring(2) + Date.now().toString(36);
};
export var settingsContext = /*#__PURE__*/createContext({
  members: []
});
var Settings = /*#__PURE__*/forwardRef(function (props, ref) {
  var _context$engine, _context$appHelper;
  var value = props.value,
    customScrollParent = props.customScrollParent;
  var context = useEngineContext();
  locales.init(localeTexts, (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 && _context$appHelper.request) {
    request.setRequest(context.appHelper.utils.request);
  }
  var _Form$useForm = Form.useForm(),
    _Form$useForm2 = _slicedToArray(_Form$useForm, 1),
    form = _Form$useForm2[0];
  var _useState = useState('basic'),
    _useState2 = _slicedToArray(_useState, 2),
    activeKey = _useState2[0],
    setActiveKey = _useState2[1];
  var uniqueIdRef = useRef(generateSimpleUUID().substring(0, 8));
  var _uniqueId = uniqueIdRef.current;

  // 手动切换索引时，不触发滚动监听回调
  var isManualChangeRef = useRef(false);
  useEffect(function () {
    document.body.id = 'body';
  }, []);
  var _useRequest = useRequest(getAllMembers, {
      defaultParams: [{
        page: 1,
        size: 499,
        with: ['account']
      }]
    }),
    membersResp = _useRequest.data;

  // 同步外部 value 到 form
  useEffect(function () {
    if (!value) return;
    var valueAny = value;
    var rawMembers = valueAny === null || valueAny === void 0 ? void 0 : valueAny.members;
    var memberIdsFromMembers = Array.isArray(rawMembers) ? Array.from(new Set(rawMembers.map(function (item) {
      return item === null || item === void 0 ? void 0 : item.tenant_account_id;
    }).filter(function (id) {
      return typeof id === 'number' && !Number.isNaN(id);
    }))) : [];
    var existingMemberIds = Array.isArray(valueAny === null || valueAny === void 0 ? void 0 : valueAny.member_ids) ? valueAny.member_ids : [];
    var resolvedMemberIds = existingMemberIds.length > 0 ? existingMemberIds : memberIdsFromMembers;
    var members = valueAny.members,
      rest = _objectWithoutProperties(valueAny, _excluded);
    form.setFieldsValue(_objectSpread(_objectSpread({}, rest), {}, {
      member_ids: resolvedMemberIds
    }));
  }, [value, form]);

  // 防抖指示器
  var debounceIndicator = useCallback(function (delay) {
    isManualChangeRef.current = true;
    var timeoutId = setTimeout(function () {
      isManualChangeRef.current = false;
    }, delay);
    return function () {
      return clearTimeout(timeoutId);
    };
  }, []);
  useImperativeHandle(ref, function () {
    return _objectSpread({}, form);
  });

  // 切换 tab 并滚动到对应区域
  var switchTab = useCallback(function (key) {
    setActiveKey(key);
    debounceIndicator(300);

    // 获取可滚动祖先元素
    var scrollParent = null;
    var formContainer = document.getElementById("saas-attendance-group-settings-".concat(_uniqueId));
    if (typeof customScrollParent === 'string') {
      scrollParent = document.querySelector(customScrollParent);
    } else {
      scrollParent = customScrollParent || formContainer;
    }
    if (!scrollParent || !formContainer) return;
    var target = document.getElementById("saas-attendance-settings-section-".concat(_uniqueId, "-").concat(key));
    if (!target) return;

    // 使用 getBoundingClientRect 计算更准确的滚动位置
    var scrollParentRect = scrollParent.getBoundingClientRect();
    var tabIndex = TAB_CONFIGS.findIndex(function (item) {
      return item.key === key;
    });
    if (tabIndex === 0) {
      // 如果是第一个 tab，滚动到容器顶部
      scrollParent.scrollTop = 0;
    } else {
      // 其他 tab，滚动到对应区域，需要减去标签页高度
      var targetRect = target.getBoundingClientRect();
      var scrollOffset = targetRect.top - scrollParentRect.top + scrollParent.scrollTop;
      scrollParent.scrollTop = scrollOffset - 16;
    }
  }, [customScrollParent, debounceIndicator, _uniqueId]);

  // 滚动监听 - 更新当前激活的 tab
  useEffect(function () {
    var scrollParent = null;
    var formContainer = document.getElementById("saas-attendance-group-settings-".concat(_uniqueId));
    if (typeof customScrollParent === 'string') {
      scrollParent = document.querySelector(customScrollParent);
    } else {
      scrollParent = customScrollParent || formContainer;
    }
    if (!scrollParent || !formContainer) return;
    var handleScroll = function handleScroll() {
      if (isManualChangeRef.current) return;
      var tabsWrapper = document.getElementById("saas-attendance-settings-".concat(_uniqueId, "_tabs"));
      var tabsHeight = (tabsWrapper === null || tabsWrapper === void 0 ? void 0 : tabsWrapper.offsetHeight) || 0;

      // 使用 getBoundingClientRect 计算当前可见的 section
      var scrollParentRect = scrollParent.getBoundingClientRect();
      // 检测点位于 tabs 下方一点的位置
      var checkPoint = scrollParentRect.top + tabsHeight + 20;

      // 找到当前可见的 section
      var currentKey = 'basic';
      for (var _i = 0, _TAB_CONFIGS = TAB_CONFIGS; _i < _TAB_CONFIGS.length; _i++) {
        var config = _TAB_CONFIGS[_i];
        var section = document.getElementById("saas-attendance-settings-section-".concat(_uniqueId, "-").concat(config.key));
        if (section) {
          var sectionRect = section.getBoundingClientRect();
          // 如果 section 的顶部在检测点之上，说明这个 section 已经滚动到可见区域
          if (sectionRect.top <= checkPoint) {
            currentKey = config.key;
          }
        }
      }
      if (currentKey !== activeKey) {
        setActiveKey(currentKey);
      }
    };
    scrollParent.addEventListener('scroll', handleScroll);
    return function () {
      var _scrollParent;
      (_scrollParent = scrollParent) === null || _scrollParent === void 0 || _scrollParent.removeEventListener('scroll', handleScroll);
    };
  }, [customScrollParent, _uniqueId, activeKey]);

  // Tab items - 仅用于渲染 tab 头部
  var tabItems = useMemo(function () {
    return TAB_CONFIGS.map(function (config) {
      return {
        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 // 不在 tab content 中渲染内容
      };
    });
  }, []);
  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-".concat(_uniqueId, "_tabs")
  }, /*#__PURE__*/React.createElement(Tabs, {
    activeKey: activeKey,
    items: tabItems,
    onChange: switchTab,
    renderTabBar: function renderTabBar(tabBarProps, DefaultTabBar) {
      return /*#__PURE__*/React.createElement(DefaultTabBar, tabBarProps);
    }
  })), /*#__PURE__*/React.createElement(Form, {
    id: "saas-attendance-group-settings-".concat(_uniqueId),
    className: "saas-attendance-group-settings__form",
    form: form,
    layout: "vertical",
    size: "large",
    onValuesChange: props.onValuesChange,
    onFinish: props.onFinish,
    scrollToFirstError: true
  }, /*#__PURE__*/React.createElement(BasicInfoTab, {
    id: "saas-attendance-settings-section-".concat(_uniqueId, "-basic")
  }), /*#__PURE__*/React.createElement(ShiftScheduleTab, {
    id: "saas-attendance-settings-section-".concat(_uniqueId, "-shift")
  }), /*#__PURE__*/React.createElement(ClockInMethodTab, {
    form: form,
    id: "saas-attendance-settings-section-".concat(_uniqueId, "-clock")
  }), /*#__PURE__*/React.createElement(CorrectionPolicyTab, {
    form: form,
    id: "saas-attendance-settings-section-".concat(_uniqueId, "-correction")
  }))));
});
export default Settings;