import { b2 as defaultFieldInfo, u as useAtomValue, b7 as selectedSectionAtom, bt as animationsAtom, z as currentTheme, r as reactExports, db as NormMode, aP as HourMask, c6 as getMonthInfo, j as jsxRuntimeExports, a3 as Tree, aN as ObjType, cF as getRendHistoryParams, ah as AxiosRequest, ae as getRightsData, V as isEmptyObject, d2 as DelphiColors, x as Grid2, T as Tooltip, I as IconButton, bR as ImgURL, bS as getIcons, ct as Divider, bM as SectionToolsJS, bG as SmetaTabs, bH as SmetaTabItem, bf as Prefixes, ax as SplitterLocal, ao as cn, d as Box, cr as Link, F as FormControl, bE as RadioGroup, i as FormControlLabel, bF as Radio, k as Checkbox, ai as Editor, bv as EditStyle, aU as ContextMenu, bu as getStaffSettings, aM as checkCurrentUserRights, as as dayjs, cy as createRecordSource, cA as createGrid, b4 as updateGridData, bj as getIntOfStrDate, ac as tokenProcessingTest, c$ as setColor, af as parseColumns } from "./index-D15x63tD.js";
import { M as MonthYearPicker } from "./MonthYearPicker-CnPllbI6.js";
import { S as SearchPersons } from "./SearchPersons-C1hfxGSb.js";
import { L as Leaves } from "./Leaves-BvV0zspE.js";
import SectionDocumentsChose from "./SectionDocumentsChose-CWNMUy0u.js";
import SectionReports from "./SectionReports-CR4VT6wR.js";
import "./DialogDoc-BCKCegu0.js";
import "./DialogDocTabs-ExyRNCmU.js";
const timeTableDefaultColumns = [
  {
    fieldName: "PersonName",
    title: "Ф. И. О.",
    width: 200,
    level: 0,
    fieldInfo: { ...defaultFieldInfo, titleAjust: "0" }
  },
  {
    fieldName: "TabNumber",
    title: "Таб. №",
    width: 55,
    level: 0,
    fieldInfo: { ...defaultFieldInfo, textAjust: "1" }
  },
  {
    fieldName: "Appointment",
    title: "Должность",
    width: 130,
    level: 0,
    fieldInfo: { ...defaultFieldInfo, titleAjust: "0" }
  },
  {
    fieldName: "Appointment",
    title: "Название",
    width: 150,
    level: 1,
    fieldInfo: { ...defaultFieldInfo, titleAjust: "0" }
  },
  {
    fieldName: "JobMode",
    title: "Форма",
    width: 90,
    level: 1,
    fieldInfo: { ...defaultFieldInfo }
  },
  {
    fieldName: "RateCount",
    title: "Ставка",
    width: 55,
    level: 1,
    fieldInfo: { ...defaultFieldInfo, textAjust: "1" }
  },
  {
    fieldName: "FirstDate",
    title: "Назначен",
    width: 80,
    level: 1,
    fieldInfo: { ...defaultFieldInfo, textAjust: "1" }
  },
  { fieldName: "LastDate", title: "Снят", width: 80, level: 1, fieldInfo: { ...defaultFieldInfo, textAjust: "1" } }
];
function setCollumsForGrid(json, grid) {
  let columns = {
    title: [...timeTableDefaultColumns]
  };
  for (let index = 1; index <= 31; index++) {
    columns.title.push({
      fieldName: `Day${index}`,
      title: index.toString(),
      hide: true,
      width: 30,
      level: 0,
      fieldInfo: { ...defaultFieldInfo, textAjust: "1" }
    });
  }
  if (json.Columns) {
    json.Columns.forEach((column) => {
      column.TextAjust = "1";
      column.FieldName = `Time${column.ID}`;
    });
  }
  columns = parseColumns(json, { inputColumns: columns });
  grid.setColumns(columns);
}
const mfInsert = 0, mfEdit = 1, mfDelete = 2;
function localCanModify(flag, me) {
  if (me.OnlyViewMode) return false;
  switch (flag) {
    case mfInsert:
      return me.getActiveSource().rights.insert;
    case mfEdit:
      return me.getActiveSource().rights.modify;
    case mfDelete:
      return me.getActiveSource().rights.delete;
  }
  return false;
}
function SectionTimeTable(props) {
  const selectedSection = useAtomValue(selectedSectionAtom);
  const animationsOn = useAtomValue(animationsAtom);
  const theme = useAtomValue(currentTheme);
  const [staffSettings, setStaffSettings] = reactExports.useState({});
  const [tree, setTree] = reactExports.useState(null);
  const treeRef = reactExports.useRef();
  const [selectionMode, setSelectionMode] = reactExports.useState(true);
  const [timerUpdateGrid, setTimerUpdateGrid] = reactExports.useState(void 0);
  const [collapsedTree, setCollapsedTree] = reactExports.useState(false);
  const [collapsedSearch, setCollapsedSearch] = reactExports.useState(true);
  const [collapsedLeaves, setCollapsedLeaves] = reactExports.useState(true);
  const [timeModeDay, setTimeModeDay] = reactExports.useState(false);
  const [normType, setNormType] = reactExports.useState(NormMode.Days);
  const [hoursType, setHoursType] = reactExports.useState(HourMask.Day);
  const [allHoursType, setAllHoursType] = reactExports.useState(true);
  const [timeTableClosed, setTimeTableClosed] = reactExports.useState(false);
  const [selectedTimeCfg, setSelectedTimeCfg] = reactExports.useState({ id: "", text: "" });
  const [monthYearSelected, setMonthYearSelected] = reactExports.useState(() => {
    const currentMonthInfo = getMonthInfo();
    return {
      year: String(currentMonthInfo.year),
      month: String(currentMonthInfo.month)
    };
  });
  const [selectedRecordRenderingID, setSelectedRecordRenderingID] = reactExports.useState("0");
  const [groupdID, setGroupdID] = reactExports.useState("");
  const mainGridRef = reactExports.useRef();
  const additionalColumnsTime = reactExports.useRef({});
  const calculatedColumns = reactExports.useRef({});
  const dayColors = reactExports.useRef([]);
  const [selectedTabIndex, setSelectedTabIndex] = reactExports.useState(0);
  const [enableTimeTableClosed, setEnableTimeTableClosed] = reactExports.useState(false);
  const selectedRecordsRef = reactExports.useRef([]);
  const stateOfViewRef = reactExports.useRef(false);
  const [disabledClearSelection, setDisabledClearSelection] = reactExports.useState(true);
  const [disabledMarkSelected, setDisabledMarkSelected] = reactExports.useState(true);
  const [searchResult, setSearchResult] = reactExports.useState();
  const [usedDateTree, setUsedDateTree] = reactExports.useState("0");
  const [timerResetGrid, setTimerResetGrid] = reactExports.useState(void 0);
  const multiSelectRenderingID = reactExports.useRef([]);
  const setDocsTabIndex = reactExports.useRef();
  reactExports.useEffect(() => {
    if (props.sectionId === selectedSection.ID) {
      if (selectedSection.Who) {
        if (selectedSection.Who === "Report") {
          setSelectedTabIndex(staffSettings.WithOutDocs === "1" ? 1 : 2);
        } else {
          setSelectedTabIndex(1);
        }
      }
    }
  }, [selectedSection]);
  async function loadInitialData() {
    const json = await getStaffSettings(props.sectionId);
    setStaffSettings(json);
    await buildGrid();
    let canModifyTimeTableClosed = localCanModify(mfEdit, mainGridRef.current.grid);
    if (canModifyTimeTableClosed) {
      canModifyTimeTableClosed = await checkCurrentUserRights(ObjType.TimeTable, mfEdit, true);
    }
    setEnableTimeTableClosed(canModifyTimeTableClosed);
  }
  reactExports.useEffect(() => {
    loadInitialData();
  }, []);
  reactExports.useEffect(() => {
    if (mainGridRef.current.grid) {
      mainGridRef.current.grid.source.onHandleRequest = onHandleRequestTimeTable();
      mainGridRef.current.grid.canModify = canModify;
    }
  }, [
    selectedRecordRenderingID,
    normType,
    selectedTimeCfg,
    allHoursType,
    hoursType,
    timeModeDay,
    timeTableClosed,
    monthYearSelected
  ]);
  reactExports.useEffect(() => {
    if (tree === null) {
      setTree(
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Tree,
          {
            props: {
              ref: treeRef,
              MultiSel: true,
              defaultMultiSel: true,
              Module: "departments",
              ObjType: ObjType.Department,
              SectionID: props.sectionId,
              Info: "0",
              UsedDate: usedDateTree,
              current: groupdID,
              ObjRef: groupdID,
              selectID: setGroupdID,
              setSelectionMode,
              defaultMenu: [],
              noExpandFirst: true
            }
          }
        )
      );
    }
  }, [tree]);
  reactExports.useEffect(() => {
    var _a;
    if ((_a = mainGridRef.current) == null ? void 0 : _a.grid) {
      clearTimeout(timerResetGrid);
      setTimerResetGrid(
        setTimeout(() => {
          resetRenderingGrid();
        }, 10)
      );
    }
  }, [groupdID, monthYearSelected]);
  reactExports.useLayoutEffect(() => {
    if (searchResult) {
      scrollToSearchResult(searchResult);
      setSearchResult(void 0);
    }
  }, [searchResult]);
  function checkNewPeriod(rendHistoryParams) {
    let newPeriod = null;
    const year = Number(monthYearSelected.year), month = Number(monthYearSelected.month);
    if (rendHistoryParams.ObjLD) {
      let objDate = dayjs(rendHistoryParams.ObjLD), objDateMonth = objDate.month() + 1, objDateYear = objDate.year();
      if (year > objDateYear || year === objDateYear && month > objDateMonth) {
        newPeriod = { year: String(objDateYear), month: String(objDateMonth) };
      } else {
        objDate = dayjs(rendHistoryParams.ObjFD);
        objDateMonth = objDate.month() + 1;
        objDateYear = objDate.year();
        if (year < objDateYear || year === objDateYear && month < objDateMonth)
          newPeriod = { year: String(objDateYear), month: String(objDateMonth) };
      }
    } else {
      const objFD = dayjs(rendHistoryParams.ObjFD), objFDMonth = objFD.month() + 1, objFDYear = objFD.year();
      if (year < objFDYear || year === objFDYear && month < objFDMonth)
        newPeriod = { year: String(objFDYear), month: String(objFDMonth) };
    }
    return newPeriod;
  }
  async function scrollToSearchResult(objRef) {
    const json = await getRendHistoryParams(objRef);
    const newPeriod = checkNewPeriod(json);
    setSelectedRecordRenderingID(json.RenderingID);
    if (groupdID.includes(json.DepartmentID)) {
      if (newPeriod) {
        await handlePeriodChange(newPeriod);
      } else mainGridRef.current.grid.refreshSource(json.RenderingID);
    } else {
      if (newPeriod) await handlePeriodChange(newPeriod);
      if (selectionMode) {
        await treeRef.current.addGroupID(json.DepartmentID);
      } else {
        await treeRef.current.selectGroupID(json.DepartmentID);
      }
    }
  }
  async function resetSelection() {
    const params = /* @__PURE__ */ new Map();
    params.set("prefix", "tables");
    params.set("comand", "ResetSelection");
    if (stateOfViewRef.current && selectedRecordsRef.current.length > 0)
      params.set("Value", selectedRecordsRef.current.join(","));
    return AxiosRequest(true, params);
  }
  async function resetRenderings() {
    const params = /* @__PURE__ */ new Map();
    params.set("prefix", "tables");
    params.set("comand", "ResetRenderings");
    params.set("SectionID", props.sectionId);
    params.set("Year", monthYearSelected.year);
    params.set("Month", monthYearSelected.month);
    return AxiosRequest(true, params, { $content: groupdID });
  }
  async function resetRenderingGrid() {
    await getTableLayout(false, mainGridRef.current.grid.source);
    changeDayColumns(!timeModeDay);
    const json = await resetRenderings();
    setTimeTableClosed(json.Closed === "1");
    await mainGridRef.current.grid.refreshSource(selectedRecordRenderingID);
    const renderingId = await mainGridRef.current.grid.source.getFieldValue("RenderingID");
    setSelectedRecordRenderingID(renderingId);
    setDisabledMarkSelected(mainGridRef.current.grid.source.recordCount === 0);
  }
  async function getTableLayout(full, source) {
    const params = /* @__PURE__ */ new Map(), data = { $content: "" };
    params.set("prefix", "tables").set("comand", "GetTableLayout").set("SectionID", props.sectionId).set("Year", monthYearSelected.year).set("Month", monthYearSelected.month);
    if (full) params.set("Full", "1");
    data.$content = groupdID;
    const json = await AxiosRequest(true, params, data);
    dayColors.current = json.DayColors.split(",");
    if (json.Rights) source.rights = getRightsData(json.Rights);
    return json;
  }
  function onHandleRequestTimeTable() {
    return async function(request, load) {
      const params = /* @__PURE__ */ new Map();
      params.set("prefix", "tables");
      if (request.Command === "PostRecord") {
        params.set("comand", "ChangeRendTime");
        params.set("RenderingID", selectedRecordRenderingID);
        params.set("Year", monthYearSelected.year);
        params.set("Month", monthYearSelected.month);
        if (!isEmptyObject(additionalColumnsTime.current))
          params.set("Time", Object.values(additionalColumnsTime.current).join(","));
        const modifiedField = request.RecordSet.Attributes[0];
        let modifiedData = request.RecordSet.Records.Record.$Data[0].text || void 0;
        if (modifiedField.startsWith("Day")) {
          params.set("Type", normType.toString());
          if (normType === NormMode.Units && selectedTimeCfg.id) params.set("TimeCfg", selectedTimeCfg.id);
          if (normType === NormMode.Hours) params.set("Mask", allHoursType ? HourMask.Total : hoursType);
          params.set("Day", modifiedField.replace("Day", ""));
        } else {
          if (additionalColumnsTime.current[modifiedField] === "-1") {
            const levelField = mainGridRef.current.grid.columns.levels.find(
              (level) => level.field.fieldName === modifiedField
            );
            modifiedData = modifiedData == null ? void 0 : modifiedData.split(",");
            levelField == null ? void 0 : levelField.items.forEach(async (item, index) => {
              params.set("TimeCfg", additionalColumnsTime.current[item.field.fieldName]);
              params.set("Value", modifiedData ? modifiedData[index] : void 0);
              await AxiosRequest(load === void 0 ? true : load, params);
            });
            return { refresh: "" };
          } else params.set("TimeCfg", additionalColumnsTime.current[modifiedField]);
        }
        params.set("Value", modifiedData);
      } else {
        params.set("comand", "HandleTable");
        params.set("SectionID", props.sectionId);
        params.set("ObjType", ObjType.Rendering);
        if (request.command === "getRecords") {
          if (!isEmptyObject(additionalColumnsTime.current))
            request.Time = Object.values(additionalColumnsTime.current).join(",");
          if (timeModeDay) {
            request.Type = normType.toString();
            if (normType === NormMode.Units && selectedTimeCfg.id) request.TimeCfg = selectedTimeCfg.id;
            if (normType === NormMode.Hours) request.Mask = allHoursType ? HourMask.Total : hoursType;
          }
        }
      }
      const json = await AxiosRequest(
        load === void 0 ? true : load,
        params,
        request.Command !== "PostRecord" ? request : void 0
      );
      if (request.command === "getFields") {
        for (let index = 1; index <= 31; index++) {
          json.Fields.push({ Name: `Day${index}`, Type: 1 });
        }
        Object.keys(additionalColumnsTime.current).forEach((key) => {
          json.Fields.push({ Name: key, Type: 1 });
        });
      }
      if (request.command === "getRecords") {
        const additionalAttributes = Object.keys(additionalColumnsTime.current);
        additionalAttributes.forEach((attribut) => {
          json.RecordSet.Attributes.push(attribut);
        });
        if (timeModeDay) {
          for (let index = 1; index <= dayColors.current.length; index++) {
            json.RecordSet.Attributes.push(`Day${index}`);
          }
        }
        json.RecordSet.Records.forEach((column) => {
          if (column.Time) {
            additionalAttributes.forEach((attribut) => {
              if (calculatedColumns.current[attribut]) {
                let textColor = "0";
                const columnText = [];
                calculatedColumns.current[attribut].forEach((fieldName) => {
                  const timeColumn = column.Time[additionalColumnsTime.current[fieldName]];
                  if (timeColumn == null ? void 0 : timeColumn.Fixed) textColor = DelphiColors.clBlue.toString();
                  if (timeColumn == null ? void 0 : timeColumn.Text) columnText.push(timeColumn.Text);
                });
                column.Data.push({ id: textColor, text: columnText.join(" / ") });
              } else {
                const timeColumn = column.Time[additionalColumnsTime.current[attribut]];
                column.Data.push({
                  id: (timeColumn == null ? void 0 : timeColumn.Fixed) === "1" ? DelphiColors.clBlue.toString() : "0",
                  text: (timeColumn == null ? void 0 : timeColumn.Text) || ""
                });
              }
            });
            if (column.Time.items) {
              column.Time.items.forEach((item) => {
                const textColor = item.Fixed === "1" ? DelphiColors.clBlue.toString() : item.TextColor || "0";
                column.Data.push({ id: `${item.BackColor || "0"},${textColor}`, text: item.Text || "" });
              });
            }
          }
        });
      }
      return json;
    };
  }
  function canModify(flag, column, grid) {
    if (column && !column.fieldName.startsWith("Day") && !column.fieldName.startsWith("Time")) return false;
    const activeSource = grid.getActiveSource();
    const canModify2 = flag === mfEdit && activeSource.getFieldValueSync("RenderingID") && localCanModify(flag, grid);
    if (canModify2) {
      if (timeTableClosed) return false;
      if ((activeSource.getFieldValueSync("ReadOnly") & 1) !== 0) return false;
      if (column.fieldName.startsWith("Day")) {
        if (normType === NormMode.Days || !timeModeDay) return false;
        if (activeSource.getFieldTextSync(column.fieldName) === "x") return false;
        if (Number(column.fieldName.substring(3)) > dayColors.current.length) return false;
      }
    }
    return canModify2;
  }
  async function onDoubleClickHandler(table) {
    const renderingID = await mainGridRef.current.grid.source.getFieldValue("RenderingID");
    const index = selectedRecordsRef.current.indexOf(renderingID);
    if (index !== -1) {
      selectedRecordsRef.current.splice(index, 1);
      if (table) changeTableStyle(table, false);
    } else {
      selectedRecordsRef.current.push(renderingID);
      if (table) changeTableStyle(table, true);
    }
    if (stateOfViewRef.current) {
      stateOfViewRef.current = selectedRecordsRef.current.length !== 0;
      await resetSelection();
      await resetRenderings();
      await mainGridRef.current.grid.refreshSource(selectedRecordRenderingID);
      const renderingId = await mainGridRef.current.grid.source.getFieldValue("RenderingID");
      setSelectedRecordRenderingID(renderingId);
      setDisabledMarkSelected(stateOfViewRef.current);
    }
    setDisabledClearSelection(selectedRecordsRef.current.length === 0);
  }
  function changeTableStyle(table, isSelected, isMultiSelected = false) {
    const firtsCol = table.querySelector(".grid-td");
    const allTd = table.querySelectorAll(".grid-td");
    const applyStyles = (firtsColBgColor, cellColor, tableBgColor) => {
      if (firtsCol) firtsCol.style.backgroundColor = firtsColBgColor;
      changeCellColor(cellColor);
      table.style.backgroundColor = tableBgColor;
    };
    if (isMultiSelected) {
      applyStyles("", "white", "");
    } else if (isSelected && !stateOfViewRef.current) {
      applyStyles("white", "white", "#1200ff");
    } else {
      applyStyles("", "", "");
    }
    function changeCellColor(colorText) {
      var _a;
      for (const cell of Object.values(allTd)) {
        if (((_a = cell.field) == null ? void 0 : _a.fieldName) && cell.field.fieldName !== "PersonName") {
          let textColor = colorText;
          let bgColor = "";
          if (cell.field.fieldName.startsWith("Day") && !colorText) {
            const colorCell = mainGridRef.current.grid.source.getFieldValueSync(cell.field.fieldName, table.recordIndex).split(",");
            if (colorCell[0] !== "0") bgColor = setColor(colorCell[0]);
            if (colorCell[1] !== "0") textColor = setColor(colorCell[1]);
          }
          if (cell.field.fieldName.startsWith("Time") && !colorText) {
            const colorCell = mainGridRef.current.grid.source.getFieldValueSync(
              cell.field.fieldName,
              table.recordIndex
            );
            if (colorCell !== "0") textColor = setColor(colorCell);
          }
          cell.style.color = textColor;
          cell.style.backgroundColor = bgColor;
        }
      }
    }
  }
  async function getImageIndex(grid) {
    if (grid == null ? void 0 : grid.source) {
      const indexVal = await grid.source.getFieldValue("JobMode");
      const listImageValues = grid.source.fields.find((field) => field.fieldName === "JobMode");
      if ((listImageValues == null ? void 0 : listImageValues.list) && indexVal) {
        const imageIndexObj = listImageValues.list[Number(indexVal)];
        return [imageIndexObj.id];
      }
    }
  }
  async function changeGridStyles(table) {
    if (table.classList[0] === "grid-item") {
      const renderingID = await mainGridRef.current.grid.source.getFieldValue("RenderingID", table.recordIndex);
      const isSelected = selectedRecordsRef.current.includes(renderingID);
      const isMultiSelected = multiSelectRenderingID.current.includes(renderingID);
      changeTableStyle(table, isSelected, isMultiSelected);
    }
  }
  async function buildGrid() {
    var _a, _b;
    const source = new createRecordSource();
    await resetSelection();
    const data = await getTableLayout(true, source);
    source.onHandleRequest = onHandleRequestTimeTable();
    source.GetFieldTextRequest = async (flag, field) => {
      return { Text: await mainGridRef.current.grid.source.getFieldText(field) };
    };
    source.onRecordIndexChanged = (source2) => {
      source2.getFieldValue("RenderingID").then((id) => {
        setSelectedRecordRenderingID(id);
      });
    };
    mainGridRef.current.grid = new createGrid(mainGridRef.current);
    const grid = mainGridRef.current.grid;
    grid.onMultiSelectChange = (grid2) => {
      const multiSelect = grid2.getMultiSelect();
      const selectedRenderingID = [];
      multiSelect.forEach((item) => {
        selectedRenderingID.push(grid2.getActiveSource().getFieldValueSync("RenderingID", Number(item)));
      });
      grid2.data.querySelectorAll(".grid-multi-selection-row").forEach((table) => {
        changeTableStyle(table, false, true);
      });
      multiSelectRenderingID.current = selectedRenderingID;
    };
    grid.canModify = canModify;
    grid.changeGridStyles = changeGridStyles;
    grid.onGetImageIndex = getImageIndex;
    if (data.Columns)
      data.Columns.forEach((column) => {
        column.DataType = "-1";
      });
    setCollumsForGrid(data, grid);
    if (data.Columns) {
      data.Columns.forEach((column) => {
        additionalColumnsTime.current[column.FieldName] = column.Time;
        if (column.Time === "-1") {
          const levelColumnTime = mainGridRef.current.grid.columns.levels.find(
            (level) => level.field.fieldName === column.FieldName
          );
          calculatedColumns.current[column.FieldName] = levelColumnTime == null ? void 0 : levelColumnTime.items.map((item) => item.field.fieldName);
        }
      });
    }
    await grid.setSource(source);
    const timeCfgList = await onDropDownList();
    setSelectedTimeCfg({ id: ((_a = timeCfgList[0]) == null ? void 0 : _a.id) || "", text: ((_b = timeCfgList[0]) == null ? void 0 : _b.label) || "" });
  }
  const handleTabChange = async (index) => {
    setSelectedTabIndex(index);
    const documentButtons = document.getElementById(`buttons_for_section${props.sectionId}`);
    if (index === 1) {
      if (documentButtons) documentButtons.style.display = "";
    } else {
      if (documentButtons) documentButtons.style.display = "none";
    }
    updateGridData(0);
  };
  function updateSizeForGrid() {
    if (animationsOn) {
      clearTimeout(timerUpdateGrid);
      setTimerUpdateGrid(
        setTimeout(() => {
          updateGridData(0);
        }, 251)
      );
    } else {
      clearTimeout(timerUpdateGrid);
      setTimerUpdateGrid(
        setTimeout(() => {
          updateGridData(0);
        }, 1)
      );
    }
  }
  function handleColapseTree() {
    setCollapsedTree(!collapsedTree);
    updateSizeForGrid();
  }
  function handleColapseSearch() {
    setCollapsedSearch(!collapsedSearch);
    updateSizeForGrid();
  }
  function handleColapseLeaves() {
    setCollapsedLeaves(!collapsedLeaves);
    updateSizeForGrid();
  }
  async function handleOnlySelected() {
    stateOfViewRef.current = !stateOfViewRef.current;
    setDisabledMarkSelected(stateOfViewRef.current);
    await resetSelection();
    await resetRenderings();
    await mainGridRef.current.grid.refreshSource(selectedRecordRenderingID);
    const renderingId = await mainGridRef.current.grid.source.getFieldValue("RenderingID");
    setSelectedRecordRenderingID(renderingId);
  }
  async function handlePeriodChange(period) {
    if (staffSettings.UseDepartHisroty === "1") {
      const lastDateMonth = String(
        getIntOfStrDate(dayjs(`${period.year}-${period.month}-01`).endOf("month").format("DD.MM.YYYY"))
      );
      setUsedDateTree(lastDateMonth);
      await treeRef.current.refreshTree(groupdID, { UsedDate: lastDateMonth });
    }
    setMonthYearSelected(period);
  }
  async function onDropDownList() {
    const params = /* @__PURE__ */ new Map();
    params.set("prefix", "tables").set("comand", "GetObjectValues").set("ObjType", "2723");
    const json = await AxiosRequest(true, params);
    if (json && json.Items) {
      return json.Items.map((item, index) => {
        if (typeof item === "object") {
          return { label: item.text, id: item.id };
        }
        return { label: item, id: index };
      });
    }
  }
  function changeDayColumns(hide) {
    const columns = mainGridRef.current.grid.columns.title.filter(
      (column) => column.fieldName.startsWith("Day")
    );
    columns.forEach((column, index) => {
      column.hide = hide;
      if (column.fieldInfo) {
        column.fieldInfo.textColor = dayColors.current[index];
      } else column.fieldInfo = { textColor: dayColors.current[index] };
      if (!hide && Number(column.fieldName.substring(3)) > dayColors.current.length) column.hide = true;
    });
  }
  async function handleMarkSelected() {
    const multiSelect = mainGridRef.current.grid.getMultiSelect();
    if (multiSelect.length > 0) {
      stateOfViewRef.current = true;
      setDisabledMarkSelected(stateOfViewRef.current);
      for (const index of multiSelect) {
        const renderingID = await mainGridRef.current.grid.getActiveSource().getFieldValue("RenderingID", Number(index));
        const indexSelected = selectedRecordsRef.current.indexOf(renderingID);
        if (indexSelected === -1) selectedRecordsRef.current.push(renderingID);
      }
      setDisabledClearSelection(false);
      await resetSelection();
      await resetRenderings();
      await mainGridRef.current.grid.refreshSource(selectedRecordRenderingID);
    } else {
      onDoubleClickHandler(mainGridRef.current.querySelector(".grid-item-focused").closest(".grid-item"));
    }
  }
  async function handleClearSelection() {
    selectedRecordsRef.current = [];
    setDisabledClearSelection(true);
    if (stateOfViewRef.current) {
      stateOfViewRef.current = false;
      setDisabledMarkSelected(stateOfViewRef.current);
      await resetSelection();
      await resetRenderings();
      await mainGridRef.current.grid.refreshSource(selectedRecordRenderingID);
    } else {
      await mainGridRef.current.grid.updateGridSize();
    }
  }
  async function contextMenuHandler(data) {
    const command = data.value;
    if (command === "markSelected") {
      await handleMarkSelected();
    } else {
      await handleClearSelection();
    }
  }
  function refreshSource() {
    setTimeout(() => {
      mainGridRef.current.grid.refreshSource("!");
    }, 10);
  }
  function openTokenProcessingWindow(objType) {
    const json = {
      Token: "SelectObject",
      Params: { Module: "tables", OnlyView: "1", ObjType: objType },
      Break: false
    };
    tokenProcessingTest(json);
  }
  const defaultButton = /* @__PURE__ */ jsxRuntimeExports.jsxs(Grid2, { style: { display: "flex" }, children: [
    selectedTabIndex === 0 && /* @__PURE__ */ jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(Grid2, { children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { title: "Окно структурных подразделений", arrow: true, enterDelay: 600, children: /* @__PURE__ */ jsxRuntimeExports.jsx(IconButton, { onClick: handleColapseTree, children: ImgURL(getIcons(35)) }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { title: "Ввод отвлечений", arrow: true, enterDelay: 600, children: /* @__PURE__ */ jsxRuntimeExports.jsx(IconButton, { onClick: handleColapseLeaves, children: ImgURL(getIcons(5)) }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { title: "Панель поиска", arrow: true, enterDelay: 600, children: /* @__PURE__ */ jsxRuntimeExports.jsx(IconButton, { onClick: handleColapseSearch, children: ImgURL(getIcons(12)) }) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { title: "Показать только отмеченных", arrow: true, enterDelay: 600, children: /* @__PURE__ */ jsxRuntimeExports.jsx(IconButton, { disabled: disabledClearSelection, onClick: handleOnlySelected, children: ImgURL(getIcons(22)) }) })
      ] }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Divider, { orientation: "vertical", flexItem: true })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsxs(Grid2, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { title: "Виды учета рабочего времени", arrow: true, enterDelay: 600, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        IconButton,
        {
          onClick: () => {
            openTokenProcessingWindow(ObjType.HourType);
          },
          children: ImgURL(getIcons(167))
        }
      ) }),
      /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { title: "Отклонения от рабочего графика", arrow: true, enterDelay: 600, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
        IconButton,
        {
          onClick: () => {
            openTokenProcessingWindow(ObjType.Absence);
          },
          children: ImgURL(getIcons(5))
        }
      ) })
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Divider, { orientation: "vertical", flexItem: true })
  ] });
  const onTabReClick = async (index) => {
    var _a;
    if (index !== 1 || staffSettings.WithOutDocs === "1") return;
    (_a = setDocsTabIndex.current) == null ? void 0 : _a.call(setDocsTabIndex);
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    Grid2,
    {
      style: { height: "100%" },
      container: true,
      direction: "column",
      justifyContent: "flex-start",
      alignItems: "flex-start",
      flexWrap: "nowrap",
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(SectionToolsJS, { ID: props.sectionId, defaultButton }),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          SmetaTabs,
          {
            style: { height: "100%", width: "100%" },
            onTabIndexChange: handleTabChange,
            tabIndex: selectedTabIndex,
            onTabReClick,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaTabItem, { label: "Учет рабочего времени", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Grid2, { container: true, style: { height: "100%", flexDirection: "column" }, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                "div",
                {
                  style: {
                    display: "flex",
                    flexDirection: "column",
                    width: "100%",
                    flex: "1 1"
                  },
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                      "div",
                      {
                        style: {
                          visibility: collapsedSearch ? "hidden" : "visible",
                          display: collapsedSearch ? "none" : ""
                        },
                        children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                          SearchPersons,
                          {
                            module: Prefixes.salary,
                            orientation: "vertical",
                            sectionId: props.sectionId,
                            objType: ObjType.Rendering,
                            colapseSearch: handleColapseSearch,
                            selectedPeriod: monthYearSelected,
                            onSelect: setSearchResult
                          }
                        )
                      }
                    ),
                    /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      SplitterLocal,
                      {
                        collapsed: collapsedTree,
                        orientation: "vertical",
                        onCollapse: handleColapseTree,
                        onExpand: handleColapseTree,
                        onResizeEnd: updateSizeForGrid,
                        sizeSecondary: "20%",
                        primaryIndex: 1,
                        transitionDuration: 250,
                        children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx(Grid2, { children: tree }),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs(
                            "div",
                            {
                              style: {
                                display: "flex",
                                flexDirection: "column"
                              },
                              children: [
                                /* @__PURE__ */ jsxRuntimeExports.jsx(MonthYearPicker, { onChange: handlePeriodChange, value: monthYearSelected }),
                                /* @__PURE__ */ jsxRuntimeExports.jsx(
                                  Grid2,
                                  {
                                    className: cn("backgroundColorStimate", {
                                      light: theme === "light"
                                    }),
                                    style: {
                                      display: "flex",
                                      width: "calc(100% - 1px)"
                                    },
                                    children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                                      Box,
                                      {
                                        display: "flex",
                                        alignItems: "center",
                                        justifyContent: "space-between",
                                        overflow: "hidden",
                                        width: "100%",
                                        children: [
                                          /* @__PURE__ */ jsxRuntimeExports.jsxs(
                                            Grid2,
                                            {
                                              style: {
                                                display: "inherit",
                                                marginLeft: "5px"
                                              },
                                              children: [
                                                /* @__PURE__ */ jsxRuntimeExports.jsx(
                                                  Link,
                                                  {
                                                    component: "button",
                                                    style: { height: "fit-content", alignSelf: "center" },
                                                    underline: "hover",
                                                    onClick: async () => {
                                                      setTimeModeDay(!timeModeDay);
                                                      changeDayColumns(timeModeDay);
                                                      setTimeout(async () => {
                                                        await mainGridRef.current.grid.source.refresh();
                                                        await mainGridRef.current.grid.refreshSource("!");
                                                      }, 10);
                                                    },
                                                    children: timeModeDay ? "Ежедневный учет" : "Ежемесячный учет"
                                                  }
                                                ),
                                                timeModeDay && /* @__PURE__ */ jsxRuntimeExports.jsx(
                                                  FormControl,
                                                  {
                                                    style: {
                                                      marginLeft: "10px"
                                                    },
                                                    children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                                                      RadioGroup,
                                                      {
                                                        row: true,
                                                        sx: { height: "38px", overflow: "auto" },
                                                        value: normType,
                                                        onChange: (ev) => {
                                                          setNormType(Number(ev.target.value));
                                                          refreshSource();
                                                        },
                                                        children: [
                                                          /* @__PURE__ */ jsxRuntimeExports.jsx(FormControlLabel, { value: NormMode.Days, control: /* @__PURE__ */ jsxRuntimeExports.jsx(Radio, { size: "small" }), label: "Дни" }),
                                                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                                                            FormControlLabel,
                                                            {
                                                              value: NormMode.Hours,
                                                              control: /* @__PURE__ */ jsxRuntimeExports.jsx(Radio, { size: "small" }),
                                                              label: "Часы"
                                                            }
                                                          ),
                                                          /* @__PURE__ */ jsxRuntimeExports.jsx(FormControlLabel, { value: NormMode.Units, control: /* @__PURE__ */ jsxRuntimeExports.jsx(Radio, { size: "small" }), label: "УЕТ" })
                                                        ]
                                                      }
                                                    )
                                                  }
                                                ),
                                                timeModeDay && normType === NormMode.Hours && /* @__PURE__ */ jsxRuntimeExports.jsxs(FormControl, { style: { display: "flex", flexDirection: "row" }, children: [
                                                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                                                    FormControlLabel,
                                                    {
                                                      checked: allHoursType,
                                                      onChange: () => {
                                                        setAllHoursType(!allHoursType);
                                                        refreshSource();
                                                      },
                                                      control: /* @__PURE__ */ jsxRuntimeExports.jsx(Checkbox, { size: "small" }),
                                                      label: "Все"
                                                    }
                                                  ),
                                                  /* @__PURE__ */ jsxRuntimeExports.jsxs(
                                                    RadioGroup,
                                                    {
                                                      row: true,
                                                      sx: { height: "38px", overflow: "auto" },
                                                      value: hoursType,
                                                      onChange: (ev) => {
                                                        setHoursType(Number(ev.target.value));
                                                        refreshSource();
                                                      },
                                                      children: [
                                                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                                                          FormControlLabel,
                                                          {
                                                            disabled: allHoursType,
                                                            value: HourMask.Day,
                                                            control: /* @__PURE__ */ jsxRuntimeExports.jsx(Radio, { size: "small" }),
                                                            label: "Дневные"
                                                          }
                                                        ),
                                                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                                                          FormControlLabel,
                                                          {
                                                            disabled: allHoursType,
                                                            value: HourMask.Evening,
                                                            control: /* @__PURE__ */ jsxRuntimeExports.jsx(Radio, { size: "small" }),
                                                            label: "Вечерние"
                                                          }
                                                        ),
                                                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                                                          FormControlLabel,
                                                          {
                                                            disabled: allHoursType,
                                                            value: HourMask.Night,
                                                            control: /* @__PURE__ */ jsxRuntimeExports.jsx(Radio, { size: "small" }),
                                                            label: "Ночные"
                                                          }
                                                        )
                                                      ]
                                                    }
                                                  )
                                                ] }),
                                                timeModeDay && normType === NormMode.Units && /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { style: { alignItems: "center", display: "flex" }, children: [
                                                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: "Вид учета операций:" }),
                                                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                                                    "div",
                                                    {
                                                      style: {
                                                        marginLeft: "1px",
                                                        marginRight: "5px",
                                                        border: "1px solid grey"
                                                      },
                                                      children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                                                        Editor,
                                                        {
                                                          value: selectedTimeCfg.text,
                                                          editStyle: EditStyle.PickList,
                                                          onDropDownList,
                                                          onEdit: (ev) => {
                                                            if (ev.tag) {
                                                              setSelectedTimeCfg({
                                                                id: ev.tag,
                                                                text: ev.value
                                                              });
                                                              refreshSource();
                                                            } else if (!ev.tag && !ev.value) {
                                                              setSelectedTimeCfg({ id: "", text: "" });
                                                              refreshSource();
                                                            }
                                                          }
                                                        }
                                                      )
                                                    }
                                                  )
                                                ] })
                                              ]
                                            }
                                          ),
                                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                                            FormControlLabel,
                                            {
                                              disabled: !enableTimeTableClosed,
                                              control: /* @__PURE__ */ jsxRuntimeExports.jsx(
                                                Checkbox,
                                                {
                                                  checked: timeTableClosed,
                                                  onChange: () => {
                                                    setTimeTableClosed(!timeTableClosed);
                                                    const params = /* @__PURE__ */ new Map();
                                                    params.set("prefix", "tables").set("comand", "CloseRange").set("Year", monthYearSelected.year).set("Month", monthYearSelected.month).set("Value", Number(!timeTableClosed));
                                                    AxiosRequest(true, params);
                                                  },
                                                  size: "small"
                                                }
                                              ),
                                              label: "Табель закрыт"
                                            }
                                          )
                                        ]
                                      }
                                    )
                                  }
                                ),
                                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                                  SplitterLocal,
                                  {
                                    collapsed: collapsedLeaves,
                                    orientation: "horizontal",
                                    primaryIndex: 0,
                                    sizeSecondary: "40%",
                                    style: { width: "calc(100% - 5px)" },
                                    onCollapse: handleColapseLeaves,
                                    onExpand: handleColapseLeaves,
                                    onResizeEnd: updateSizeForGrid,
                                    transitionDuration: 250,
                                    children: [
                                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                                        ContextMenu,
                                        {
                                          for: "grid",
                                          data: {
                                            Table: [
                                              {
                                                Caption: "Отметить выбранных",
                                                value: "markSelected",
                                                Disabled: disabledMarkSelected
                                              },
                                              {
                                                Caption: "Снять всю отметку",
                                                value: "clearSelection",
                                                Disabled: disabledClearSelection
                                              },
                                              { Caption: "Divider" }
                                            ]
                                          },
                                          onMenuItemClick: contextMenuHandler,
                                          id: props.sectionId,
                                          children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                                            "div",
                                            {
                                              id: "gridpanel" + props.sectionId,
                                              ref: mainGridRef,
                                              tabIndex: 0,
                                              style: {
                                                height: "100%",
                                                width: "100%"
                                              },
                                              rcsgrid_panel: "",
                                              onDoubleClick: (ev) => {
                                                if (mainGridRef.current.grid.source.recordCount) {
                                                  const target = ev.target;
                                                  const table = target.closest(".grid-item");
                                                  const columnFocused = target.closest(".grid-item-focused");
                                                  let canModify2 = false;
                                                  if (columnFocused == null ? void 0 : columnFocused.field)
                                                    canModify2 = mainGridRef.current.grid.canModify(
                                                      mfEdit,
                                                      columnFocused.field,
                                                      mainGridRef.current.grid
                                                    );
                                                  if (table && !canModify2) {
                                                    onDoubleClickHandler(table);
                                                  }
                                                }
                                              }
                                            }
                                          )
                                        }
                                      ),
                                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                                        Leaves,
                                        {
                                          noRefs: true,
                                          SectionID: props.sectionId,
                                          GroupID: selectedRecordRenderingID,
                                          Date: monthYearSelected,
                                          Full: "0",
                                          open: !collapsedLeaves,
                                          CLSID: props.CLSID
                                        }
                                      )
                                    ]
                                  }
                                )
                              ]
                            }
                          )
                        ]
                      }
                    )
                  ]
                }
              ) }) }),
              staffSettings.WithOutDocs !== "1" && /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaTabItem, { label: "Документы", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                SectionDocumentsChose,
                {
                  id: props.sectionId,
                  sectionTools: false,
                  setParentFunc: (func) => {
                    setDocsTabIndex.current = func;
                  }
                }
              ) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaTabItem, { label: "Отчёты", children: /* @__PURE__ */ jsxRuntimeExports.jsx(SectionReports, { CLSID: props.CLSID, id: props.sectionId }) })
            ]
          }
        )
      ]
    }
  );
}
export {
  SectionTimeTable as default
};
//# sourceMappingURL=SectionTimeTable-C6g_ZqO6.js.map
