import { bk as generateUtilityClass, bl as generateUtilityClasses, r as reactExports, bm as useDefaultProps, bn as _objectWithoutPropertiesLoose, bo as _extends, j as jsxRuntimeExports, y as styled, bb as clsx, bp as capitalize, bq as composeClasses, aj as requireInteropRequireDefault, ak as requireCreateSvgIcon, al as requireJsxRuntime, am as getDefaultExportFromCjs, E as useAtom, br as renderingIdAtom, u as useAtomValue, b7 as selectedSectionAtom, bs as sectionPersonsData, a6 as GridLoader, ag as handleTable, a0 as smetaStore, bt as animationsAtom, b4 as updateGridData, bf as Prefixes, ax as SplitterLocal, a3 as Tree, aU as ContextMenu, aV as getDefaultMenu, bu as getStaffSettings, ah as AxiosRequest, aa as getBookContextMenu, ad as PostHandleTable, ae as getRightsData, af as parseColumns, t as React, aI as Tabs, aw as Params, b9 as SectionDocuments, bv as EditStyle, b2 as defaultFieldInfo, bg as smetaAxios, bw as PostAddIcon, bx as DeleteIcon, b3 as getDateOfInt, by as Param, bz as setParamObjectText, az as GetAddressUseKladr, aB as getParamsObject, ai as Editor, bd as CheckBoxMultiCheck, aC as AddressParams, bA as handleCadresRequest, a7 as TabItem, aK as LoadingMask, bB as getBase64ByFileReader, bC as ButtonsForGridComponent, I as IconButton, bD as ClearOutlinedIcon, an as CheckOutlinedIcon, F as FormControl, aQ as FormLabel, bE as RadioGroup, i as FormControlLabel, bF as Radio, ac as tokenProcessingTest, bG as SmetaTabs, bH as SmetaTabItem, bI as SpaceDashboardOutlinedIcon, bJ as SearchIcon, bK as AccountBoxOutlinedIcon, bL as CheckBoxIcon, bM as SectionToolsJS } from "./index-D15x63tD.js";
import { S as SearchPersons } from "./SearchPersons-C1hfxGSb.js";
import SectionReports from "./SectionReports-CR4VT6wR.js";
import SectionDocumentsChose from "./SectionDocumentsChose-CWNMUy0u.js";
function getIconUtilityClass(slot) {
  return generateUtilityClass("MuiIcon", slot);
}
generateUtilityClasses("MuiIcon", ["root", "colorPrimary", "colorSecondary", "colorAction", "colorError", "colorDisabled", "fontSizeInherit", "fontSizeSmall", "fontSizeMedium", "fontSizeLarge"]);
const _excluded = ["baseClassName", "className", "color", "component", "fontSize"];
const useUtilityClasses = (ownerState) => {
  const {
    color,
    fontSize,
    classes
  } = ownerState;
  const slots = {
    root: ["root", color !== "inherit" && `color${capitalize(color)}`, `fontSize${capitalize(fontSize)}`]
  };
  return composeClasses(slots, getIconUtilityClass, classes);
};
const IconRoot = styled("span", {
  name: "MuiIcon",
  slot: "Root",
  overridesResolver: (props, styles) => {
    const {
      ownerState
    } = props;
    return [styles.root, ownerState.color !== "inherit" && styles[`color${capitalize(ownerState.color)}`], styles[`fontSize${capitalize(ownerState.fontSize)}`]];
  }
})(({
  theme,
  ownerState
}) => ({
  userSelect: "none",
  width: "1em",
  height: "1em",
  // Chrome fix for https://bugs.chromium.org/p/chromium/issues/detail?id=820541
  // To remove at some point.
  overflow: "hidden",
  display: "inline-block",
  // allow overflow hidden to take action
  textAlign: "center",
  // support non-square icon
  flexShrink: 0,
  fontSize: {
    inherit: "inherit",
    small: theme.typography.pxToRem(20),
    medium: theme.typography.pxToRem(24),
    large: theme.typography.pxToRem(36)
  }[ownerState.fontSize],
  // TODO v5 deprecate, v6 remove for sx
  color: {
    primary: (theme.vars || theme).palette.primary.main,
    secondary: (theme.vars || theme).palette.secondary.main,
    info: (theme.vars || theme).palette.info.main,
    success: (theme.vars || theme).palette.success.main,
    warning: (theme.vars || theme).palette.warning.main,
    action: (theme.vars || theme).palette.action.active,
    error: (theme.vars || theme).palette.error.main,
    disabled: (theme.vars || theme).palette.action.disabled,
    inherit: void 0
  }[ownerState.color]
}));
const Icon = /* @__PURE__ */ reactExports.forwardRef(function Icon2(inProps, ref) {
  const props = useDefaultProps({
    props: inProps,
    name: "MuiIcon"
  });
  const {
    baseClassName = "material-icons",
    className,
    color = "inherit",
    component: Component = "span",
    fontSize = "medium"
  } = props, other = _objectWithoutPropertiesLoose(props, _excluded);
  const ownerState = _extends({}, props, {
    baseClassName,
    color,
    component: Component,
    fontSize
  });
  const classes = useUtilityClasses(ownerState);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(IconRoot, _extends({
    as: Component,
    className: clsx(
      baseClassName,
      // Prevent the translation of the text content.
      // The font relies on the exact text content to render the icon.
      "notranslate",
      classes.root,
      className
    ),
    ownerState,
    "aria-hidden": true,
    ref
  }, other));
});
Icon.muiName = "Icon";
var LockOutlined = {};
var hasRequiredLockOutlined;
function requireLockOutlined() {
  if (hasRequiredLockOutlined) return LockOutlined;
  hasRequiredLockOutlined = 1;
  var _interopRequireDefault = requireInteropRequireDefault();
  Object.defineProperty(LockOutlined, "__esModule", {
    value: true
  });
  LockOutlined.default = void 0;
  var _createSvgIcon = _interopRequireDefault(/* @__PURE__ */ requireCreateSvgIcon());
  var _jsxRuntime = requireJsxRuntime();
  LockOutlined.default = (0, _createSvgIcon.default)(/* @__PURE__ */ (0, _jsxRuntime.jsx)("path", {
    d: "M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2M9 6c0-1.66 1.34-3 3-3s3 1.34 3 3v2H9zm9 14H6V10h12zm-6-3c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2"
  }), "LockOutlined");
  return LockOutlined;
}
var LockOutlinedExports = /* @__PURE__ */ requireLockOutlined();
const LockOutlinedIcon = /* @__PURE__ */ getDefaultExportFromCjs(LockOutlinedExports);
var LockOpenOutlined = {};
var hasRequiredLockOpenOutlined;
function requireLockOpenOutlined() {
  if (hasRequiredLockOpenOutlined) return LockOpenOutlined;
  hasRequiredLockOpenOutlined = 1;
  var _interopRequireDefault = requireInteropRequireDefault();
  Object.defineProperty(LockOpenOutlined, "__esModule", {
    value: true
  });
  LockOpenOutlined.default = void 0;
  var _createSvgIcon = _interopRequireDefault(/* @__PURE__ */ requireCreateSvgIcon());
  var _jsxRuntime = requireJsxRuntime();
  LockOpenOutlined.default = (0, _createSvgIcon.default)(/* @__PURE__ */ (0, _jsxRuntime.jsx)("path", {
    d: "M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6h2c0-1.66 1.34-3 3-3s3 1.34 3 3v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2m0 12H6V10h12zm-6-3c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2"
  }), "LockOpenOutlined");
  return LockOpenOutlined;
}
var LockOpenOutlinedExports = /* @__PURE__ */ requireLockOpenOutlined();
const LockOpenOutlinedIcon = /* @__PURE__ */ getDefaultExportFromCjs(LockOpenOutlinedExports);
const MoveObjects = async (id, groupID) => {
  const params = /* @__PURE__ */ new Map();
  params.set("prefix", "persons").set("comand", "MoveObjects").set("ID", id).set("GroupID", groupID);
  AxiosRequest(true, params);
};
const setOptionsRecord = async (id, value) => {
  const params = /* @__PURE__ */ new Map([
    ["prefix", "persons"],
    ["comand", "SetOptions"],
    ["ID", id],
    ["Value", value]
  ]);
  return AxiosRequest(true, params);
};
async function LoadGridData(data) {
  const json = await PostHandleTable("persons", void 0, data.groupID, data.SectionID);
  if (json) {
    data.gridObject.source.rights = getRightsData(json.Rights);
    data.updatePersonsData({ Archive: json.Archive === "1", ObjType: json.ObjType || "0" });
  }
  const objType = json ? json.ObjType : "0";
  data.setObjType(objType);
  const columns = parseColumns(json);
  data.gridObject.grid.setColumns(columns);
  data.gridObject.source.onHandleRequest = handleTable({
    Module: "persons",
    ObjType: objType,
    GroupID: data.groupID,
    selectedRecordID: data.ObjRef || "0",
    SectionID: data.SectionID,
    selectionMode: data.selectionMode,
    Tag: "1"
  });
  await data.gridObject.source.open();
  data.gridObject.source.onRecordIndexChanged = function(source) {
    const id = source.getFieldTextSync("ID");
    data.setSelectedRecordID(id);
  };
  data.gridObject.grid.setImageFields(["Options"]);
  data.gridObject.source.booksGetImage = (value) => {
    if (value & 1) return 3;
    if (value & 2) return 29;
  };
  await data.gridObject.grid.setSource(data.gridObject.source);
  if (!data.renderingId.personId) {
    await data.gridObject.grid.refreshSource();
    data.setSelectedRecordID(data.gridObject.source.getFieldTextSync("ID"));
  }
  await data.gridObject.grid.updateGridSize();
}
function PersonTableTab(props) {
  const [renderingId, setRenderingId] = useAtom(renderingIdAtom);
  const sideBarSelected = useAtomValue(selectedSectionAtom);
  const [mainGrid, setMainGrid] = reactExports.useState();
  const [groupID, setGroupID] = reactExports.useState();
  const [selectedRecordID, setSelectedRecordID] = reactExports.useState();
  const [selectionMode, setSelectionMode] = reactExports.useState();
  const [objType, setObjType] = reactExports.useState();
  const [settings, setSettings] = reactExports.useState();
  const [timerUpdateGrid, setTimerUpdateGrid] = reactExports.useState();
  const [collapsedTree, setCollapsedTree] = reactExports.useState(false);
  const [personsData, setPersonsData] = useAtom(sectionPersonsData);
  const dataContext = reactExports.useContext(PersonsDataContext);
  const firstLoad = reactExports.useRef(true);
  const updatePersonId = reactExports.useRef(false);
  const mainBlock = reactExports.useRef(null);
  const search = reactExports.useRef(null);
  const needUpdate = reactExports.useRef();
  const treeRef = reactExports.useRef();
  const pinnedRecords = reactExports.useRef([]);
  const cutBuffer = reactExports.useRef([]);
  const gridPanel = reactExports.useRef();
  const initSettings = async () => {
    if (!settings) setSettings(await getStaffSettings(props.SectionID) || {});
  };
  reactExports.useEffect(() => {
    GridLoader(gridPanel.current, { Module: "persons" }, {}).then((res) => {
      setMainGrid(res);
      dataContext.setTable(res);
    });
    initSettings();
    mainBlock.current.collapseTree = onCollapseTree;
    mainBlock.current.collapseSearch = updateGrid;
  }, []);
  reactExports.useEffect(() => {
    if (mainGrid) {
      mainGrid.grid.refreshSource();
    }
  }, [personsData.Archive]);
  reactExports.useEffect(() => {
    if (mainGrid) {
      mainBlock.current.updateTable = updateTable;
    }
  }, [mainGrid]);
  reactExports.useEffect(() => {
    if (mainGrid && groupID && firstLoad.current) {
      LoadGridData({
        gridObject: mainGrid,
        groupID,
        setSelectedRecordID,
        ObjRef: "0",
        SectionID: props.SectionID,
        setObjType,
        selectionMode,
        renderingId,
        updatePersonsData
      }).then(() => {
        renderingId.personId && onSelect(renderingId.personId);
        updatePersonId.current = true;
      });
      firstLoad.current = false;
      return;
    }
    if (needUpdate.current) {
      refreshGridDepTree(needUpdate.current);
      needUpdate.current = void 0;
      return;
    }
    if (groupID !== void 0) {
      refreshGridDepTree();
    }
  }, [groupID]);
  reactExports.useEffect(() => {
    if (selectedRecordID !== void 0) {
      dataContext.setPersonId(selectedRecordID);
      if (updatePersonId.current) {
        setRenderingId({ ...renderingId, personId: selectedRecordID });
      }
    }
  }, [selectedRecordID]);
  reactExports.useEffect(() => {
    if (sideBarSelected.CLSID === "{D9958041-524D-11D4-91A4-000021670179}" && mainGrid) {
      onSelect(renderingId.personId);
    }
  }, [sideBarSelected.ID]);
  const updateTable = () => {
    mainGrid && mainGrid.grid.refreshSource();
  };
  const updatePersonsData = (data) => {
    setPersonsData({ ...personsData, ...data });
  };
  async function refreshGridDepTree(index) {
    mainGrid.source.onHandleRequest = handleTable({
      Module: "persons",
      ObjType: objType,
      GroupID: groupID,
      selectedRecordID: index ? index : "0",
      SectionID: props.SectionID,
      selectionMode,
      Tag: "1"
    });
    await mainGrid.source.first();
    await mainGrid.grid.setSource(mainGrid.source);
    await mainGrid.grid.refreshSource(index);
    setSelectedRecordID(index || mainGrid.source.getFieldTextSync("ID"));
    await mainGrid.grid.updateGridSize();
  }
  function updateGrid() {
    if (smetaStore.get(animationsAtom)) {
      clearTimeout(timerUpdateGrid);
      setTimerUpdateGrid(
        setTimeout(() => {
          updateGridData(0);
        }, 251)
      );
    } else updateGridData(0);
  }
  function onCollapseTree(state) {
    setCollapsedTree(state);
    updateGrid();
  }
  function onCollapseSearch() {
    search.current.style.display = "none";
    updateGrid();
  }
  function getPersonGroup(index) {
    const params = /* @__PURE__ */ new Map();
    params.set("prefix", "persons").set("comand", "GetPersonGroup").set("ID", index);
    return AxiosRequest(true, params);
  }
  async function onSelect(index) {
    const json = await getPersonGroup(index);
    if (json && json.GroupID) {
      if (json.GroupID !== groupID) {
        needUpdate.current = index;
        if (selectionMode) {
          await treeRef.current.addGroupID(json.GroupID);
        } else {
          await treeRef.current.selectGroupID(json.GroupID);
        }
      } else {
        mainGrid.grid.refreshSource(index);
        return;
      }
    }
  }
  const onMenuClick = async () => {
    var _a;
    const json = await getBookContextMenu("persons", objType, selectedRecordID, props.SectionID);
    return { arr: [...(_a = json == null ? void 0 : json.Items) == null ? void 0 : _a.items.map((item) => item)] };
  };
  const showGroupID = () => {
    onSelect(selectedRecordID);
  };
  const selectToMove = () => {
    const selection = mainGrid.grid.getMultiSelect();
    if (selection.length === 0) {
      pushCutBuffer(selectedRecordID);
      return;
    }
    selection.forEach((id) => {
      const personID = mainGrid.source.getFieldTextSync("ID", Number(id));
      pushCutBuffer(personID);
    });
  };
  const pushCutBuffer = (id) => {
    !cutBuffer.current.includes(id) && cutBuffer.current.push(id);
  };
  const insertToGroup = async () => {
    if (cutBuffer.current.length) {
      await MoveObjects(cutBuffer.current.join(","), groupID);
      cutBuffer.current = [];
      mainGrid.grid.refreshSource();
    }
  };
  const blockFIO = () => {
    setOptionsRecord(selectedRecordID, 1);
    mainGrid.grid.refreshSource("!");
  };
  const archiveUser = () => {
    setOptionsRecord(selectedRecordID, 2);
    mainGrid.grid.refreshSource("!");
  };
  const pinSelected = () => {
  };
  const unPinSelected = () => {
  };
  const contextMenuHandler = (data) => {
    var _a;
    const comands = {
      ShowGroupID: showGroupID,
      SelectToMove: selectToMove,
      InsertToGroup: insertToGroup,
      BlockFIO: blockFIO,
      ArchiveUser: archiveUser,
      PinSelected: pinSelected,
      UnPinSelected: unPinSelected
    };
    (_a = comands[data.value]) == null ? void 0 : _a.call(comands);
  };
  const changeDataOfItem = (val) => {
    var _a;
    const changeValue = {
      BlockFIO: changeBlockFio,
      ArchiveUser: changeArchiveUser,
      UnPinSelected: changeUnPinSelected
    };
    return ((_a = changeValue[val.value]) == null ? void 0 : _a.call(changeValue, val)) || val;
  };
  const changeBlockFio = (val) => {
    let img = /* @__PURE__ */ jsxRuntimeExports.jsx(LockOutlinedIcon, {});
    let caption = "Заблокировать ФИО";
    if (mainGrid.source.getFieldTextSync("Options") & 1) {
      caption = "Разблокировать ФИО";
      img = /* @__PURE__ */ jsxRuntimeExports.jsx(LockOpenOutlinedIcon, {});
    }
    const newOptions = {
      Image: img,
      Caption: caption
    };
    return { ...val, ...newOptions };
  };
  const changeArchiveUser = (val) => {
    const newOptions = {
      Caption: mainGrid.source.getFieldTextSync("Options") & 2 ? "Извлечь из Архива личных карточек" : "Отправить в Архив личных карточек"
    };
    return { ...val, ...newOptions };
  };
  const changeUnPinSelected = (val) => {
    const newOptions = {
      Disabled: pinnedRecords.current.length === 0
    };
    return { ...val, ...newOptions };
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "div",
    {
      id: "main-person-table-block",
      ref: mainBlock,
      treecollapsed: "false",
      style: {
        height: "100%",
        width: "100%",
        border: "1px solid rgb(204, 204, 204)",
        display: "flex",
        flexDirection: "column"
      },
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ref: search, style: { display: "none" }, id: "search-person-table", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          SearchPersons,
          {
            colapseSearch: onCollapseSearch,
            module: Prefixes.person,
            sectionId: props.SectionID,
            objType,
            onSelect
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            style: {
              height: "100%",
              width: "100%",
              display: "flex",
              flex: "1 1 0"
            },
            children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
              SplitterLocal,
              {
                onResizeEnd: updateGrid,
                onCollapse: updateGrid,
                onExpand: updateGrid,
                orientation: "vertical",
                collapsed: collapsedTree,
                style: {
                  width: "100%",
                  height: "100%"
                },
                primaryIndex: 1,
                transitionDuration: 250,
                sizeSecondary: "20%",
                hideButtons: true,
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { height: "100%", width: "100%" }, children: settings && /* @__PURE__ */ jsxRuntimeExports.jsx(
                    Tree,
                    {
                      props: {
                        ref: treeRef,
                        ObjType: "2790",
                        SectionID: props.SectionID,
                        Module: "departments",
                        Current: groupID,
                        ObjRef: groupID,
                        selectID: setGroupID,
                        UsedDate: "0",
                        Info: settings.DepTypes || "0",
                        Internal: "0",
                        MultiSel: true,
                        setSelectionMode,
                        defaultMenu: [],
                        noExpandFirst: true
                      }
                    }
                  ) }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { height: "100%", width: "100%" }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    ContextMenu,
                    {
                      for: "personsTable",
                      changeDataOfItem,
                      Menu: getDefaultMenu("personsTable"),
                      onRightClick: onMenuClick,
                      onMenuItemClick: contextMenuHandler,
                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                        "div",
                        {
                          id: `rcgrid_panel`,
                          style: {
                            height: "100%",
                            width: "100%",
                            position: "relative"
                          },
                          ref: gridPanel
                        }
                      )
                    }
                  ) })
                ]
              }
            )
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { display: "flex" } })
      ]
    }
  );
}
function PersonsInnerTabs({ props }) {
  const [tabs, setTabs] = React.useState();
  React.useEffect(() => {
    setTabs(
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Tabs,
        {
          onChange: props.onChange,
          ref: props.ref,
          enableMouseWheelAction: true,
          tabPosition: props.tabPosition ? props.tabPosition : "top",
          animation: "none",
          style: { height: "100%", width: "100%" },
          children: props.tabs
        }
      )
    );
  }, [props.tabs]);
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { width: "100%", height: "100%" }, children: tabs });
}
function PersonsSubTabs({ props }) {
  const [tabs, setTabs] = React.useState();
  const [tabsData, setTabsData] = React.useState(props.detailItem);
  const [needUpdateTab, setNeedUpdateTab] = React.useState();
  const [timer, setTimer] = React.useState(null);
  const tabsRef = React.useRef();
  const detailValues = React.useRef([]);
  const mainBlock = React.useRef();
  const dataContext = reactExports.useContext(PersonsDataContext);
  React.useEffect(() => {
    mainBlock.current.update = () => setNeedUpdateTab(true);
  }, []);
  React.useEffect(() => {
    if (tabsData) {
      setTabs(getDefaultSubTabs(tabsData));
      detailValues.current = tabsData.Pages;
    }
  }, [tabsData]);
  React.useEffect(() => {
    if (needUpdateTab) {
      updateTab(tabsRef.current.selectedIndex);
      setNeedUpdateTab(false);
    }
  }, [needUpdateTab]);
  reactExports.useEffect(() => {
    setNeedUpdateTab(true);
  }, [dataContext.personId]);
  function getContentForTab(detail, index) {
    if (detail.Pages) {
      return "tabs";
    }
    if (detail.CLSID) {
      switch (detail.CLSID) {
        case "{D8402CE6-6582-4F0D-A82D-C2D9CA73F79E}":
          return "params";
        case "{48C155C0-1336-11D6-9CF2-DB1D5BC3046D}":
          return "documents";
        case "{2A10A1C9-DAA5-42ED-A452-AB062FA33064}":
          return "cadres";
        case "{295EA015-4573-4AD9-922A-A14CE0FD9C78}":
          return "children";
        case "{C83806B3-80D6-4983-A53D-1FA792B60130}":
          return "address";
        case "{D370E2F6-166E-4519-8A55-7A582F73F533}":
          return "jobHistory";
        default:
          return "emptyTab";
      }
    }
    return "emptyTab";
  }
  function updateTabsContent(data, firstLoad) {
    if (firstLoad) {
      data.firstLoadFunc();
    } else {
      updatePersonsTabContentFunc(data);
    }
  }
  function updateTab(index) {
    if (index !== void 0 && tabs) {
      clearTimeout(timer);
      const newTimer = setTimeout(() => {
        const detailItem = detailValues.current[index];
        if (!detailItem) return;
        const selector = getContentForTab(detailItem);
        const blockTab = tabsRef.current.nativeElement.getTabContent(index);
        const firstLoad = blockTab.children[0].hasAttribute("load");
        const userID = dataContext.personId;
        updateTabsContent(
          {
            // Module: props.Module,
            detailItem,
            // selectedRecordID: selectedRecordID,
            index,
            element: blockTab.ownerElement,
            selector,
            SectionID: props.SectionID,
            userID,
            firstLoadFunc: () => {
              const tabContent = getPersonsDetailContent(selector, props, {
                // selectedRecordID: selectedRecordID,
                onRequest: async () => PersonTabChange(detailItem, userID, props.SectionID, true),
                detailItem,
                userID,
                SectionID: props.SectionID
              });
              const tab = getFullSubTab(detailItem, tabContent, index);
              tabsRef.current.select(index);
              tabs[index] = tab;
              setTabs([...tabs]);
            }
          },
          firstLoad
        );
      }, 100);
      setTimer(newTimer);
    }
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      id: "sub-persons-tabs",
      ref: mainBlock,
      style: {
        width: "100%",
        height: "100%",
        paddingTop: "5px"
      },
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        PersonsInnerTabs,
        {
          props: {
            ref: tabsRef,
            tabs,
            onChange: (ev) => {
              if (ev && ev.target) return;
              setNeedUpdateTab(true);
            }
          }
        }
      )
    }
  );
}
function PersonsParams({ props }) {
  const [data, setData] = React.useState();
  const box = React.useRef();
  React.useEffect(() => {
    box.current.update = updateData;
    if (props.onRequest) {
      props.onRequest().then((res) => {
        setData(res);
      });
    }
  }, []);
  React.useEffect(() => {
    box.current.update = updateData;
  }, [data]);
  function updateData(res) {
    if (res.Props) {
      data.Items = data.Items.map((item) => {
        if (res.Props[item.ShortName]) {
          item = {
            ...item,
            Value: res.Props[item.ShortName].Value,
            EditVal: res.Props[item.ShortName].EditVal,
            ID: res.Props[item.ShortName].ID,
            TextColor: res.Props[item.ShortName].TextColor,
            CheckState: res.Props[item.ShortName].CheckState,
            ObjRef: res.Props[item.ShortName].ObjRef
          };
          return item;
        }
      });
      setData({ ...data });
    }
  }
  const getRefreshParams = async () => {
    const json = await PersonTabChange(props.detailItem, props.userID, props.SectionID, true);
    return json || { Items: [] };
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      ref: box,
      id: "params-tab-box",
      style: {
        width: "100%",
        height: "100%"
      },
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(Params, { data, NoTitle: true, NoHistory: true, getRefreshParams })
    }
  );
}
function PersonsDocs({ props }) {
  const [ParentID, setParentID] = React.useState(props.userID);
  React.useEffect(() => {
    if (props.onRequest) {
      props.onRequest().then((res) => {
        if (res && res.ParentID) {
          setParentID(ParentID);
        }
      });
    }
  }, []);
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      style: {
        width: "100%",
        height: "100%"
      },
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        SectionDocuments,
        {
          id: props.SectionID,
          ParentID,
          DocCfgID: props.detailItem.ObjType,
          HideParams: true,
          SectionToolsJS: false,
          PlaneView: "0",
          noAutoFocus: true,
          HideControlButtons: true,
          detailsOpen: true
        }
      )
    }
  );
}
const workRangesDefaultColumns = [
  {
    fieldName: "ID",
    title: "№",
    width: 35,
    level: 0,
    fieldInfo: {
      ...defaultFieldInfo,
      EditStyle: EditStyle.ReadOnly.toString(),
      textAjust: "1"
    }
  },
  {
    fieldName: "First",
    title: "Поступление",
    width: 95,
    level: 0,
    fieldInfo: {
      ...defaultFieldInfo,
      EditStyle: EditStyle.Calendar.toString(),
      textAjust: "1"
    }
  },
  {
    fieldName: "Final",
    title: "Увольнение",
    width: 95,
    level: 0,
    fieldInfo: {
      ...defaultFieldInfo,
      EditStyle: EditStyle.Calendar.toString(),
      textAjust: "1"
    }
  }
];
const saveChangeWorkRanges = (records, grid, personID) => {
  const data = [];
  records.forEach((record) => {
    const dataRecord = {};
    grid.columns.title.forEach((item) => {
      const fieldName = item.fieldName;
      const recordValue = record[fieldName];
      if (fieldName === "ID") {
        dataRecord[fieldName] = recordValue;
      } else if (fieldName === "First" || fieldName === "Final") {
        if (typeof recordValue === "object" && recordValue.id) dataRecord[fieldName] = recordValue.id;
      } else {
        if (recordValue) {
          if (typeof recordValue === "object" && recordValue.id !== "0") dataRecord[fieldName] = recordValue.id;
        } else {
          dataRecord[fieldName] = "-1";
        }
      }
    });
    data.push(dataRecord);
  });
  return smetaAxios.post(
    "SetWorkRanges",
    { Items: data },
    { prefix: Prefixes.cadr, params: { PersonID: personID }, loadMask: true }
  );
};
function WorkRanges({ props }) {
  var _a;
  const gridPanel = reactExports.useRef(null);
  const records = reactExports.useRef([]);
  const additionalColumns = reactExports.useRef();
  const personID = reactExports.useRef();
  reactExports.useEffect(() => {
    smetaAxios.get("GetWorkRangesLayout", {
      prefix: Prefixes.cadr,
      params: { SectionID: props.SectionID },
      loadMask: true
    }).then((json) => {
      var _a2;
      if (json.JSONType === "ParamColumns") additionalColumns.current = json;
      gridPanel.current.refreshMainGrid = refreshMainGrid;
      (_a2 = props.onRequest) == null ? void 0 : _a2.call(props);
      mainGridLoader().then(() => {
        refreshMainGrid(props.userID);
      });
    });
  }, []);
  const updateRecords = async (personID2) => {
    var _a2;
    const json = await smetaAxios.get("HandleWorkRanges", {
      prefix: Prefixes.cadr,
      params: { PersonID: personID2 },
      loadMask: true
    });
    if ((_a2 = json == null ? void 0 : json.Items) == null ? void 0 : _a2.items) {
      const titleColumns = gridPanel.current.grid.columns.title;
      records.current = json.Items.items.map((item) => {
        const record = { ID: item.ID };
        Object.keys(item).forEach((key) => {
          const itemKey = item[key];
          if (typeof itemKey === "object" && itemKey.FieldName) {
            const field = titleColumns.find((obj) => obj.fieldName === itemKey.FieldName);
            if (field == null ? void 0 : field.fieldInfo.Values.length) {
              const objRef = itemKey.Value || "0", textValue = field.fieldInfo.Values[objRef].label || "";
              record[itemKey.FieldName] = {
                text: textValue,
                id: objRef
              };
            } else
              record[itemKey.FieldName] = {
                text: itemKey.Text || "",
                id: itemKey.Value || "-1"
              };
          } else if (key === "First" || key === "Final") {
            record[key] = {
              text: getDateOfInt(itemKey),
              id: itemKey
            };
          } else record[key] = itemKey;
        });
        return record;
      });
    } else records.current = [];
  };
  function refreshMainGrid(userID) {
    if (personID.current != userID) {
      personID.current = userID;
      updateRecords(userID).then(gridPanel.current.grid.refreshSource);
    }
  }
  const getColumns = () => {
    let columns = {
      title: [...workRangesDefaultColumns]
    };
    if (additionalColumns.current) columns = parseColumns(additionalColumns.current, { inputColumns: columns });
    return columns;
  };
  const getDefaultFields = () => {
    var _a2;
    const defaultFields = [
      { Name: "ID", Title: "ID" },
      { Name: "First", Title: "First" },
      { Name: "Final", Title: "Final" }
    ];
    if (additionalColumns.current) {
      (_a2 = additionalColumns.current.Columns) == null ? void 0 : _a2.forEach((column) => {
        defaultFields.push({
          Name: column.FieldName,
          Title: column.FieldName
        });
      });
    }
    return defaultFields;
  };
  const getRecordKeys = () => {
    var _a2;
    const recordKeys = ["ID", "First", "Final"];
    if (additionalColumns.current) {
      (_a2 = additionalColumns.current.Columns) == null ? void 0 : _a2.forEach((column) => {
        recordKeys.push(column.FieldName);
      });
    }
    return recordKeys;
  };
  const getFieldText = (request, data) => {
    var _a2;
    const dataRecords = data.getRecords();
    if (gridPanel.current.grid.source.getState() === 3) return { Text: "" };
    if (dataRecords.length)
      return {
        Text: ((_a2 = dataRecords[request.RecordIndex][request.FieldName]) == null ? void 0 : _a2.text) || ""
      };
    return { Text: "" };
  };
  const checkFieldText = async (request, data) => {
    const source = data.source;
    return {
      Text: source.getFieldTextSync(request.FieldName),
      ObjRef: source.getFieldValueSync(request.FieldName)
    };
  };
  const onPostRecord = async (request, requestData) => {
    var _a2, _b, _c;
    const attributeIndex = requestData.length - 1;
    if (request.NewRecord === "1") {
      const newRecord = {
        ID: String(records.current.length + 1)
      };
      records.current.splice(request.RecordIndex, 0, newRecord);
    }
    const record = records.current[request.RecordIndex], modifiedField = request.RecordSet.Attributes[attributeIndex], modifiedData = requestData[attributeIndex], newText = modifiedData.text;
    let newId = modifiedData.id;
    if (!newId && newText) {
      const columnDataType = Number(
        (_c = (_b = (_a2 = additionalColumns.current) == null ? void 0 : _a2.Columns) == null ? void 0 : _b.find((column) => column.FieldName === modifiedField)) == null ? void 0 : _c.DataType
      );
      if (columnDataType >= Param.Str008 && columnDataType <= Param.Str256) {
        const json = await setParamObjectText(void 0, columnDataType, void 0, newText);
        newId = json.ObjRef;
      }
    }
    if (newText && !newId) {
      await gridPanel.current.grid.refreshSource(gridPanel.current.grid.source.activeRecord);
      gridPanel.current.grid.updateGridSize();
      return;
    }
    if (!newText && !newId) {
      delete record[modifiedField];
    } else {
      record[modifiedField] = {
        text: newText,
        id: newId
      };
    }
    await saveChangeWorkRanges(records.current, gridPanel.current.grid, personID.current);
    await gridPanel.current.grid.refreshSource(gridPanel.current.grid.source.activeRecord);
    gridPanel.current.grid.updateGridSize();
  };
  const createRecord = () => {
    const index = records.current.length ? gridPanel.current.grid.source.activeRecord + 1 : 0;
    const newRecords = [...records.current];
    const newRecord = {
      ID: String(records.current.length + 1)
    };
    newRecords.splice(index, 0, newRecord);
    return {
      index,
      records: newRecords,
      keys: ["ID"],
      titleKey: ""
    };
  };
  const deleteRecord = async (request) => {
    if (gridPanel.current.grid.source.getState() !== 3) {
      records.current.splice(request.RecordIndex, 1);
      saveChangeWorkRanges(records.current, gridPanel.current.grid, personID.current);
    }
    return {
      Command: "DeleteRecord",
      RecordIndex: records.current.length === 0 ? 0 : request.RecordIndex - 1,
      RecordCount: records.current.length,
      UpdatesPending: "1",
      RecordKey: {}
    };
  };
  const canModify = (flag, column) => {
    if (gridPanel.current.grid.OnlyViewMode) return false;
    if ((column == null ? void 0 : column.fieldName) === "ID") return false;
    return true;
  };
  async function mainGridLoader() {
    await GridLoader(
      gridPanel.current,
      {},
      {
        localGrid: true,
        refresh: false,
        Columns: getColumns(),
        defaultFields: getDefaultFields(),
        keyField: "ID",
        recordKeys: getRecordKeys(),
        titleKey: "",
        getFieldText,
        onPostRecord,
        createRecord,
        deleteRecord,
        canModify,
        checkFieldText,
        getRecordIndexRefresh: (key) => key,
        getRecords: () => records.current,
        Rights: "-1"
      }
    );
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    ContextMenu,
    {
      for: "grid",
      Menu: {
        Table: [
          {
            Caption: "Новая запись",
            value: "Insert",
            Image: /* @__PURE__ */ jsxRuntimeExports.jsx(PostAddIcon, { fontSize: "small" })
          },
          {
            Caption: "Удалить запись",
            value: "Delete",
            Image: /* @__PURE__ */ jsxRuntimeExports.jsx(DeleteIcon, { fontSize: "small" })
          },
          { Caption: "Divider" },
          { Caption: "Режим просмотра", value: "OnlyViewMode" },
          { Caption: "Сохранять отметку", value: "SaveMark", Disabled: true }
        ],
        Header: [{ Caption: "Поиск по столбцу", value: "ColumnFilter" }]
      },
      refs: { current: (_a = gridPanel.current) == null ? void 0 : _a.grid },
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          id: "work-ranges-grid",
          ref: gridPanel,
          style: {
            height: "100%",
            width: "100%",
            position: "relative",
            overflow: "hidden"
          }
        }
      )
    }
  );
}
const list = ["Адрес по прописке", "Фактический адрес", "Место рождения", "Место работы"].join("\r\n");
const GetPersonAddr = async (data) => {
  const params = /* @__PURE__ */ new Map();
  params.set("prefix", data.module).set("comand", "GetPersonAddr").set("GroupID", data.groupId).set("Index", data.type);
  return AxiosRequest(true, params);
};
const GetAddressInfo = async (data) => {
  const params = /* @__PURE__ */ new Map();
  params.set("prefix", data.module).set("comand", "GetAddressInfo").set("Type", data.type || "0").set("GroupID", data.groupId).set("ObjRef", data.objRef);
  return AxiosRequest(true, params);
};
const PersonAddrMain = async (data) => {
  const params = /* @__PURE__ */ new Map();
  params.set("prefix", data.module).set("comand", "PersonAddrMain").set("GroupID", data.groupId).set("Checked", data.checked);
  return AxiosRequest(true, params);
};
function PersonsAddress({ props }) {
  const [data, setData] = reactExports.useState();
  const useKladr = reactExports.useRef();
  const type = reactExports.useRef(0);
  const checkbox = reactExports.useRef();
  const userId = reactExports.useRef(props.userID);
  const checkContainer = reactExports.useRef();
  const box = reactExports.useRef();
  reactExports.useEffect(() => {
    box.current.update = updateData;
    getKladr();
    getType();
  }, []);
  const getKladr = async () => {
    const json = await GetAddressUseKladr();
    if (json.service === "1") {
      useKladr.current = true;
      return;
    }
    useKladr.current = false;
  };
  const getType = async () => {
    const json = await GetPersonAddr({
      module: "persons",
      groupId: userId.current,
      type: type.current
    });
    if (json) {
      checkbox.current = json.Checked === "1" && json.Checked || "0";
      getData(json.ID);
    }
  };
  const getData = async (objRef) => {
    const json = await GetAddressInfo({
      module: "persons",
      type: type.current,
      groupId: userId.current,
      objRef
    });
    if (json && json.Values) {
      setData({ ...getParamsObject(json, userId.current, json.Caption), Type: json.Type });
    }
  };
  const changeTypeSettings = async () => {
    await getType();
  };
  async function updateData(id) {
    userId.current = id;
    changeTypeSettings();
  }
  const onEditTypeAddress = async (data2) => {
    type.current = data2.tag;
    checkContainer.current.style.display = data2.tag === 1 ? "" : "none";
    changeTypeSettings();
    data2.setValue({
      label: data2.value,
      id: data2.tag
    });
    data2.setInputValue(data2.value);
  };
  const onEditCheckbox = async (data2) => {
    checkbox.current = data2.CheckState;
    await PersonAddrMain({
      module: "persons",
      groupId: userId.current,
      checked: checkbox.current
    });
    changeTypeSettings();
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { ref: box, id: "address-tab-box", className: "mainTabBox", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "typeAddressContainer", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "typeAddressContent", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "typeAddressLabel", children: "Вид адреса:" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "typeAddressInputContainer", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Editor, { value: "Адрес по прописке", editStyle: 65, list, onEdit: onEditTypeAddress }) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "typeAddressCheckBox", style: { display: "none" }, ref: checkContainer, children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "typeAddressCheckBoxLabel", children: "По прописке:" }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(CheckBoxMultiCheck, { CheckState: checkbox.current, onEdit: onEditCheckbox })
      ] })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "addressParamsContainer", children: /* @__PURE__ */ jsxRuntimeExports.jsx(AddressParams, { data, NoTitle: true, NoHistory: true, useKladr: useKladr.current, Module: "persons" }) })
  ] });
}
function PersonsChildren({ props }) {
  const [mainGrid, setMainGrid] = reactExports.useState();
  const gridPanel = reactExports.useRef();
  const mainBox = reactExports.useRef();
  reactExports.useEffect(() => {
    var _a;
    (_a = props.onRequest) == null ? void 0 : _a.call(props).then((res) => {
      GridLoader(
        gridPanel.current,
        { Module: "cadres", Path: res.Params.Path, SectionID: props.SectionID, ObjType: "0", GroupID: props.userID },
        {}
      ).then(setMainGrid);
    });
  }, []);
  reactExports.useEffect(() => {
    mainBox.current.refreshMainGrid = refreshMainGrid;
  }, [mainGrid]);
  const refreshMainGrid = async (data) => {
    mainGrid.source.onHandleRequest = handleCadresRequest({
      Module: "cadres",
      Path: data.Path,
      SectionID: props.SectionID,
      GroupID: data.userID
    });
    await mainGrid.grid.setSource(mainGrid.source);
    await mainGrid.grid.refreshSource();
    await mainGrid.grid.updateGridSize();
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      ref: mainBox,
      id: "children-grid",
      style: {
        width: "100%",
        height: "100%"
      },
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(ContextMenu, { for: "personsChildren", Menu: getDefaultMenu("personsChildren"), children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          id: `rcgrid_panel`,
          ref: gridPanel,
          style: {
            height: "100%",
            width: "100%",
            position: "relative"
          }
        }
      ) })
    }
  );
}
function getColumnsJobHistory() {
  return {
    title: [
      {
        fieldName: "Title",
        title: "Должность (организация)",
        width: 200,
        fieldInfo: { ...defaultFieldInfo }
      },
      {
        fieldName: "$value",
        title: "Ставки",
        width: 70,
        fieldInfo: { ...defaultFieldInfo }
      },
      {
        fieldName: "StartDate",
        title: "Начало",
        width: 100,
        fieldInfo: { ...defaultFieldInfo }
      },
      {
        fieldName: "DocumentText",
        title: "Приказ назначения",
        width: 200,
        fieldInfo: { ...defaultFieldInfo }
      },
      {
        fieldName: "EndDate",
        title: "Конец",
        width: 100,
        fieldInfo: { ...defaultFieldInfo }
      },
      {
        fieldName: "LastDocText",
        title: "Приказ снятия",
        width: 200,
        fieldInfo: { ...defaultFieldInfo }
      },
      {
        fieldName: "Mode",
        title: "Форма",
        width: 100,
        fieldInfo: { ...defaultFieldInfo }
      }
    ]
  };
}
function getDefaultFieldsJobHistory() {
  return [
    {
      Name: "ID",
      Title: "ID",
      Width: "20"
    },
    {
      Name: "Title",
      Title: "Должность (организация)",
      Width: "20"
    },
    {
      Name: "$value",
      Title: "Ставки",
      Width: "20"
    },
    {
      Name: "StartDate",
      Title: "Начало",
      Width: "20"
    },
    {
      Name: "DocumentText",
      Title: "Приказ назначения",
      Width: "20"
    },
    {
      Name: "EndDate",
      Title: "Конец",
      Width: "20"
    },
    {
      Name: "LastDocText",
      Title: "Приказ снятия",
      Width: "20"
    },
    {
      Name: "Mode",
      Title: "Форма",
      Width: "20"
    },
    {
      Name: "Document",
      Title: "Document",
      Width: "20"
    },
    {
      Name: "LastDoc",
      Title: "LastDoc",
      Width: "20"
    }
  ];
}
function getRecordsJobHistory(records) {
  return records.map((item) => {
    const newItem = {
      ...item,
      StartDate: item.StartDate && Number(item.StartDate) > 0 ? getDateOfInt(item.StartDate) : "",
      EndDate: item.EndDate && Number(item.EndDate) > 0 ? getDateOfInt(item.EndDate || 0) : ""
    };
    return newItem;
  });
}
const GetStaffParams = (data) => {
  const params = /* @__PURE__ */ new Map();
  params.set("prefix", "staff").set("comand", "GetStaffParams").set("Path", data.Path).set("ID", data.ID).set("ObjType", data.ObjType);
  return AxiosRequest(true, params);
};
const GetJobHistory = (data) => {
  const params = /* @__PURE__ */ new Map();
  params.set("prefix", "staff").set("comand", "GetJobHistory").set("PersonID", data.userID);
  return AxiosRequest(true, params);
};
const updateGridOnSplitterStateChange = () => updateGridData(0);
function PersonsJobHistory({ props }) {
  const [data, setData] = reactExports.useState();
  const [paramsData, setParamsData] = reactExports.useState();
  const [selectedRecord, setSelectedRecord] = reactExports.useState();
  const [mainGrid, setMainGrid] = reactExports.useState();
  const userID = reactExports.useRef(props.userID);
  const mainBox = reactExports.useRef(null);
  const gridPanelRef = reactExports.useRef(null);
  const recordIndexRefresh = reactExports.useRef();
  const records = reactExports.useRef([]);
  reactExports.useEffect(() => {
    GetJobHistory({ userID: userID.current }).then((res) => {
      var _a, _b;
      setData(res);
      if ((_a = res == null ? void 0 : res.Items) == null ? void 0 : _a.items) records.current = getRecordsJobHistory((_b = res == null ? void 0 : res.Items) == null ? void 0 : _b.items);
      mainGridLoader();
    });
  }, []);
  reactExports.useEffect(() => {
    if (mainBox.current) mainBox.current.refreshMainGrid = refreshGrid;
  }, [mainGrid]);
  reactExports.useEffect(() => {
    if (data && data.Params) setParamsData(data.Params);
    recordIndexRefresh.current = records.current.findIndex((el) => el.ID === (data == null ? void 0 : data.ID));
    recordIndexRefresh.current && (mainGrid == null ? void 0 : mainGrid.grid.refreshSource(data == null ? void 0 : data.ID));
  }, [data]);
  reactExports.useEffect(() => {
    if (selectedRecord !== void 0) {
      updateParamsData(selectedRecord);
    }
  }, [selectedRecord]);
  const mainGridLoader = async () => {
    setMainGrid(
      await GridLoader(gridPanelRef.current, props, {
        localGrid: true,
        refresh: false,
        Columns: getColumnsJobHistory(),
        defaultFields: getDefaultFieldsJobHistory(),
        keyField: "ID",
        recordKeys: ["ID", "Title", "$value", "DocumentText", "StartDate", "EndDate", "LastDocText", "Mode"],
        getRecords: () => records.current,
        Rights: "0",
        setSelectedRecord,
        getRecordIndexRefresh
      })
    );
  };
  const getRecordIndexRefresh = () => {
    return recordIndexRefresh.current;
  };
  const refreshGrid = async (id) => {
    var _a, _b;
    const res = await GetJobHistory({ userID: id });
    setData(res);
    if ((_a = res == null ? void 0 : res.Items) == null ? void 0 : _a.items) records.current = getRecordsJobHistory((_b = res == null ? void 0 : res.Items) == null ? void 0 : _b.items);
    recordIndexRefresh.current = records.current.findIndex((el) => el.ID === (res == null ? void 0 : res.ID));
    await (mainGrid == null ? void 0 : mainGrid.grid.refreshSource());
  };
  const updateParamsData = async (id) => {
    const res = await GetStaffParams({
      Path: paramsData == null ? void 0 : paramsData.Path,
      ObjType: paramsData == null ? void 0 : paramsData.ObjType,
      ID: id
    });
    if (res.Props) {
      const newItems = paramsData == null ? void 0 : paramsData.Items.map((item) => {
        var _a, _b, _c, _d, _e, _f;
        let newItem = {
          ...item,
          Value: (_a = res.Props[item.ShortName]) == null ? void 0 : _a.Value,
          EditVal: (_b = res.Props[item.ShortName]) == null ? void 0 : _b.EditVal,
          ID: (_c = res.Props[item.ShortName]) == null ? void 0 : _c.ID,
          TextColor: (_d = res.Props[item.ShortName]) == null ? void 0 : _d.TextColor,
          CheckState: (_e = res.Props[item.ShortName]) == null ? void 0 : _e.CheckState,
          ObjRef: (_f = res.Props[item.ShortName]) == null ? void 0 : _f.ObjRef
        };
        return newItem;
      });
      const newParamsData = {
        ...paramsData,
        Items: newItems || []
      };
      setParamsData(newParamsData);
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      id: "job-history-tab-box",
      ref: (ref) => {
        mainBox.current = ref;
      },
      className: "mainTabBox",
      children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        SplitterLocal,
        {
          orientation: "horizontal",
          onExpand: updateGridOnSplitterStateChange,
          onCollapse: updateGridOnSplitterStateChange,
          onResizeEnd: updateGridOnSplitterStateChange,
          sizeSecondary: "20%",
          defaultCollapsed: false,
          primaryIndex: 0,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "fullSpaceContainer", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { id: `rcgrid_panel`, ref: gridPanelRef, className: "fullSpaceContainer" }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "fullSpaceContainer", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Params, { data: paramsData }) })
          ]
        }
      )
    }
  );
}
async function GetPersonBlocks() {
  const params = /* @__PURE__ */ new Map();
  params.set("prefix", "persons").set("comand", "GetPersonBlocks");
  return AxiosRequest(true, params);
}
async function getTabsDataForDataMainTabs() {
  const json = await GetPersonBlocks();
  return json;
}
function getDefaultMainTabs(data) {
  if (data && data.Items && data.Items.length) {
    return data.Items.map((item, index) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        TabItem,
        {
          id: `LoadTab_${item.Caption}`,
          "data-data": item,
          style: {
            textTransform: "none",
            width: "100%",
            height: "100%",
            paddingBottom: "2px",
            marginLeft: "0",
            display: "inline-block"
          },
          label: item.Caption,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                style: {
                  height: "30px",
                  width: "100%",
                  fontSize: "150%",
                  display: "flex",
                  borderBottom: "1px solid #cccccc",
                  paddingLeft: "10px",
                  alignItems: "center",
                  color: "#616161",
                  backgroundColor: "rgba(220, 216, 204,0.5)",
                  boxShadow: "0px 3px 5px rgba(0, 0, 0, 0.2)"
                },
                children: item.Caption
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                id: `item_${item.Caption}`,
                load: "true",
                style: {
                  width: "100%",
                  height: "calc(100% - 30px)",
                  position: "relative"
                },
                children: /* @__PURE__ */ jsxRuntimeExports.jsx(LoadingMask, {})
              }
            )
          ]
        },
        `TabItem_${item.Caption}_${index}`
      );
    });
  }
}
const devDiv = /* @__PURE__ */ jsxRuntimeExports.jsx(
  "div",
  {
    style: {
      height: "100%",
      width: "100%",
      display: "flex",
      alignItems: "center",
      justifyContent: "center"
    },
    children: "Функционал в разработке"
  }
);
function getPersonsDetailContent(selector, props, data) {
  const properties = { ...props, ...data };
  const content = {
    tabs: /* @__PURE__ */ jsxRuntimeExports.jsx(PersonsSubTabs, { props: properties }),
    params: /* @__PURE__ */ jsxRuntimeExports.jsx(PersonsParams, { props: properties }),
    documents: /* @__PURE__ */ jsxRuntimeExports.jsx(PersonsDocs, { props: properties }),
    cadres: /* @__PURE__ */ jsxRuntimeExports.jsx(WorkRanges, { props: properties }),
    children: /* @__PURE__ */ jsxRuntimeExports.jsx(PersonsChildren, { props: properties }),
    address: /* @__PURE__ */ jsxRuntimeExports.jsx(PersonsAddress, { props: properties }),
    jobHistory: /* @__PURE__ */ jsxRuntimeExports.jsx(PersonsJobHistory, { props: properties })
  };
  return content[selector] || devDiv;
}
async function PersonTabChange(item, userID, SectionID, full) {
  const params = /* @__PURE__ */ new Map();
  params.set("prefix", "persons").set("comand", "PersonTabChange").set("ID", userID).set("prm", item.prm).set("tag", item.tag).set("CLSID", item.CLSID).set("ProgID", item.ProgID).set("Path", item.Path).set("SectionID", SectionID);
  if (full) params.set("Full", "1");
  return AxiosRequest(true, params);
}
const tabsUpdate = async (data) => {
  const tabContainer = data.element.querySelector("#sub-persons-tabs");
  if (tabContainer) {
    tabContainer.update();
  }
};
const paramsUpdate = async (data) => {
  const jsonParams = await PersonTabChange(data.detailItem, data.userID, data.SectionID);
  const parambox = data.element.querySelector("#params-tab-box");
  if (parambox && parambox.update) {
    parambox.update(jsonParams);
  }
};
const documentsUpdate = async (data) => {
  await PersonTabChange(data.detailItem, data.userID, data.SectionID);
  const docDiv = data.element.querySelector(`#Documents${data.SectionID}`);
  if (docDiv && docDiv.refreshMainGrid) {
    docDiv.refreshMainGrid({
      DocCfgID: data.detailItem.DocCfgID ? data.detailItem.DocCfgID : data.detailItem.ObjType,
      ParentID: data.userID
    });
  }
};
const cadresUpdate = async (data) => {
  await PersonTabChange(data.detailItem, data.userID, data.SectionID);
  const workRangesGrid = data.element.querySelector("#work-ranges-grid");
  if (workRangesGrid && workRangesGrid.refreshMainGrid) {
    workRangesGrid.refreshMainGrid(data.userID);
  }
};
const childrenUpdate = async (data) => {
  var _a;
  const jsonChildren = await PersonTabChange(data.detailItem, data.userID, data.SectionID);
  const childrenGrid = data.element.querySelector("#children-grid");
  if (childrenGrid && childrenGrid.refreshMainGrid) {
    childrenGrid.refreshMainGrid({ Path: (_a = jsonChildren == null ? void 0 : jsonChildren.Params) == null ? void 0 : _a.Path, userID: data.userID });
  }
};
const addressUpdate = async (data) => {
  await PersonTabChange(data.detailItem, data.userID, data.SectionID);
  const addressBox = data.element.querySelector("#address-tab-box");
  if (addressBox && addressBox.update) {
    addressBox.update(data.userID);
  }
};
const jobHistoryUpdate = async (data) => {
  await PersonTabChange(data.detailItem, data.userID, data.SectionID);
  const jobHistoryGrid = data.element.querySelector("#job-history-tab-box");
  jobHistoryGrid && jobHistoryGrid.refreshMainGrid(data.userID);
};
async function updatePersonsTabContentFunc(data) {
  var _a;
  const updtFuncs = {
    tabs: tabsUpdate,
    params: paramsUpdate,
    documents: documentsUpdate,
    cadres: cadresUpdate,
    children: childrenUpdate,
    address: addressUpdate,
    jobHistory: jobHistoryUpdate
  };
  (_a = updtFuncs[data.selector]) == null ? void 0 : _a.call(updtFuncs, data);
}
function getPersonsFullTab(detailItem, content, index) {
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    TabItem,
    {
      id: `Tab_${detailItem.Caption}`,
      style: {
        textTransform: "none",
        width: "100%",
        height: "100%",
        paddingBottom: "2px",
        display: "inline-block"
      },
      label: detailItem.Caption,
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            style: {
              height: "30px",
              width: "100%",
              fontSize: "150%",
              display: "flex",
              borderBottom: "1px solid #cccccc",
              paddingLeft: "10px",
              alignItems: "center",
              color: "#616161",
              backgroundColor: "rgba(220, 216, 204,0.5)",
              boxShadow: "0px 3px 5px rgba(0, 0, 0, 0.2)"
            },
            children: detailItem.Caption
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            id: `item_${detailItem.Caption}`,
            style: {
              width: "100%",
              height: "calc(100% - 30px)",
              position: "relative"
            },
            children: content
          }
        )
      ]
    },
    `TabItem_${detailItem.Caption}_${index}`
  );
}
function getDefaultSubTabs(data) {
  if (data && data.Pages && data.Pages.length) {
    return data.Pages.map((item, index) => {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        TabItem,
        {
          id: `LoadTab_${item.Caption}`,
          "data-data": item,
          style: {
            textTransform: "none",
            width: "100%",
            height: "100%",
            paddingBottom: "2px",
            marginLeft: "0",
            display: "inline-block"
          },
          label: item.Caption,
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              id: `item_${item.Caption}`,
              load: "true",
              style: {
                width: "100%",
                height: "100%",
                position: "relative"
              },
              children: /* @__PURE__ */ jsxRuntimeExports.jsx(LoadingMask, {})
            }
          )
        },
        `TabItem_${item.Caption}_${index}`
      );
    });
  }
}
function getFullSubTab(detailItem, content, index) {
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    TabItem,
    {
      id: `Tab_${detailItem.Caption}`,
      style: {
        textTransform: "none",
        width: "100%",
        height: "100%",
        paddingBottom: "2px",
        display: "inline-block"
      },
      label: detailItem.Caption,
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          id: `item_${detailItem.Caption}`,
          style: {
            width: "100%",
            height: "100%",
            position: "relative"
          },
          children: content
        }
      )
    },
    `TabItem_${detailItem.Caption}_${index}`
  );
}
var PersonOutlineOutlined = {};
var hasRequiredPersonOutlineOutlined;
function requirePersonOutlineOutlined() {
  if (hasRequiredPersonOutlineOutlined) return PersonOutlineOutlined;
  hasRequiredPersonOutlineOutlined = 1;
  var _interopRequireDefault = requireInteropRequireDefault();
  Object.defineProperty(PersonOutlineOutlined, "__esModule", {
    value: true
  });
  PersonOutlineOutlined.default = void 0;
  var _createSvgIcon = _interopRequireDefault(/* @__PURE__ */ requireCreateSvgIcon());
  var _jsxRuntime = requireJsxRuntime();
  PersonOutlineOutlined.default = (0, _createSvgIcon.default)(/* @__PURE__ */ (0, _jsxRuntime.jsx)("path", {
    d: "M12 5.9c1.16 0 2.1.94 2.1 2.1s-.94 2.1-2.1 2.1S9.9 9.16 9.9 8s.94-2.1 2.1-2.1m0 9c2.97 0 6.1 1.46 6.1 2.1v1.1H5.9V17c0-.64 3.13-2.1 6.1-2.1M12 4C9.79 4 8 5.79 8 8s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4m0 9c-2.67 0-8 1.34-8 4v3h16v-3c0-2.66-5.33-4-8-4"
  }), "PersonOutlineOutlined");
  return PersonOutlineOutlined;
}
var PersonOutlineOutlinedExports = /* @__PURE__ */ requirePersonOutlineOutlined();
const PersonOutlineOutlinedIcon = /* @__PURE__ */ getDefaultExportFromCjs(PersonOutlineOutlinedExports);
function selectFile(data) {
  const input = createInput(data);
  input.click();
}
function createInput(data) {
  const fileSelector = document.createElement("input");
  fileSelector.setAttribute("type", "file");
  fileSelector.setAttribute("accept", data.filter || "file");
  data.multiple && fileSelector.setAttribute("multiple", data.multiple);
  fileSelector.addEventListener("change", async (e) => {
    if (!e.target) return;
    const files = Array.from(e.target.files);
    const filesNames = files.map((file) => file.name).join("\n");
    const filesData = await Promise.all(files.map((file) => getBase64ByFileReader(file)));
    const finalData = filesData.reduce(
      (acc, fileData, index) => ({
        ...acc,
        [files[index].name]: {
          size: files[index].size,
          rcdata: fileData.rcdata
        }
      }),
      {}
    );
    const resultObject = {
      files,
      filesNames,
      filesData,
      finalData
    };
    data.onSelect(resultObject);
  });
  return fileSelector;
}
const getPersonPhoto = async (id) => {
  const params = /* @__PURE__ */ new Map();
  params.set("prefix", "persons").set("comand", "GetPersonPhoto").set("ID", id);
  return AxiosRequest(true, params);
};
const setPersonPhoto = async (id, data) => {
  const params = /* @__PURE__ */ new Map();
  params.set("prefix", "persons").set("comand", "SetPersonPhoto").set("ID", id).set("WSM", "1");
  return AxiosRequest(true, params, data);
};
function PersonInfo() {
  const [firstName, setFirstName] = reactExports.useState("");
  const [secondName, setSecondName] = reactExports.useState("");
  const [thirdName, setThirdName] = reactExports.useState("");
  const [applyButtonDisabled, setApplyButtonDisabled] = reactExports.useState(true);
  const [photo, setPhoto] = reactExports.useState();
  const [date, setDate] = reactExports.useState("");
  const [sex, setSex] = reactExports.useState("");
  const dataContext = reactExports.useContext(PersonsDataContext);
  const mainBlock = reactExports.useRef();
  const fullName = reactExports.useRef();
  const newFullName = reactExports.useRef();
  reactExports.useEffect(() => {
    updateInfo();
    mainBlock.current.updateInfo = updateInfo;
  }, [dataContext]);
  reactExports.useEffect(() => {
    if (!dataContext.personId) return;
    if (!mainBlock.current.checkVisibility()) return;
    updateInfo();
    getPersonPhoto(dataContext.personId).then((res) => {
      if (!(res == null ? void 0 : res.RCDATA)) {
        setPhoto("");
        return;
      }
      (res == null ? void 0 : res.RCDATA) && setPhoto(res.RCDATA);
    });
  }, [dataContext.personId]);
  reactExports.useEffect(() => {
    newFullName.current = `${secondName} ${firstName} ${thirdName}`;
  }, [firstName, secondName, thirdName]);
  const updateInfo = () => {
    if (dataContext.table) {
      const nameUser = dataContext.table.source.getFieldTextSync("FIO");
      const birthDateUser = dataContext.table.source.getFieldTextSync("BirthDate");
      const sexUser = dataContext.table.source.getFieldTextSync("Sex");
      fullName.current = nameUser;
      setName(nameUser);
      setDate(birthDateUser);
      setSex(sexUser === "Ж" ? "female" : "male");
    }
  };
  const setName = (name) => {
    if (!name) {
      setSecondName("");
      setFirstName("");
      setThirdName("");
      return;
    }
    const nameArr = name.split(" ");
    nameArr.length && setSecondName(nameArr[0]);
    nameArr.length > 1 ? setFirstName(nameArr[1]) : setFirstName("");
    nameArr.length > 2 ? setThirdName(nameArr[2]) : setThirdName("");
  };
  const onChangeSex = async (ev) => {
    var _a, _b;
    setSex(ev.target.value);
    await ((_a = dataContext.table) == null ? void 0 : _a.grid.postSomeData("Sex", { text: ev.target.value === "female" ? "Ж" : "М" }));
    await ((_b = dataContext.table) == null ? void 0 : _b.grid.postExicstedEditRec(true));
  };
  const onEditFirstName = (data) => {
    setFirstName(data.value);
    setApplyButtonDisabled(false);
  };
  const onEditSecondName = (data) => {
    setSecondName(data.value);
    setApplyButtonDisabled(false);
  };
  const onEditThirdName = (data) => {
    setThirdName(data.value);
    setApplyButtonDisabled(false);
  };
  const onEditDate = async (data) => {
    var _a, _b;
    await ((_a = dataContext.table) == null ? void 0 : _a.grid.postSomeData("BirthDate", { text: data.value, id: data.tag }));
    await ((_b = dataContext.table) == null ? void 0 : _b.grid.postExicstedEditRec(true));
  };
  const onApplyName = async () => {
    var _a, _b;
    await ((_a = dataContext.table) == null ? void 0 : _a.grid.postSomeData("FIO", { text: newFullName.current }));
    await ((_b = dataContext.table) == null ? void 0 : _b.grid.postExicstedEditRec(true));
    fullName.current = newFullName.current;
    setApplyButtonDisabled(true);
  };
  const onCancelName = () => {
    setName(fullName.current);
    setApplyButtonDisabled(true);
  };
  const uploadPhoto = async () => {
    selectFile({
      filter: "image/png, image/gif, image/jpeg",
      onSelect: async (data) => {
        const json = await setPersonPhoto(dataContext.personId, {
          FileName: data.filesNames,
          $content: data.filesData[0]
        });
        if (json.Token) {
          tokenProcessingTest(json);
          return;
        }
        (json == null ? void 0 : json.RCDATA) && setPhoto(json.RCDATA);
      }
    });
  };
  const deletePhoto = async () => {
    const json = await setPersonPhoto(dataContext.personId);
    if (json.Token) {
      tokenProcessingTest(json);
      return;
    }
    setPhoto("");
  };
  const contextMenuHandler = (data) => {
    var _a;
    const comands = {
      SetPhoto: uploadPhoto,
      DeletePhoto: deletePhoto
    };
    (_a = comands[data.value]) == null ? void 0 : _a.call(comands);
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { id: "person-info-block", ref: mainBlock, className: "mainTabBox", children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "personInfoHeader", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "personInfoHeaderContainer", children: dataContext.table && dataContext.table.grid && dataContext.table.source && /* @__PURE__ */ jsxRuntimeExports.jsx(
      ButtonsForGridComponent,
      {
        grid: dataContext.table,
        buttons: {
          navigate: true,
          delete: true,
          create: true
        }
      }
    ) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "personInfoPhoto", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ContextMenu, { for: "personsPhoto", Menu: getDefaultMenu("personsPhoto"), onMenuItemClick: contextMenuHandler, children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "personInfoPhotoContainer", children: photo ? /* @__PURE__ */ jsxRuntimeExports.jsx("img", { className: "personPhoto", src: `data:image/gif;base64,${photo}` }) : /* @__PURE__ */ jsxRuntimeExports.jsx(Icon, { className: "personPhoto", children: /* @__PURE__ */ jsxRuntimeExports.jsx(PersonOutlineOutlinedIcon, { className: "personPhoto personPhotoDefault" }) }) }) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "personInfoContainer", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "personInfoNameContainer", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "personInfoNameItem", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Editor,
        {
          onEdit: onEditSecondName,
          styleInput: {
            fontSize: "1rem",
            fontWeight: "400"
          },
          value: secondName
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "personInfoNameItem", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Editor,
        {
          onEdit: onEditFirstName,
          styleInput: {
            fontSize: "1rem",
            fontWeight: "400"
          },
          value: firstName
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "personInfoNameItem", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Editor,
        {
          onEdit: onEditThirdName,
          styleInput: {
            fontSize: "1rem",
            fontWeight: "400"
          },
          value: thirdName
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "personInfoNameItem personInfoNameApplyButtonsContainer", children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(IconButton, { onClick: onCancelName, disabled: applyButtonDisabled, className: "personInfoNameApplyButton", children: /* @__PURE__ */ jsxRuntimeExports.jsx(ClearOutlinedIcon, { className: "personInfoNameApplyIcon" }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(IconButton, { onClick: onApplyName, disabled: applyButtonDisabled, className: "personInfoNameApplyButton", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CheckOutlinedIcon, { className: "personInfoNameApplyIcon" }) })
      ] })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "personInfoContainer", children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "personInfoDateContainer", children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "personInfoDateLabel", children: "Дата рождения:" }),
      /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "personInfoDateEditorContainer", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        Editor,
        {
          onEdit: onEditDate,
          styleInput: {
            fontSize: "1rem",
            fontWeight: "400"
          },
          value: date,
          editStyle: 2
        }
      ) })
    ] }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "personInfoContainer", children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "personInfoSexRadioButtonsContainer", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(FormControl, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(FormLabel, { id: "demo-radio-buttons-group-label", children: "Пол" }),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        RadioGroup,
        {
          onChange: onChangeSex,
          "aria-labelledby": "demo-radio-buttons-group-label",
          value: sex,
          name: "radio-buttons-group",
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(FormControlLabel, { value: "female", control: /* @__PURE__ */ jsxRuntimeExports.jsx(Radio, {}), label: "Женский" }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(FormControlLabel, { value: "male", control: /* @__PURE__ */ jsxRuntimeExports.jsx(Radio, {}), label: "Мужской" })
          ]
        }
      )
    ] }) }) })
  ] });
}
function PersonDataTab(props) {
  const [tabs, setTabs] = React.useState([]);
  const [tabsData, setTabsData] = React.useState();
  const [needUpdateTab, setNeedUpdateTab] = React.useState();
  const [collapsed, setCollapsed] = React.useState(false);
  const [timerUpdateGrid, setTimerUpdateGrid] = React.useState();
  const [timer, setTimer] = React.useState(null);
  const tabsRef = React.useRef();
  const mainBlock = React.useRef();
  const detailValues = React.useRef([]);
  const dataContext = reactExports.useContext(PersonsDataContext);
  React.useEffect(() => {
    getTabsDataForDataMainTabs().then((res) => {
      setTabsData(res);
    });
    mainBlock.current.update = () => {
      setNeedUpdateTab(true);
    };
    mainBlock.current.collapseInfo = (state) => {
      setCollapsed(state);
      updateGrid();
    };
  }, []);
  React.useEffect(() => {
    if (tabsData) {
      setTabs(getDefaultMainTabs(tabsData));
      detailValues.current = tabsData.Items;
    }
  }, [tabsData]);
  reactExports.useEffect(() => {
    if (!mainBlock.current.checkVisibility()) return;
    setNeedUpdateTab(true);
  }, [dataContext.personId]);
  React.useEffect(() => {
    if (needUpdateTab) {
      updateTab(tabsRef.current.selectedIndex);
      setNeedUpdateTab(false);
    }
  }, [needUpdateTab]);
  function getContentForTab(detail, index) {
    if (detail.Pages) {
      return "tabs";
    }
    if (detail.CLSID) {
      switch (detail.CLSID) {
        case "{D8402CE6-6582-4F0D-A82D-C2D9CA73F79E}":
          return "params";
        case "{48C155C0-1336-11D6-9CF2-DB1D5BC3046D}":
          return "documents";
        case "{2A10A1C9-DAA5-42ED-A452-AB062FA33064}":
          return "cadres";
        case "{295EA015-4573-4AD9-922A-A14CE0FD9C78}":
          return "children";
        case "{C83806B3-80D6-4983-A53D-1FA792B60130}":
          return "address";
        case "{D370E2F6-166E-4519-8A55-7A582F73F533}":
          return "jobHistory";
        default:
          return "emptyTab";
      }
    }
    return "emptyTab";
  }
  async function updateTabsContent(data, firstLoad) {
    if (firstLoad) {
      data.firstLoadFunc();
    } else {
      await updatePersonsTabContentFunc(data);
    }
  }
  function updateTab(index) {
    if (index !== void 0 && tabs) {
      clearTimeout(timer);
      const newTimer = setTimeout(async () => {
        const detailItem = detailValues.current[index];
        if (!detailItem) return;
        const selector = getContentForTab(detailItem);
        const blockTab = tabsRef.current.nativeElement.getTabContent(index);
        const firstLoad = blockTab.children[1].hasAttribute("load");
        const userID = dataContext.personId;
        await updateTabsContent(
          {
            // Module: props.Module,
            detailItem,
            // selectedRecordID: selectedRecordID,
            index,
            element: blockTab.ownerElement,
            selector,
            SectionID: props.SectionID,
            userID,
            // onRequest: getReqForContent(selector),
            firstLoadFunc: () => {
              const tabContent = getPersonsDetailContent(selector, props, {
                onRequest: async () => PersonTabChange(detailItem, userID, props.SectionID, true),
                detailItem,
                userID,
                SectionID: props.SectionID
              });
              const tab = getPersonsFullTab(detailItem, tabContent, index);
              tabsRef.current.select(index);
              tabs[index] = tab;
              setTabs([...tabs]);
            }
          },
          firstLoad
        );
      }, 100);
      setTimer(newTimer);
    }
  }
  function updateGrid() {
    if (smetaStore.get(animationsAtom)) {
      clearTimeout(timerUpdateGrid);
      setTimerUpdateGrid(
        setTimeout(() => {
          updateGridData(0);
        }, 251)
      );
    } else updateGridData(0);
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    "div",
    {
      id: "persons-data-tabs",
      ref: mainBlock,
      treecollapsed: "false",
      style: {
        height: "100%",
        width: "100%",
        border: "1px solid rgb(204, 204, 204)"
      },
      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          style: {
            height: "100%",
            width: "100%"
          },
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
            SplitterLocal,
            {
              blockResize: true,
              orientation: "vertical",
              style: {
                width: "100%",
                height: "100%"
              },
              collapsed,
              primaryIndex: 1,
              transitionDuration: 250,
              sizeSecondary: "230px",
              children: [
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { height: "100%", width: "100%", borderRight: "1px solid #cccccc" }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(PersonInfo, { tableRef: props.tableRef }) }),
                /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { height: "100%", width: "100%" }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                  Tabs,
                  {
                    onChange: (ev) => {
                      if (ev && ev.target) return;
                      setNeedUpdateTab(true);
                    },
                    ref: tabsRef,
                    enableMouseWheelAction: true,
                    tabPosition: "bottom",
                    animation: "none",
                    style: { height: "100%", width: "100%" },
                    children: tabs
                  }
                ) })
              ]
            }
          )
        }
      )
    }
  );
}
const PersonsDataContext = reactExports.createContext({
  table: null,
  setTable: null,
  personId: null,
  setPersonId: null
});
function PersonDataMainTabs({ props }) {
  const selectedSection = useAtomValue(selectedSectionAtom);
  const [tabIndex, setTabIndex] = reactExports.useState(0);
  const [table, setTable] = reactExports.useState(null);
  const [personId, setPersonId] = reactExports.useState(null);
  const [context, setContext] = reactExports.useState({
    table,
    setTable,
    personId,
    setPersonId
  });
  const setDocsTabIndex = reactExports.useRef();
  reactExports.useEffect(() => {
    const contextData = {
      table,
      setTable: (val) => setTable(val),
      personId,
      setPersonId: (val) => setPersonId(val)
    };
    setContext(contextData);
  }, [table, personId]);
  reactExports.useEffect(() => {
    if (props.SectionID === selectedSection.ID) {
      if (selectedSection.Who) {
        selectTab(2);
      }
    }
  }, [selectedSection]);
  reactExports.useEffect(() => {
    firstLoadContent();
  }, []);
  function onBreadCrumbClick() {
    setTabIndex(2);
  }
  async function firstLoadContent() {
    props.setButtons({
      tree: true,
      search: true,
      check: true,
      userArh: true,
      card: false
    });
  }
  function selectTab(index) {
    setTabIndex(index);
  }
  const onTabChange = async (index, element, data, actualIndex) => {
    setTabIndex(index);
    if (index === 0) {
      const personTable = element.querySelector("#main-person-table-block");
      setTimeout(() => {
        personTable.updateTable();
      });
      props.setButtons({
        tree: true,
        search: true,
        check: true,
        userArh: true
      });
    }
    if (index === 1) {
      const personDataTabsContainer = element.querySelector("#persons-data-tabs");
      setTimeout(() => {
        personDataTabsContainer.update();
      });
      const personDataInfoContainer = element.querySelector("#person-info-block");
      setTimeout(() => {
        personDataInfoContainer.updateInfo();
      });
      props.setButtons({
        tree: false,
        search: true,
        check: false,
        userArh: false,
        card: true
      });
    }
    if (index === 2) {
      props.setButtons({
        tree: false,
        search: false,
        check: false,
        userArh: false,
        card: false
      });
    }
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsx(PersonsDataContext.Provider, { value: context, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
    SmetaTabs,
    {
      onTabReClick: () => {
        var _a;
        return tabIndex === 2 && ((_a = setDocsTabIndex.current) == null ? void 0 : _a.call(setDocsTabIndex));
      },
      style: { height: "100%", width: "100%", display: "flex" },
      position: "top",
      tabIndex,
      onTabIndexChange: onTabChange,
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaTabItem, { label: "Общий список", children: /* @__PURE__ */ jsxRuntimeExports.jsx(PersonTableTab, { SectionID: props.SectionID }) }, `person-data-tab_Общий-список`),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaTabItem, { label: "Индивидуально", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          PersonDataTab,
          {
            buttonsFunctions: props.buttonsFunctions,
            setButtonsFunctions: props.setButtonsFunctions,
            SectionID: props.SectionID
          }
        ) }, `person-data-tab_Индивидуально`),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaTabItem, { label: "Документы", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          SectionDocumentsChose,
          {
            id: props.SectionID,
            sectionTools: false,
            setParentFunc: (func) => {
              setDocsTabIndex.current = func;
            },
            onBreadCrumbClick
          }
        ) }, `person-data-tab_Документы`),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaTabItem, { label: "Отчеты", children: /* @__PURE__ */ jsxRuntimeExports.jsx(SectionReports, { CLSID: props.CLSID, id: props.SectionID }) }, `person-data-tab_Отчеты`)
      ]
    }
  ) });
}
var BadgeOutlined = {};
var hasRequiredBadgeOutlined;
function requireBadgeOutlined() {
  if (hasRequiredBadgeOutlined) return BadgeOutlined;
  hasRequiredBadgeOutlined = 1;
  var _interopRequireDefault = requireInteropRequireDefault();
  Object.defineProperty(BadgeOutlined, "__esModule", {
    value: true
  });
  BadgeOutlined.default = void 0;
  var _createSvgIcon = _interopRequireDefault(/* @__PURE__ */ requireCreateSvgIcon());
  var _jsxRuntime = requireJsxRuntime();
  BadgeOutlined.default = (0, _createSvgIcon.default)([/* @__PURE__ */ (0, _jsxRuntime.jsx)("path", {
    d: "M14 12h4v1.5h-4zm0 3h4v1.5h-4z"
  }, "0"), /* @__PURE__ */ (0, _jsxRuntime.jsx)("path", {
    d: "M20 7h-5V4c0-1.1-.9-2-2-2h-2c-1.1 0-2 .9-2 2v3H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2m-9 0V4h2v5h-2zm9 13H4V9h5c0 1.1.9 2 2 2h2c1.1 0 2-.9 2-2h5z"
  }, "1"), /* @__PURE__ */ (0, _jsxRuntime.jsx)("circle", {
    cx: "9",
    cy: "13.5",
    r: "1.5"
  }, "2"), /* @__PURE__ */ (0, _jsxRuntime.jsx)("path", {
    d: "M11.08 16.18c-.64-.28-1.34-.43-2.08-.43s-1.44.15-2.08.43c-.56.24-.92.78-.92 1.39V18h6v-.43c0-.61-.36-1.15-.92-1.39"
  }, "3")], "BadgeOutlined");
  return BadgeOutlined;
}
var BadgeOutlinedExports = /* @__PURE__ */ requireBadgeOutlined();
const BadgeOutlinedIcon = /* @__PURE__ */ getDefaultExportFromCjs(BadgeOutlinedExports);
const setShowArchive = async (data) => {
  const params = /* @__PURE__ */ new Map([
    ["prefix", "persons"],
    ["comand", "SetShowArchive"],
    ["ObjType", data.objType],
    ["Value", data.value ? "1" : "0"]
  ]);
  return AxiosRequest(true, params);
};
function SectionPersonalData({ SectionID, sectionData }) {
  const data = {
    SectionID: !SectionID ? sectionData.ID : SectionID
  };
  const [personsData, setPersonsData] = useAtom(sectionPersonsData);
  const [buttons, setButtons] = React.useState({
    tree: true,
    search: true,
    check: true,
    userArh: true,
    card: true
  });
  const tabsBlock = React.useRef();
  const styleButton = {
    margin: "0px 2px 0px 1px",
    width: "30px",
    height: "30px"
  };
  function onSearchClick() {
    const tabPanel = tabsBlock.current.querySelector("#person-data-main-tabs");
    const searchBlock = tabsBlock.current.querySelector("#search-person-table");
    const tableBlock = tabsBlock.current.querySelector("#main-person-table-block");
    if (tabPanel && tabPanel.selectedIndex !== 0) {
      tabPanel.select(0);
      if (searchBlock) {
        searchBlock.style.display = "flex";
      }
    } else {
      if (searchBlock) {
        if (searchBlock.style.display === "none") {
          searchBlock.style.display = "flex";
        } else searchBlock.style.display = "none";
      }
    }
    if (tableBlock) {
      tableBlock.collapseSearch();
    }
  }
  function onTreeClick() {
    const tableBlock = tabsBlock.current.querySelector("#main-person-table-block");
    if (tableBlock) {
      tableBlock.treecollapsed = tableBlock.treecollapsed === "false" ? "true" : "false";
      tableBlock.collapseTree(tableBlock.treecollapsed === "false");
    }
  }
  async function onCardClick() {
    await setShowArchive({ value: !personsData.Archive, objType: personsData.ObjType });
    setPersonsData({ ...personsData, Archive: !personsData.Archive });
  }
  function onPersonInfoClick() {
    const Block = tabsBlock.current.querySelector("#persons-data-tabs");
    if (Block) {
      Block.treecollapsed = Block.treecollapsed === "false" ? "true" : "false";
      Block.collapseInfo(Block.treecollapsed === "false");
    }
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { width: "100%", height: "100%" }, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "div",
    {
      style: {
        width: "100%",
        height: "100%",
        display: "flex",
        flexDirection: "column"
      },
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            style: {
              width: "100%",
              display: "flex",
              borderTop: "1px solid rgba(0,0,0,0.1)",
              borderBottom: "1px solid rgba(0,0,0,0.1)",
              paddingLeft: "9px",
              alignItems: "center"
            },
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                IconButton,
                {
                  style: buttons.tree ? styleButton : { display: "none" },
                  title: "Окно структурных подразделений",
                  onClick: onTreeClick,
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(SpaceDashboardOutlinedIcon, { style: { transform: "rotate(+180deg)", fontSize: "100%" } })
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                IconButton,
                {
                  title: "Панель поиска",
                  style: buttons.search ? styleButton : { display: "none" },
                  onClick: onSearchClick,
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(SearchIcon, { style: { fontSize: "100%" } })
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                IconButton,
                {
                  style: buttons.userArh ? { ...styleButton, border: personsData.Archive && "1px solid" } : { display: "none" },
                  title: "Архив личных карточек",
                  onClick: onCardClick,
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(AccountBoxOutlinedIcon, { style: { fontSize: "100%" } })
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(IconButton, { disabled: true, style: buttons.check ? styleButton : { display: "none" }, title: "", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CheckBoxIcon, { style: { fontSize: "100%" } }) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                IconButton,
                {
                  style: buttons.card ? styleButton : { display: "none" },
                  title: "Панель общих сведений",
                  onClick: onPersonInfoClick,
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(BadgeOutlinedIcon, { style: { fontSize: "100%" } })
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  style: {
                    height: "100%",
                    borderRight: "1px solid rgba(0,0,0,0.1)",
                    position: "relative",
                    left: "8px"
                  }
                }
              ),
              data.SectionID && data.SectionID > 100 ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { width: "100%", display: "flex" }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(SectionToolsJS, { ID: data.SectionID }) }) : null
            ]
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            ref: tabsBlock,
            style: {
              width: "100%",
              display: "flex",
              flex: "1 1 0"
            },
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              PersonDataMainTabs,
              {
                props: {
                  data: sectionData,
                  SectionID: data.SectionID,
                  setButtons
                }
              }
            )
          }
        )
      ]
    }
  ) });
}
export {
  SectionPersonalData as default
};
//# sourceMappingURL=SectionPersonalData-BFn2gtxv.js.map
