import { r as reactExports, aM as checkCurrentUserRights, j as jsxRuntimeExports, x as Grid2, T as Tooltip, I as IconButton, bR as ImgURL, bS as getIcons, ct as Divider, b4 as updateGridData, aN as ObjType, bv as EditStyle, b3 as getDateOfInt, ae as getRightsData, bg as smetaAxios, bf as Prefixes, a6 as GridLoader, bG as SmetaTabs, bH as SmetaTabItem, bd as CheckBoxMultiCheck, c9 as SmetaSplitter, ca as SmetaSplitterItem, aU as ContextMenu, bw as PostAddIcon, bx as DeleteIcon, b2 as defaultFieldInfo, bz as setParamObjectText, cu as getParamObjectText, ac as tokenProcessingTest, ap as smetaModals, aE as ViewClass, ar as getStyleWindow, c6 as getMonthInfo, cv as PayTypeOption, cw as ParamSetOption, ah as AxiosRequest, u as useAtomValue, cx as isAdminAtom, cy as createRecordSource, cz as parseGridState, cA as createGrid, b1 as getParamColumnsOptions, b0 as createGridStateString, z as currentTheme, E as useAtom, b7 as selectedSectionAtom, ck as useSetAtom, br as renderingIdAtom, cB as groupIdAtom, cC as leavesOpenAtom, bi as salaryRangeAtom, bM as SectionToolsJS, ax as SplitterLocal, bC as ButtonsForGridComponent, B as Button, ao as cn, cD as Menu, cE as MenuItems, cr as Link, cF as getRendHistoryParams, c8 as FooterDataShow, a3 as Tree, v as renderMessageBox, aT as DlgType, cG as DlgRes, aS as Button$1, cH as HandleTable, aD as getModalSectionID, as as dayjs } from "./index-D15x63tD.js";
import { M as MonthYearPicker } from "./MonthYearPicker-CnPllbI6.js";
import { S as SearchPersons } from "./SearchPersons-C1hfxGSb.js";
import SectionDocumentsChose from "./SectionDocumentsChose-CWNMUy0u.js";
import SectionReports from "./SectionReports-CR4VT6wR.js";
import { l as listMonth, a as listSource, A as Amounts, b as listType, g as getAmountStr, c as getShortName, r as recordKeysBaseSum, d as defaultFieldsBaseSum, J as JobHistoryList } from "./Amounts-D9Fd5gdh.js";
import { L as Leaves } from "./Leaves-BvV0zspE.js";
import DialogDocTabs from "./DialogDocTabs-ExyRNCmU.js";
import { L as LocalParams } from "./LocalParams-Dz-ktk1o.js";
import "./DialogDoc-BCKCegu0.js";
const SalaryButtons = (props) => {
  const [disabledButtonRanges, setDisabledButtonRanges] = reactExports.useState(false);
  reactExports.useEffect(() => {
    if (props.withOutRanges && props.rangeObjType) {
      checkCurrentUserRights(props.rangeObjType, 1, true).then((canModify) => {
        setDisabledButtonRanges(!canModify);
      });
    }
  }, [props.withOutRanges, props.rangeObjType]);
  const buttonsArr = [
    { tooltipText: "Окно структурных подразделений", image: "35", onClick: "handleCollapseTree" },
    {
      tooltipText: props.withOutRanges ? "Открыть (закрыть) месяц" : "График расчётов",
      image: props.withOutRanges ? "4" : "23",
      onClick: "openChartOfCalculations",
      disabled: disabledButtonRanges,
      checked: props.withOutRanges ? !props.canModifyRange : false
    },
    { tooltipText: "Ввод отвлечений", image: "5", onClick: "openLeaves" },
    { tooltipText: "Поиск сотрудников", image: "87", onClick: "handleCollapseSearch" },
    { path: "divider" },
    { tooltipText: "Тарификация", image: "162", onClick: "handleInputTariffication" },
    { path: "divider" }
  ];
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    Grid2,
    {
      container: true,
      direction: "row",
      sx: {
        justifyContent: "flex-start",
        alignItems: "center"
      },
      style: { marginLeft: "5px", marginRight: "1px" },
      children: buttonsArr.map((item, index) => {
        if (item.path !== "divider") {
          const imgStyle = { border: "1px solid", borderColor: `rgba(0, 0, 0, ${item.checked ? "0.54" : "0"})` };
          return /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { title: item.tooltipText, arrow: true, enterDelay: 600, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
            IconButton,
            {
              disabled: item.disabled,
              onClick: () => {
                props.onClick({ value: item.onClick });
              },
              children: ImgURL(getIcons(item.image), imgStyle)
            }
          ) }, "salaryDivider" + index);
        }
        {
          return /* @__PURE__ */ jsxRuntimeExports.jsx(Divider, { orientation: "vertical", flexItem: true }, "salaryDivider" + index);
        }
      })
    }
  );
};
function BaseSum(props) {
  const [actual, setActual] = reactExports.useState(true);
  const records = reactExports.useRef([]);
  const baseSumParams = reactExports.useRef({
    renderingID: props.renderingId,
    selectedPeriods: props.selectedPeriods,
    actual: true,
    payTypeSet: props.payTypeSet,
    isGridReady: false
  });
  const modesList = reactExports.useRef([]);
  const [selectedRecordId, setSelectedRecordId] = reactExports.useState("");
  const [paramsData, setParamsData] = reactExports.useState({
    Items: []
  });
  const gridPanel = reactExports.useRef(null);
  const [isGridReady, setIsGridReady] = reactExports.useState(false);
  const [tabIndex, setTabIndex] = reactExports.useState(0);
  const standardParams = ["Time", "Type", "Mode", "Norm", "Month", "Source", "Links", "ObjRef"];
  reactExports.useEffect(() => {
    if (props.isHistoryInput) {
      setTabIndex(1);
    } else {
      setTabIndex(0);
      if (isGridReady) getRendBaseSums(false);
    }
  }, [props.isHistoryInput]);
  reactExports.useEffect(() => {
    updateGridData(0);
  }, [tabIndex]);
  reactExports.useEffect(() => {
    mainGridLoader();
  }, []);
  reactExports.useEffect(() => {
    var _a;
    const changeTab = baseSumParams.current.renderingID !== props.renderingId || baseSumParams.current.selectedPeriods !== props.selectedPeriods || baseSumParams.current.actual !== actual || baseSumParams.current.isGridReady !== isGridReady;
    baseSumParams.current = {
      actual,
      renderingID: props.renderingId,
      selectedPeriods: props.selectedPeriods,
      payTypeSet: props.payTypeSet,
      isGridReady
    };
    if (isGridReady) {
      if (props.selectedPeriods && props.renderingId) {
        getRendBaseSums(changeTab);
      } else {
        (_a = props.setIsHistoryInput) == null ? void 0 : _a.call(props, true);
        updateRecord({ Modes: { items: [] } });
      }
    }
  }, [props.renderingId, props.selectedPeriods, actual, isGridReady]);
  reactExports.useEffect(() => {
    if (selectedRecordId) {
      const selectRecord = records.current.find((record) => record.ID === selectedRecordId);
      setParamsData({ Items: getParamsItems(selectRecord || {}) });
    } else setParamsData({ Items: getParamsItems() });
  }, [selectedRecordId]);
  function getParamsItems(selectRecord = {}) {
    var _a, _b, _c, _d, _e;
    const paramsItems = [];
    paramsItems.push({
      FieldName: "Time",
      Name: "Рабочее время",
      Value: selectRecord.TimeName,
      EditStyle: EditStyle.PickList + EditStyle.Ellipsis,
      Module: "tables",
      ObjType: ObjType.HourType
    });
    paramsItems.push({
      FieldName: "Type",
      Name: "Вид учета",
      Value: selectRecord.Type,
      EditStyle: EditStyle.PickList,
      Level: 1
    });
    paramsItems.push({
      FieldName: "Mode",
      Name: "График нормы",
      Value: selectRecord.ModeName,
      EditStyle: EditStyle.PickList,
      Module: "schedule",
      ObjType: ObjType.WorkMode,
      Level: 1
    });
    paramsItems.push({
      FieldName: "Norm",
      Name: "Значение нормы",
      Value: selectRecord.Norm,
      Level: 1
    });
    paramsItems.push({
      FieldName: "Month",
      Name: "Месяц учета",
      Value: ((_a = listMonth.find((month) => month.id === selectRecord.Month)) == null ? void 0 : _a.label) || "Текущий",
      EditStyle: EditStyle.PickList,
      Level: 1
    });
    paramsItems.push({
      FieldName: "Source",
      Name: "Базовая сумма",
      Value: ((_b = listSource.find((source) => source.id === selectRecord.Source)) == null ? void 0 : _b.label) || "По текущим",
      EditStyle: EditStyle.PickList
    });
    if (selectRecord.Source) {
      const name = { "1": "Сотрудник", "2": "Должность", "3": "Фиксированная" };
      const editStyle = {
        "1": EditStyle.PickList + EditStyle.Ellipsis,
        "2": EditStyle.PickList + EditStyle.Ellipsis,
        "3": 0
      };
      const module = {
        "1": "staff",
        "2": "staff",
        "3": "programs"
      };
      const objType = {
        "1": ObjType.Rendering,
        "2": ObjType.Appointment,
        "3": 0
      };
      paramsItems.push({
        FieldName: "ObjRef",
        Name: name[selectRecord.Source],
        Module: module[selectRecord.Source],
        ObjType: objType[selectRecord.Source],
        Value: selectRecord.Object,
        EditStyle: editStyle[selectRecord.Source],
        Level: 1
      });
    }
    paramsItems.push({ FieldName: "Links", Name: "Сумма начислений", Value: selectRecord.Base, Level: 1, Locked: "1" });
    if (selectRecord.Links) {
      (_c = selectRecord.Links.items) == null ? void 0 : _c.forEach((link) => {
        paramsItems.push({
          FieldName: link.ID,
          Name: link.Name,
          EditStyle: EditStyle.Check,
          CheckState: link.Type,
          Value: link.Value,
          Level: 2,
          Locked: "1"
        });
      });
    }
    (_e = (_d = selectRecord.Params) == null ? void 0 : _d.items) == null ? void 0 : _e.forEach((item) => {
      paramsItems.push(item);
    });
    return paramsItems;
  }
  async function updateRecord(json) {
    var _a, _b;
    modesList.current = [];
    json.Modes.items.forEach((item) => {
      var _a2;
      modesList.current.push({
        id: ((_a2 = item.$tag) == null ? void 0 : _a2.toString()) || "0",
        label: item.ShortCut ? `${item.Name} (${item.ShortCut})` : item.Name
      });
    });
    records.current = [];
    if ((_a = json.Items) == null ? void 0 : _a.items) {
      (_b = json.Items) == null ? void 0 : _b.items.forEach((item, index) => {
        var _a2;
        records.current.push(item);
        records.current[index].FirstDate = item.FirstDate !== "0" ? {
          text: getDateOfInt(item.FirstDate),
          id: item.FirstDate
        } : "";
        records.current[index].LastDate = item.LastDate !== "0" ? {
          text: getDateOfInt(item.LastDate),
          id: item.LastDate
        } : "";
        if (item.Amount) {
          records.current[index].AmountText = `${item.Value} ${item.Amount}`;
        } else records.current[index].AmountText = records.current[index].Value;
        (_a2 = item.Params.items) == null ? void 0 : _a2.forEach((item2) => {
          item2.FieldName = item2.Name;
          item2.Name = item2.Title;
          item2.Value = item2.Text;
        });
      });
    }
    const recordSource = gridPanel.current.grid.getActiveSource();
    recordSource.rights = getRightsData(json.Rights || "-1");
    await gridPanel.current.grid.refreshSource("!");
    setSelectedRecordId(await recordSource.getFieldText("ID"));
  }
  async function getRendBaseSums(сhangeTab) {
    var _a, _b, _c, _d, _e;
    const json = await smetaAxios.get("GetRendBaseSums", {
      prefix: Prefixes.amount,
      params: {
        RenderingID: baseSumParams.current.renderingID || "0",
        Year: (_a = baseSumParams.current.selectedPeriods) == null ? void 0 : _a.year,
        Month: (_b = baseSumParams.current.selectedPeriods) == null ? void 0 : _b.month,
        All: baseSumParams.current.actual ? "0" : "1"
      },
      loadMask: true
    });
    const emptyRecords = !(((_c = json.Items) == null ? void 0 : _c.items) && json.Items.items.length > 0);
    if (emptyRecords && сhangeTab) {
      (_d = props.setIsHistoryInput) == null ? void 0 : _d.call(props, true);
    } else if (!emptyRecords && сhangeTab) (_e = props.setIsHistoryInput) == null ? void 0 : _e.call(props, false);
    updateRecord(json);
  }
  const togglePayTypeFilter = async (clearFilter) => {
    const params = /* @__PURE__ */ new Map();
    if (clearFilter) {
      params.set("Clear", "1");
    } else {
      params.set("ObjType", baseSumParams.current.payTypeSet || ObjType.PayType).set("Include", PayTypeOption.Constant).set("Exclude", PayTypeOption.Unused);
    }
    return smetaAxios.get("SetPayTypeFilter", {
      prefix: Prefixes.paytype,
      params: Object.fromEntries(params),
      loadMask: true
    });
  };
  const amountsPayTypeDropDownList = async () => {
    await togglePayTypeFilter(false);
    const json = await smetaAxios.get("GetObjectValues", {
      prefix: Prefixes.paytype,
      params: { ObjType: baseSumParams.current.payTypeSet || ObjType.PayType },
      loadMask: true
    });
    await togglePayTypeFilter(true);
    return Object.values(json.Items).map((item) => {
      return { label: item.text, id: item.id };
    });
  };
  const amountsPayTypeEditButtonClick = async () => {
    await togglePayTypeFilter(false);
    const recordSource = gridPanel.current.grid.getActiveSource();
    const json = await smetaAxios.get("GetDialogParams", {
      prefix: Prefixes.paytype,
      params: {
        ObjType: baseSumParams.current.payTypeSet || ObjType.PayType,
        ObjRef: recordSource.getFieldTextSync("PayType") || "0"
      },
      loadMask: true
    });
    json.Break = "";
    json.Token = "HandleTable";
    tokenProcessingTest(json, {
      props: {
        Module: "paytypes",
        SectionID: props.sectionId,
        ObjType: baseSumParams.current.payTypeSet || ObjType.PayType,
        UsedDate: "0",
        Info: "0",
        ObjRef: recordSource.getFieldTextSync("PayType") || "0",
        onEdit: async (editData) => {
          await togglePayTypeFilter(true);
          if (records.current.length === 0) {
            await recordSource.appendRecord();
          }
          const request = {
            NewRecord: recordSource.getState() === 3 ? "1" : void 0,
            RecordIndex: recordSource.activeRecord,
            RecordSet: {
              Attributes: ["PayType"]
            }
          };
          const requestData = [{ id: editData.tag }];
          onPostRecord(request, requestData);
        },
        setValue: true,
        setInputValue: true,
        onClose: () => togglePayTypeFilter(true)
      }
    });
  };
  const amountsDocumentEditButtonClick = async () => {
    const recordSource = gridPanel.current.grid.getActiveSource();
    const json = await smetaAxios.get("GetAmountDocTypes", {
      prefix: Prefixes.amount,
      params: {
        PayType: recordSource.getFieldTextSync("PayType") || "0",
        RenderingID: baseSumParams.current.renderingID
      },
      loadMask: true
    });
    const selectDocument = [];
    Object.values(json.Types).forEach((item) => {
      selectDocument.push({ DocCfgID: item.id, Name: item.text });
    });
    smetaModals.open(
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        DialogDocTabs,
        {
          props: {
            CLSID: ViewClass.DocSite,
            SelectDocument: selectDocument,
            NewModalWindow: true,
            onEdit: async (values) => {
              if (records.current.length === 0) {
                await recordSource.appendRecord();
              }
              const request = {
                NewRecord: recordSource.getState() === 3 ? "1" : void 0,
                RecordIndex: recordSource.activeRecord,
                RecordSet: {
                  Attributes: ["DocID"]
                }
              };
              const requestData = [{ id: values.tag }];
              onPostRecord(request, requestData);
            }
          }
        }
      ),
      {
        hiddenButton: true,
        blockSaveLocation: true,
        style: getStyleWindow(ViewClass.DocSite),
        setFocus: true
      }
    );
  };
  const getFieldText = async (request) => {
    var _a, _b, _c;
    if (gridPanel.current.grid.getActiveSource().getState() === 3) {
      if (request.FieldName === "FirstDate")
        return {
          Text: getMonthInfo((_a = baseSumParams.current.selectedPeriods) == null ? void 0 : _a.year, (_b = baseSumParams.current.selectedPeriods) == null ? void 0 : _b.month).firstDayStr
        };
      return { Text: "" };
    }
    if (records.current.length) {
      const val = request.FieldName === "AmountText" ? "Value" : request.FieldName;
      return { Text: ((_c = records.current[request.RecordIndex][val]) == null ? void 0 : _c.text) || records.current[request.RecordIndex][val] };
    }
    return { Text: "" };
  };
  const canModify = (flag, column, grid) => {
    const mfDelete = 2;
    if (!baseSumParams.current.renderingID || baseSumParams.current.renderingID === "0") return false;
    if (records.current.length === 0 && flag === mfDelete) return false;
    if (grid.localCanModify(flag, column, grid)) {
      return checkCurrentUserRights(ObjType.BaseValue, flag);
    }
    return false;
  };
  const onPostRecord = async (request, requestData) => {
    var _a, _b, _c, _d, _e, _f;
    if (request.NewRecord === "1") {
      const monthInfo = getMonthInfo(
        (_a = baseSumParams.current.selectedPeriods) == null ? void 0 : _a.year,
        (_b = baseSumParams.current.selectedPeriods) == null ? void 0 : _b.month
      );
      const newRecord = {
        FirstDate: { text: monthInfo.firstDayStr, id: monthInfo.firstDayInt }
      };
      records.current.splice(request.RecordIndex, 0, newRecord);
    }
    const record = records.current[request.RecordIndex];
    const postData = {
      ID: record.ID,
      PayType: record.PayType,
      FirstDate: (_c = record.FirstDate) == null ? void 0 : _c.id,
      LastDate: (_d = record.LastDate) == null ? void 0 : _d.id,
      Value: record.Value,
      DocID: record.DocID,
      Time: record.Time,
      Mode: record.Mode,
      Norm: record.Norm,
      Type: record.Type,
      Month: record.Month,
      Source: record.Source,
      ObjRef: record.ObjRef,
      Object: record.Object,
      Status: request.NewRecord === "1" ? "2" : "4"
    };
    request.RecordSet.Attributes.forEach((attribute, index) => {
      let attributeName, value;
      switch (attribute) {
        case "Name":
          attributeName = "PayType";
          value = requestData[index].id;
          break;
        case "AmountText":
          attributeName = "Value";
          if (requestData[index].id) {
            value = `${getAmountStr(record.Value || "")} ${getShortName(requestData[index].text)}`;
          } else value = requestData[index].text;
          break;
        case "DocIDName":
          if (requestData[index]) return;
          attributeName = "DocID";
          value = void 0;
          break;
        default:
          attributeName = attribute;
          value = requestData[index].id;
          break;
      }
      postData[attributeName] = value;
    });
    await updateRecord(
      await smetaAxios.post(
        "SetRendBaseSums",
        { Item: postData },
        {
          prefix: Prefixes.amount,
          params: {
            RenderingID: baseSumParams.current.renderingID,
            Year: (_e = baseSumParams.current.selectedPeriods) == null ? void 0 : _e.year,
            Month: (_f = baseSumParams.current.selectedPeriods) == null ? void 0 : _f.month,
            All: baseSumParams.current.actual ? "0" : "1"
          },
          loadMask: true
        }
      )
    );
  };
  const deleteRecord = async (request) => {
    var _a, _b;
    const postData = { Item: { ID: request.RecordKey, Status: "8" } };
    await updateRecord(
      await smetaAxios.post("SetRendBaseSums", postData, {
        prefix: Prefixes.amount,
        params: {
          RenderingID: baseSumParams.current.renderingID,
          Year: (_a = baseSumParams.current.selectedPeriods) == null ? void 0 : _a.year,
          Month: (_b = baseSumParams.current.selectedPeriods) == null ? void 0 : _b.month,
          All: baseSumParams.current.actual ? "0" : "1"
        },
        loadMask: true
      })
    );
  };
  const createRecord = () => {
    var _a, _b;
    const index = records.current.length ? gridPanel.current.grid.getActiveSource().activeRecord + 1 : 0;
    const newRecords = [...records.current];
    const monthInfo = getMonthInfo(
      (_a = baseSumParams.current.selectedPeriods) == null ? void 0 : _a.year,
      (_b = baseSumParams.current.selectedPeriods) == null ? void 0 : _b.month
    );
    const newRecord = {
      FirstDate: { text: monthInfo.firstDayStr, id: monthInfo.firstDayInt }
    };
    newRecords.splice(index, 0, newRecord);
    return {
      index,
      records: newRecords,
      keys: ["FirstDate", "Month"],
      titleKey: ""
    };
  };
  const getColumns = () => {
    return {
      title: [
        {
          fieldName: "Name",
          title: "Вид оплаты",
          width: 200,
          onDropDownList: amountsPayTypeDropDownList,
          onEditButtonClick: amountsPayTypeEditButtonClick,
          fieldInfo: {
            ...defaultFieldInfo,
            EditStyle: EditStyle.PickList + EditStyle.Ellipsis,
            Module: "paytypes",
            DataType: ObjType.PayType,
            titleAjust: "0"
          }
        },
        {
          fieldName: "FirstDate",
          title: "Начало",
          width: 90,
          fieldInfo: {
            ...defaultFieldInfo,
            EditStyle: EditStyle.Calendar,
            titleAjust: "0",
            textAjust: "1"
          }
        },
        {
          fieldName: "AmountText",
          title: "Значение",
          width: 90,
          onDropDownList: () => modesList.current,
          fieldInfo: {
            ...defaultFieldInfo,
            EditStyle: EditStyle.PickList,
            titleAjust: "0",
            textAjust: "0"
          }
        },
        {
          fieldName: "LastDate",
          title: "Конец",
          width: 90,
          fieldInfo: {
            ...defaultFieldInfo,
            EditStyle: EditStyle.Calendar,
            titleAjust: "0",
            textAjust: "1"
          }
        },
        {
          fieldName: "DocIDName",
          title: "Документ (приказ)",
          width: 200,
          onEditButtonClick: amountsDocumentEditButtonClick,
          fieldInfo: {
            ...defaultFieldInfo,
            EditStyle: EditStyle.Ellipsis,
            titleAjust: "0"
          }
        }
      ]
    };
  };
  const changeGridStyles = async (table) => {
    if (table.classList[0] === "grid-item") {
      const record = records.current[table.recordIndex] || {};
      if (record.OutOfDate === "1") table.style.textDecoration = "line-through";
    }
  };
  async function mainGridLoader() {
    const res = await GridLoader(
      gridPanel.current,
      {},
      {
        localGrid: true,
        Columns: getColumns(),
        defaultFields: defaultFieldsBaseSum,
        keyField: "ID",
        recordKeys: recordKeysBaseSum,
        titleKey: "",
        getFieldText,
        canModify,
        onPostRecord,
        deleteRecord,
        createRecord,
        changeGridStyles,
        getRecords: () => records.current
      }
    );
    if (res) {
      res.source.onRecordIndexChanged = (source) => {
        setSelectedRecordId(source.getFieldTextSync("ID"));
      };
    }
    setIsGridReady(true);
  }
  const getObjectValues = async (fieldName) => {
    const fieldParams = paramsData.Items.find((item) => item.FieldName === fieldName);
    if (fieldParams == null ? void 0 : fieldParams.Module) {
      const json = await smetaAxios.get("GetObjectValues", {
        prefix: fieldParams.Module,
        params: { ObjType: fieldParams.ObjType },
        loadMask: true
      });
      return Object.values(json.Items).map((item) => {
        return { label: item.text, id: item.id };
      });
    }
  };
  const localParamsDropDownList = async (fieldName) => {
    const fieldHandlers = {
      Type: () => listType,
      Month: () => listMonth,
      Source: () => listSource,
      default: () => getObjectValues(fieldName)
    };
    const handler = fieldHandlers[fieldName] || fieldHandlers.default;
    return handler();
  };
  const handleApplyParams = async (data) => {
    const recordSource = gridPanel.current.grid.getActiveSource();
    if (standardParams.includes(data.fieldname)) {
      const requestData = [];
      if (data.fieldname === "Type" || data.fieldname === "Norm") {
        requestData.push({ text: data.value, id: data.value });
      } else requestData.push({ text: data.value, id: data.tag });
      const request = {
        NewRecord: recordSource.getState() === 3 ? "1" : void 0,
        RecordIndex: recordSource.activeRecord,
        RecordSet: {
          Attributes: [data.fieldname]
        }
      };
      onPostRecord(request, requestData);
    } else {
      let objRef = data.tag;
      if (data.textchanged === "1")
        objRef = data.value ? (await setParamObjectText(data.type, data.datatype, data.tag, data.value)).ObjRef : "0";
      await smetaAxios.get("ChangeAmountParam", {
        prefix: Prefixes.amount,
        params: {
          Name: data.fieldname,
          RenderingID: props.renderingId,
          ID: recordSource.getFieldTextSync("ID"),
          ObjRef: objRef
        },
        loadMask: true
      });
      const json = await getParamObjectText(data.type, data.datatype, objRef);
      const newParamsData = { ...paramsData, Items: [...paramsData.Items] };
      const index = newParamsData.Items.findIndex((obj) => obj.FieldName === data.fieldname);
      if (index !== -1) {
        newParamsData.Items[index].Text = json.Text;
        newParamsData.Items[index].EditVal = json.EditVal || json.Text;
      }
      setParamsData(newParamsData);
    }
  };
  const toggleActual = () => {
    setActual(!actual);
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(SmetaTabs, { tabIndex, position: "hidden", style: { height: "100%", width: "100%" }, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsxs(SmetaTabItem, { children: [
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        "div",
        {
          style: {
            height: "25px",
            background: "linear-gradient(to top, #cccccc, 30%, #f9f9f9)",
            border: "1px solid #cccccc"
          },
          children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { style: { display: "inline-flex", alignItems: "center", cursor: "pointer" }, onClick: toggleActual, children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(CheckBoxMultiCheck, { CheckState: actual, onEditCheckBox: toggleActual }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx("span", { style: { fontSize: "0.9rem" }, children: "Только действующие" })
          ] })
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        SmetaSplitter,
        {
          onResizeEnd: () => {
            gridPanel.current.grid.updateGridSize();
          },
          hideButtons: true,
          orientation: "vertical",
          style: { height: "calc(100% - 25px)" },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaSplitterItem, { size: "75%", children: /* @__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: "Сохранять отметку", Disabled: true }
                  ],
                  Header: [{ Caption: "Поиск по столбцу", value: "ColumnFilter" }]
                },
                children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { height: "100%", width: "100%", position: "relative" }, rcsgrid_panel: "", ref: gridPanel })
              }
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaSplitterItem, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              LocalParams,
              {
                onlyModified: true,
                NoTitle: true,
                data: paramsData,
                onDropDownList: localParamsDropDownList,
                onApply: handleApplyParams
              }
            ) })
          ]
        }
      )
    ] }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaTabItem, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
      Amounts,
      {
        sectionId: props.sectionId,
        renderingId: tabIndex === 1 ? props.renderingId : void 0,
        payTypeSet: props.payTypeSet,
        inputTariffication: props.inputTariffication
      }
    ) })
  ] });
}
const onDetailsByReq = async (data) => {
  const params = /* @__PURE__ */ new Map();
  params.set("prefix", "salary").set("comand", "GetObjectParamList").set("ObjType", "2640").set("ID", data.ID);
  const json = await AxiosRequest(true, params);
  if (json && json.Items && json.Items.items) {
    return {
      Items: json.Items.items,
      OnCloseUpListCustom: OnEditCustom,
      OnEditCustom,
      OnListCustom
    };
  }
};
const OnEditCustom = (data) => {
  const params = /* @__PURE__ */ new Map();
  params.set("prefix", "salary").set("comand", "SetObjectParamValue").set("ID", data.parentID).set("ObjType", "2586").set("Name", data.fieldname);
  if (data.CheckState !== void 0 || data.tag !== void 0) {
    params.set("ObjRef", data.CheckState || data.tag);
  } else params.set("ObjRef", "0");
  params.set("TextChanged", data.TextChanged);
  params.set("Text", data.Value);
  return AxiosRequest(true, params);
};
const OnListCustom = async (data) => {
  const params = /* @__PURE__ */ new Map();
  params.set("prefix", data.module).set("comand", "GetObjectValues").set("ObjType", data.datatype);
  const json = await AxiosRequest(true, params);
  if (json && json.Items) {
    return Object.values(json.Items).map((item, index) => {
      if (typeof item !== "object") {
        if (data.checklist) return { label: item, id: `${Math.pow(2, index)}` };
        return { label: item, id: `${index}` };
      }
      return { label: item.text, id: item.id };
    });
  }
};
const salaryIndividualDefaultFields = [
  {
    Name: "Начисление / удержание",
    FieldName: "PayTypeCode",
    Width: "150",
    Options: ParamSetOption.CanGroup + ParamSetOption.Filterable + ParamSetOption.Fixed + ParamSetOption.Sortable,
    DataType: "",
    EditStyle: 17,
    Module: "paytypes"
  },
  {
    Name: "Раздел",
    FieldName: "Day",
    Width: "120",
    Options: ParamSetOption.CanGroup + ParamSetOption.Filterable + ParamSetOption.Sortable,
    EditStyle: 17,
    onDropDownList: void 0
  },
  {
    Name: "Расчет",
    FieldName: "Number",
    Width: "110",
    Options: ParamSetOption.CanGroup + ParamSetOption.Filterable + ParamSetOption.Sortable + ParamSetOption.Hidden,
    EditStyle: 17,
    onDropDownList: void 0
  },
  {
    Name: "Мес. оплаты",
    FieldName: "Source",
    Width: "114",
    Options: ParamSetOption.CanGroup + ParamSetOption.Filterable + ParamSetOption.Sortable,
    EditStyle: 1,
    onDropDownList: void 0
  },
  {
    Name: "Сумма",
    FieldName: "Amount",
    Width: "50",
    Options: ParamSetOption.Sortable
  },
  {
    Name: "Документ (основание)",
    FieldName: "BaseDoc",
    Width: "182",
    Options: ParamSetOption.Reference + ParamSetOption.CanGroup + ParamSetOption.Filterable + ParamSetOption.Sortable,
    Module: "documents",
    DataType: "2200",
    EditStyle: 16
  },
  {
    Name: "Период",
    FieldName: "DayRange",
    Width: "95",
    Options: ParamSetOption.CanGroup + ParamSetOption.Filterable + ParamSetOption.Sortable
  },
  {
    Name: "Расчётные данные",
    FieldName: "Params",
    Width: "150",
    Module: "salary",
    EditStyle: 1,
    DataType: "2586",
    DetailsByReq: onDetailsByReq
  },
  {
    Name: "Группа",
    FieldName: "GroupCode",
    Width: "100",
    Options: ParamSetOption.CanGroup + ParamSetOption.Filterable + ParamSetOption.Sortable,
    EditStyle: 17,
    Module: "paytypes",
    DataType: "2380"
  },
  {
    Name: "Платежная ведомость",
    FieldName: "PaySheet",
    Width: "40",
    Options: ParamSetOption.CanGroup + ParamSetOption.Filterable + ParamSetOption.Sortable + ParamSetOption.Hidden
  },
  {
    Name: "По должности",
    FieldName: "AppointmentID",
    Width: "40",
    Options: ParamSetOption.CanGroup + ParamSetOption.Filterable + ParamSetOption.Sortable + ParamSetOption.Hidden + ParamSetOption.NotEdit
  },
  {
    Name: "Сумма по сотруднику",
    FieldName: "ViewMode",
    Width: "40",
    Options: ParamSetOption.CanGroup + ParamSetOption.Filterable + ParamSetOption.Sortable + ParamSetOption.Hidden + ParamSetOption.NotEdit
  },
  { Name: "Ключ", FieldName: "ID", Width: "40", Options: ParamSetOption.Hidden }
];
const SalaryIndividual = (props) => {
  const mainGridRef = reactExports.useRef(null);
  const rangeRef = reactExports.useRef(0);
  const isAdmnin = useAtomValue(isAdminAtom);
  const updateSalaryGridState = () => {
    if (mainGridRef.current && mainGridRef.current.grid) {
      const state = mainGridRef.current.grid.source.saveState();
      const gridStateString = createGridStateString(state);
      if (gridStateString) localStorage.setItem("salaryIndividualGridState", gridStateString);
    }
  };
  reactExports.useEffect(() => {
    var _a, _b;
    if (props.tabIndex === 1 && ((_a = props.date) == null ? void 0 : _a.year) && ((_b = props.date) == null ? void 0 : _b.month)) {
      resetValues().then(buildGrid);
    }
    return () => {
      updateSalaryGridState();
    };
  }, [props.tabIndex, props.payTypeSet.Code, props.date, props.renderingID, props.canModifyRange]);
  const onRecordIndexChanged = async (source) => {
    const range = await source.getFieldValue("Range");
    props.setSelectedRange(range || "0");
  };
  const changeGridStyles = async (table, grid) => {
    const isFixed = await grid.source.getFieldText("IsFixed");
    const canModify = await grid.source.getFieldText("CanModify") === "Да";
    const id = Number(grid.source.getFieldTextSync("ID"));
    if (isFixed === "Да") {
      table.style.backgroundColor = "#d9d9d9";
    }
    if (!canModify) {
      table.style.color = "#808080";
    } else if (between(id, -100, -1)) {
      table.style.color = "#green";
    }
  };
  const onMultiSelectChange = async (grid) => {
    const multiSelect = grid.getMultiSelect();
    let sum = "";
    if (multiSelect.length > 0) {
      const summArr = await Promise.all(
        multiSelect.map(
          async (item) => parseFloat((await grid.source.getFieldText("Amount", item)).replaceAll(",", ".").replaceAll(" ", ""))
        )
      );
      console.log("multiSelectCount", summArr);
      sum = summArr.reduce((acc, item) => acc + item, 0).toFixed(2);
    }
    props.showSalaryFooterData(sum);
  };
  async function buildGrid() {
    let source, grid;
    if (mainGridRef.current && mainGridRef.current.grid) {
      grid = mainGridRef.current.grid;
      grid.source.onHandleRequest = onHandleRequestDocuments();
      grid.canModify = canModifyIndividual;
      setCollumsForGrid(grid);
      grid.resetValues = async () => {
        await resetValues();
        await buildGrid();
      };
      await mainGridRef.current.grid.refreshSource();
      onRecordIndexChanged(mainGridRef.current.grid.source);
    } else {
      source = new createRecordSource();
      source.onHandleRequest = onHandleRequestDocuments();
      const gridState = localStorage.getItem("salaryIndividualGridState");
      const parsedState = parseGridState(gridState);
      if (parsedState) source.setGridState(parsedState);
      source.onRecordIndexChanged = onRecordIndexChanged;
      mainGridRef.current.grid = new createGrid(mainGridRef.current);
      grid = mainGridRef.current.grid;
      grid.canModify = canModifyIndividual;
      grid.changeGridStyles = changeGridStyles;
      grid.setImageFields("Image");
      grid.onMultiSelectChange = onMultiSelectChange;
      setCollumsForGrid(grid);
      await grid.setSource(source);
      grid.refreshSource();
      grid.resetValues = async () => {
        await resetValues();
        await buildGrid();
      };
    }
  }
  const getRangeList = async (objType, day) => {
    const params = /* @__PURE__ */ new Map();
    params.set("prefix", "salary");
    params.set("comand", "GetRangeList");
    params.set("Year", props.date.year || "");
    params.set("Month", props.date.month || "");
    if (day !== void 0) params.set("Day", "1");
    params.set("RenderingID", props.renderingID);
    params.set("ObjType", "2798");
    const json = await AxiosRequest(true, params);
    if (json == null ? void 0 : json.Items) {
      const fixedJson = Object.values(json == null ? void 0 : json.Items).map((item) => {
        return { label: item == null ? void 0 : item.text, id: item == null ? void 0 : item.id };
      });
      return fixedJson;
    }
    return [];
  };
  const between = (x, min, max) => {
    return x >= min && x <= max;
  };
  const canModifyFields = (column, grid) => {
    const cols = ["PayTypeCode", "Day", "Number", "Source"];
    if ((column == null ? void 0 : column.fieldName) && cols.indexOf(column == null ? void 0 : column.fieldName) !== -1) {
      const amount = grid.source.getFieldTextSync("Amount");
      return amount === "";
    } else return true;
  };
  const canModifyRecord = (grid) => {
    const id = Number(grid.source.getFieldTextSync("ID"));
    const baseDoc = Number(grid.source.getFieldTextSync("BaseDoc"));
    let isFixed = grid.source.getFieldTextSync("IsFixed");
    isFixed = isFixed === "" ? "Нет" : isFixed;
    let canModify;
    if (id !== 0) {
      canModify = grid.source.getFieldTextSync("CanModify") === "Да";
    } else canModify = props.canModifyRange;
    if (canModify) {
      canModify = isFixed === "Нет" && baseDoc === 0 && !between(id, -100, -1);
    }
    return canModify;
  };
  const canEditGroupCode = (fieldName) => {
    return fieldName === "GroupCode" && isAdmnin;
  };
  const canEdit = (column, grid) => {
    if (!canEditGroupCode(column == null ? void 0 : column.fieldName)) {
      if ((column == null ? void 0 : column.fieldName) && ["BaseDoc", "Params"].indexOf(column == null ? void 0 : column.fieldName) === -1) {
        return canModifyFields(column, grid) && canModifyRecord(grid);
      }
    }
    return true;
  };
  function canModifyIndividual(flag, column, grid) {
    const flags = [
      () => props.canModifyRange,
      //insert
      (grid2, column2) => canEdit(column2, grid2),
      //edit
      (grid2) => canModifyRecord(grid2)
      //delete
    ];
    return flags[flag](grid, column);
  }
  function resetValues() {
    const params = /* @__PURE__ */ new Map();
    params.set("prefix", "salary");
    params.set("comand", "ResetValues");
    params.set("SectionID", props.id);
    params.set("Year", props.date.year || "");
    params.set("Month", props.date.month || "");
    params.set("RenderingID", props.renderingID);
    params.set("PayTypeSet", props.payTypeSet.Code);
    return AxiosRequest(true, params);
  }
  function setCollumsForGrid(grid) {
    const columns = { title: [] };
    let dest;
    const cols = salaryIndividualDefaultFields.map((col) => {
      if (col.Module === "paytypes") {
        return { ...col, DataType: props.payTypeSet.Code };
      } else if (!col.onDropDownList) return { ...col, onDropDownList: getRangeList };
      return col;
    });
    for (const value of Object.values(cols)) {
      if (value.FieldName) {
        dest = {
          fieldName: value.FieldName,
          title: value.Name || "",
          fieldInfo: {
            options: getParamColumnsOptions(value.Options || 0),
            EditStyle: value.EditStyle || "",
            detailsByReq: value.DetailsByReq,
            Module: value.Module,
            DataType: value.DataType,
            onDropDownList: value.onDropDownList
          },
          hide: value.Options && value.Options & 8192 ? true : false,
          width: value.Width ? parseInt(String(Number(value.Width) * 1.33)) : 100,
          level: value.Level ? parseInt(String(value.Level)) : 0
        };
        columns.title.push(dest);
      }
    }
    grid == null ? void 0 : grid.setColumns(columns, true);
    return columns;
  }
  function onHandleRequestDocuments(id, wsm) {
    return async function(request, load, wsmFromGrid) {
      const params = /* @__PURE__ */ new Map();
      params.set("prefix", "salary");
      params.set("comand", "HandleTable");
      params.set("SectionID", props.id);
      params.set("Values", "1");
      params.set("Year", props.date.year || "");
      params.set("Month", props.date.month || "");
      params.set("RenderingID", props.renderingID);
      params.set("PayTypeSet", props.payTypeSet.Code);
      params.set("AutoCalc", "1");
      if (wsmFromGrid) params.set("WSM", "1");
      const result = await AxiosRequest(load === void 0 ? true : load, params, request);
      if (result.Range) rangeRef.current = result.Range;
      return result;
    };
  }
  function changeDataOfItem(val) {
    const grid = mainGridRef.current.grid;
    if (!val.value) return val;
    const isFixed = grid.source.getFieldValueSync("IsFixed");
    if (val.value === "setFixation" && isFixed === "1") {
      return {
        Caption: "Снять фиксацию",
        value: "disableFixation"
      };
    } else {
      return val;
    }
  }
  const postRecordGrid = async (grid, column, data) => {
    await grid.postSomeData(column, data);
    await grid.postExicstedEditRec(false);
  };
  async function contextMenuHandler(data) {
    const command = data.value;
    const grid = mainGridRef.current.grid;
    switch (command) {
      case "disableFixation":
      case "setFixation": {
        await postRecordGrid(
          grid,
          "IsFixed",
          command === "disableFixation" ? { text: "", id: "" } : { text: "Да", id: "1" }
        );
        break;
      }
    }
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    SmetaTabs,
    {
      id: "salaryIndividual" + props.id,
      onTabIndexChange: async (index) => {
        props.setIsPermanentAccrualsTabActive(index === 1);
        updateGridData(0);
      },
      position: props.tabIndex === 1 ? "bottom" : "hidden",
      style: {
        height: "100%",
        width: "100%"
      },
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaTabItem, { label: "Начисления в текущем месяце", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          ContextMenu,
          {
            for: "grid",
            changeDataOfItem,
            data: {
              Table: [
                {
                  Caption: "Установить фиксацию",
                  value: "setFixation"
                },
                { Caption: "Divider" }
              ]
            },
            onMenuItemClick: contextMenuHandler,
            id: props.id,
            children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                id: "gridpanel" + props.id,
                ref: mainGridRef,
                salary_grid: "",
                tabIndex: 0,
                style: {
                  height: "100%",
                  width: "100%"
                },
                rcsgrid_panel: ""
              }
            )
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaTabItem, { label: "График постоянных начислений", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          BaseSum,
          {
            sectionId: props.id,
            renderingId: props.tabIndex === 1 ? props.renderingID : void 0,
            payTypeSet: props.payTypeSet.Code,
            inputTariffication: props.inputTariffication,
            isHistoryInput: props.isHistoryInput,
            setIsHistoryInput: props.setIsHistoryInput,
            selectedPeriods: props.date
          }
        ) })
      ]
    },
    "salaryIndividual" + props.id
  );
};
const defaultFields = [
  {
    Name: "Фамилия, Имя, Отчество",
    FieldName: "PersonName",
    Width: "150",
    EditStyle: "64",
    Options: `${ParamSetOption.Fixed + ParamSetOption.Sortable}`,
    onEditQuery: true
  },
  { Name: "Таб. №", FieldName: "TabNumber", Width: "55", EditStyle: "64" },
  {
    Name: "Должность",
    FieldName: "Appointment",
    Width: "70",
    EditStyle: "64",
    Options: `${ParamSetOption.Filterable + ParamSetOption.Sortable}`,
    onEditQuery: true
  },
  {
    Name: "Название",
    FieldName: "Appointment",
    Width: "50",
    Options: `${ParamSetOption.Filterable + ParamSetOption.Sortable}`,
    Level: "1",
    onEditQuery: true
  },
  {
    Name: "Подразделение",
    FieldName: "Department",
    Width: "50",
    Options: `${ParamSetOption.Filterable + ParamSetOption.Sortable + ParamSetOption.Hidden}`,
    Level: "1",
    onEditQuery: true
  },
  {
    Name: "Форма назначения",
    FieldName: "JobMode",
    Width: "50",
    Options: `${ParamSetOption.Filterable + ParamSetOption.Sortable}`,
    Level: "1",
    onEditQuery: true
  },
  {
    Name: "Назначение",
    FieldName: "FirstDate",
    Width: "50",
    Level: "1",
    Options: `${ParamSetOption.Sortable}`,
    onEditQuery: true
  },
  {
    Name: "Снятие",
    FieldName: "LastDate",
    Width: "40",
    Level: "1",
    Options: `${ParamSetOption.Sortable}`,
    onEditQuery: true
  },
  { Name: "Расчёт до", FieldName: "FinalDate", Width: "40", Level: "1" },
  {
    Name: "Ставки",
    FieldName: "RateCount",
    Width: "40",
    Level: "1",
    Options: `${ParamSetOption.Sortable}`,
    onEditQuery: true
  }
];
function SalaryComponent(props) {
  var _a;
  const theme = useAtomValue(currentTheme);
  const [selectedSection, setSelectedSection] = useAtom(selectedSectionAtom);
  const [tree, setTree] = reactExports.useState();
  const [payTypeSet, setPayTypeSet] = reactExports.useState();
  const setRenderingIdAtom = useSetAtom(renderingIdAtom);
  const setGroupIdAtom = useSetAtom(groupIdAtom);
  const setLeavesOpenAtom = useSetAtom(leavesOpenAtom);
  const setSalaryRangeAtom = useSetAtom(salaryRangeAtom);
  const [leavesOpen, setLeavesOpen] = reactExports.useState(false);
  const [treeOpen, setTreeOpen] = reactExports.useState(false);
  const [selectedRange, setSelectedRange] = reactExports.useState("0");
  const [buttonState, setButtonState] = reactExports.useState({
    salarySelected: false
  });
  const [individualName, setIndividualName] = reactExports.useState("");
  const [canModifyRange, setCanModifyRange] = reactExports.useState(true);
  const [payTypeSetSelected, setPayTypeSetSelected] = reactExports.useState({
    Name: "",
    Code: "-1"
  });
  const [groupID, setGroupID] = reactExports.useState("");
  const [collapsedSearch, setCollapsedSearch] = reactExports.useState(false);
  const [selectionMode, setSelectionMode] = reactExports.useState(true);
  const [tableLayout, setTableLayout] = reactExports.useState({});
  const [anchor, setAnchor] = reactExports.useState(null);
  const [date, setDate] = reactExports.useState({});
  const [docs, setDocs] = reactExports.useState(null);
  const [tabIndex, setTabIndex] = reactExports.useState(0);
  const [selectedRecordRenderingID, setSelectedRecordRenderingID] = reactExports.useState("0");
  const mainGridRef = reactExports.useRef(null);
  reactExports.useRef(null);
  const selectedRecordsRef = reactExports.useRef([]);
  const stateOfViewRef = reactExports.useRef(false);
  const treeRef = reactExports.useRef(null);
  const setDocsTabIndex = reactExports.useRef(null);
  const [inputTariffication, setInputTariffication] = reactExports.useState(false);
  const [activePeriod, setActivePeriod] = reactExports.useState({});
  const [canEditStaff, setCanEditStaff] = reactExports.useState(false);
  const depTypes = reactExports.useRef("0");
  const [rangeObjType, setRangeObjType] = reactExports.useState("");
  const [withOutRanges, setWithOutRanges] = reactExports.useState(false);
  const [isHistoryInput, setIsHistoryInput] = reactExports.useState(false);
  const [isPermanentAccrualsTabActive, setIsPermanentAccrualsTabActive] = reactExports.useState(false);
  let treeDefaultMultiSel = true;
  reactExports.useEffect(() => {
    if (props.id === selectedSection.ID) {
      if (selectedSection.Who) {
        setTabIndex(selectedSection.Who === "Report" ? 3 : 2);
      }
    }
  }, [selectedSection]);
  reactExports.useEffect(() => {
    processSalary();
    if (selectedSection.Selected) return;
    setSelectedSection({ ...selectedSection, Selected: { Name: "Общий список" } });
  }, []);
  reactExports.useEffect(() => {
    if (!mainGridRef.current || !mainGridRef.current.grid) return;
    const tabIndexes = {
      0: () => {
        mainGridRef.current.grid.updateGridSize();
        showSalaryFooterData();
        setTreeOpen(false);
      },
      1: () => setTreeOpen(true),
      2: () => setCurrentRendering(),
      3: () => setCurrentRendering()
    };
    tabIndexes[tabIndex]();
  }, [tabIndex]);
  reactExports.useEffect(() => {
    resetRenderingGrid();
    setSalaryRangeAtom(date);
  }, [groupID, date]);
  const checkNewPeriod = (rendHistoryParams, currentDate) => {
    let newPeriod = null;
    const year = Number(currentDate.year), month = Number(currentDate.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;
  };
  const updateSalaryAfterSearch = async (objRef) => {
    const json = await getRendHistoryParams(objRef);
    const { RenderingID, DepartmentID } = json;
    setSelectedRecordRenderingID(RenderingID);
    const newDate = checkNewPeriod(json, date);
    if (newDate !== null) {
      setDate(newDate);
    } else mainGridRef.current.grid.refreshSource(RenderingID);
    if (DepartmentID && !groupID.includes(DepartmentID)) {
      if (selectionMode) {
        await treeRef.current.addGroupID(json.DepartmentID);
      } else {
        await treeRef.current.selectGroupID(json.DepartmentID);
      }
    }
  };
  async function getTableLayout(paytype) {
    let params = /* @__PURE__ */ new Map(), data = {}, payTypeSetResp = {}, payTypeSet2 = paytype;
    params.set("prefix", "salary");
    params.set("comand", "GetTableLayout");
    params.set("SectionID", props.id);
    params.set("PayTypeSet", payTypeSet2 && payTypeSet2.Code || payTypeSetSelected.Code);
    data.$content = groupID;
    const resp = await AxiosRequest(true, params, data);
    if (resp.DepTypes) depTypes.current = resp.DepTypes;
    if (payTypeSetSelected.Code === "-1") setTableLayout(resp);
    treeDefaultMultiSel = resp.MultiSel !== "1";
    setCanEditStaff(resp.Staff);
    setWithOutRanges(resp.WithOutRanges === "1");
    setRangeObjType(resp.RangeObjType);
    setSelectionMode(treeDefaultMultiSel);
    if (resp.PayTypeSet) {
      payTypeSetResp.Code = resp.PayTypeSet;
    }
    if (resp.PayTypeSetName) {
      payTypeSetResp.Name = resp.PayTypeSetName;
    }
    if (payTypeSetSelected.Code !== payTypeSetResp.Code && paytype === void 0) setPayTypeSetSelected(payTypeSetResp);
    if (resp.Year && resp.Year !== date.year || resp.Month && resp.Month !== date.Month) {
      setDate({ year: resp.Year, month: resp.Month });
      setActivePeriod({ year: resp.Year, month: resp.Month });
    } else {
      const { month: currentMonth, year: currentYear } = getMonthInfo();
      setDate({ year: currentYear.toString(), month: currentMonth.toString() });
      setActivePeriod({ year: currentYear.toString(), month: currentMonth.toString() });
    }
    return resp;
  }
  async function getPayTypeSets() {
    let params = /* @__PURE__ */ new Map();
    params.set("prefix", "paytypes");
    params.set("comand", "GetPayTypeSets");
    let resp = await AxiosRequest(true, params);
    resp = rebuildItems(resp.items);
    setPayTypeSet(resp);
  }
  async function showSalaryFooterData(text) {
    const source = mainGridRef.current.grid.source;
    const finalText = text ? [`Сумма: ${text}`] : [
      `Текущий:`,
      `Изменен ${await source.getFieldText("PersonName")} (${await source.getFieldText(
        "Department"
      )}) [Количество: ${source.recordCount}] `
    ];
    FooterDataShow(props.id, finalText);
  }
  async function onPayTypeSetClick(e) {
    const code = e.currentTarget.id;
    const text = e.currentTarget.textContent;
    if (code !== payTypeSetSelected.Code) {
      mainGridRef.current.grid.source.close();
    }
    handleCloseAnchorEl();
    await processSalary({ Code: code, Name: text });
    await resetRenderingGrid();
    setPayTypeSetSelected({ Code: code, Name: text });
  }
  function rebuildItems(item) {
    return item.map((val) => {
      if (val.items)
        return {
          ...val,
          Image: getIcons(val.Image),
          ID: val.Code,
          items: rebuildItems(val.items)
        };
      else return { ...val, Image: getIcons(val.Image), ID: val.Code };
    });
  }
  const updateGroupId = (id) => {
    setGroupID(id);
    setGroupIdAtom(id);
  };
  function getTree() {
    if (tree === void 0)
      setTree(
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Tree,
          {
            props: {
              CLSID: props.CLSID,
              MultiSel: true,
              Selection: "",
              ObjType: 2790,
              SectionID: props.id,
              Module: "departments",
              current: groupID,
              ObjRef: groupID,
              selectID: updateGroupId,
              Info: depTypes.current,
              defaultMultiSel: treeDefaultMultiSel,
              ref: treeRef,
              setSelectionMode,
              defaultMenu: [],
              noExpandFirst: true
            }
          }
        )
      );
  }
  const updateOrBuildGrid = async (data) => {
    const grid = mainGridRef.current && mainGridRef.current.grid;
    if (grid) {
      const source = grid.source;
      source.active = false;
      await source.acquireFields();
      source.active = true;
      setCollumsForGrid(data.Columns, grid);
    } else {
      await buildGrid(data);
    }
  };
  async function processSalary(paytype) {
    const data = await getTableLayout(paytype);
    await resetSelection();
    getTree();
    await updateOrBuildGrid(data);
  }
  async function resetRenderings(selectedTreeItems = groupID, datePeriod = date, flag = "0") {
    let params = /* @__PURE__ */ new Map();
    params.set("prefix", "salary");
    params.set("comand", "ResetRenderings");
    params.set("SectionID", props.id);
    params.set("Year", datePeriod.year);
    params.set("Month", datePeriod.month);
    params.set("Flag", flag);
    params.set("AppName", "0");
    params.set("WithFinalDate", "1");
    const resp = await AxiosRequest(true, params, { $content: selectedTreeItems });
    if (resp) {
      setCanModifyRange(!(resp.Locked === "1"));
    }
    return resp;
  }
  const resetSelection = async () => {
    let params = /* @__PURE__ */ new Map();
    params.set("prefix", "salary");
    params.set("comand", "ResetSelection");
    params.set("SectionID", props.id);
    if (stateOfViewRef.current && selectedRecordsRef.current.length > 0)
      params.set("Value", selectedRecordsRef.current.join(","));
    const resp = await AxiosRequest(true, params);
    return resp;
  };
  async function resetRenderingGrid(selectedTreeItems, datePeriod, renderingId = selectedRecordRenderingID, flag = "0") {
    if (date !== void 0) {
      const resp = await resetRenderings(selectedTreeItems, datePeriod, flag);
      if (mainGridRef.current && mainGridRef.current.grid) {
        const grid = mainGridRef.current.grid;
        grid.canModifyRange = !(resp.Locked === "1");
        await grid.refreshSource(renderingId);
        grid.groupID = groupID;
        const renderingID = await mainGridRef.current.grid.source.getFieldValue("RenderingID");
        getIndName();
        await showSalaryFooterData();
        if (renderingID !== "") setSelectedRecordRenderingID(renderingID);
      }
    }
  }
  const updateSalarySliceId = (id, personId) => {
    setRenderingIdAtom({ renderingId: id, personId });
  };
  const updateSalarySliceLeaves = (open) => {
    setLeavesOpenAtom(open);
  };
  const getImageIndex = async (grid) => {
    if (grid && grid.source) {
      const indexVal = await grid.source.getFieldValue("JobMode");
      const listImageValues = grid.source.fields[10];
      if (listImageValues.list && indexVal) {
        const imageIndexObj = listImageValues.list[Number(indexVal)];
        return [imageIndexObj == null ? void 0 : imageIndexObj.id];
      }
    }
  };
  const onRecordIndexChanged = async (source) => {
    const id = await source.getFieldValue("RenderingID");
    showSalaryFooterData();
    if (id !== void 0 && id !== "") {
      const personId = await source.getFieldValue("PersonID");
      setSelectedRecordRenderingID(id);
      updateSalarySliceId(id, personId);
    }
    getIndName();
  };
  const columnOnEditQuery = (column, grid) => {
    let canEdit2 = canEditStaff && grid.columns.levels[2].expanded;
    if (canEdit2 && column.fieldName === "PersonID") {
      canEdit2 = grid.source.getFieldTextSync("FirstDate") === "";
    }
    return canEdit2;
  };
  const canEdit = (column, flag, grid) => {
    if (!grid.columns.levels[2].expanded) return flag === 1 && grid.source.recordCount !== 0;
    else {
      if (flag === 0) return !selectionMode;
      return grid.groupID !== "";
    }
  };
  const canModify = (flag, column, grid) => {
    const mfEdit = 1;
    if (!grid.canModifyRange) return grid.canModifyRange;
    if (flag === mfEdit) {
      if (column.fieldInfo.onEditQuery) return columnOnEditQuery(column, grid);
      else return canEdit(column, flag, grid);
    } else return canEditStaff && canEdit(column, flag, grid) && checkCurrentUserRights(ObjType.RendHistory, flag);
  };
  async function buildGrid(data) {
    let source, grid;
    if (mainGridRef.current && mainGridRef.current.grid) {
      grid = mainGridRef.current.grid;
      grid.canModify = canModify;
      source = grid.source;
      source.active = false;
      await source.acquireFields();
      source.active = true;
    } else {
      source = new createRecordSource();
      source.onHandleRequest = onHandleRequest();
      source.onRecordIndexChanged = onRecordIndexChanged;
      mainGridRef.current.grid = new createGrid(mainGridRef.current);
      grid = mainGridRef.current.grid;
      grid.canModify = canModify;
      grid.activateRange = onMonthOrYearChange;
      grid.OnlyViewMode = true;
      grid.onGetImageIndex = getImageIndex;
      mainGridRef.current.ondblclick = (e) => {
        const table = e.target.closest(".grid-item");
        if (table) {
          ondblclick(table);
        }
      };
      grid.changeGridStyles = changeGridStyles;
    }
    setCollumsForGrid(data.Columns, grid);
    await grid.setSource(source);
    const RenderingID = await source.getFieldValue("RenderingID");
    getIndName();
    if (RenderingID !== "") setSelectedRecordRenderingID(RenderingID);
    grid.refreshSource();
  }
  function getIndName() {
    var _a2, _b;
    if (((_a2 = mainGridRef.current) == null ? void 0 : _a2.grid) && ((_b = mainGridRef.current) == null ? void 0 : _b.grid.source)) {
      const source = mainGridRef.current.grid.source;
      const tabNumber = source.getFieldTextSync("TabNumber");
      const personName = source.getFieldTextSync("PersonName");
      const appointment = source.getFieldTextSync("Appointment");
      const rateCount = source.getFieldTextSync("RateCount");
      const jobMode = source.getFieldTextSync("JobMode");
      let indName = `[${tabNumber}] ${personName} (${appointment} ${rateCount} ст. (${jobMode}))`;
      setIndividualName(indName.replace("()", ""));
    }
  }
  async function ondblclick(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);
    }
  }
  async function changeGridStyles(table) {
    if (table.classList[0] === "grid-item") {
      const isSelected = await isSelectedRow(mainGridRef.current.grid, table.recordIndex);
      if (!isSelected) {
        changeTableStyle(table, true);
      } else {
        changeTableStyle(table, false);
      }
      const isLocked = mainGridRef.current.grid.canModifyRange;
      if (!isLocked) {
        changeTableStyle(table);
      }
    }
  }
  function changeTableStyle(table, state) {
    const allTd = table.querySelectorAll(".grid-td");
    const isLocked = !mainGridRef.current.grid.canModifyRange;
    if (state === true && stateOfViewRef.current === false) {
      changeTextColor("white");
      table.style.backgroundColor = "#1200ff";
    } else if (!state) {
      table.style.backgroundColor = "";
      changeTextColor("");
    }
    function changeTextColor(color) {
      for (const value of Object.values(allTd)) {
        if (value.field && value.field.fieldName && value.field.fieldName !== "PersonName") {
          value.style.color = isLocked ? "gray" : color;
        }
      }
    }
  }
  async function isSelectedRow(grid, recordIndex) {
    const renderingID = await grid.source.getFieldValue("RenderingID", recordIndex);
    const index = selectedRecordsRef.current.indexOf(renderingID);
    return index === -1;
  }
  function setCollumsForGrid(columns, grid) {
    if (columns) {
      const allFields = defaultFields.concat(columns);
      const cols = allFields.map((item) => {
        return {
          fieldName: item.FieldName,
          title: item.Name,
          width: item.Width ? parseInt(item.Width) * 1.3 : 100,
          level: parseInt(item.Level) || 0,
          fieldInfo: {
            options: getParamColumnsOptions(item.Options || 0),
            onEditQuery: item.onEditQuery,
            EditStyle: item.EditStyle || "",
            Module: item.Module || "",
            DataType: item.DataType || ""
          }
        };
      });
      grid == null ? void 0 : grid.setColumns({ title: cols }, true);
      return cols;
    } else grid.defaultColumns = true;
  }
  function onMonthOrYearChange(e) {
    if (e.range) setActivePeriod({ year: e.year, month: e.month });
    setDate(e);
  }
  function onHandleRequest(id, wsm) {
    return async function(request, load, wsmFromGrid) {
      let params = /* @__PURE__ */ new Map();
      params.set("prefix", "salary");
      params.set("comand", "HandleTable");
      params.set("SectionID", props.id);
      params.set("AppName", "0");
      if (wsmFromGrid) params.set("WSM", "1");
      const result = await AxiosRequest(load === void 0 ? true : load, params, request);
      return result;
    };
  }
  function getTheme() {
    return theme;
  }
  const setCurrentRendering = async () => {
    let params = /* @__PURE__ */ new Map();
    params.set("prefix", "salary");
    params.set("comand", "SetCurrentRendering");
    params.set("SectionID", props.id);
    params.set("ID", selectedRecordRenderingID);
    await AxiosRequest(true, params);
  };
  const onTabReClick = (index) => {
    var _a2;
    if (index !== 2) return;
    (_a2 = setDocsTabIndex.current) == null ? void 0 : _a2.call(setDocsTabIndex);
  };
  function onTabChange(index) {
    setTabIndex(index);
    hideSetionButtons(index);
    const indexNames = ["Общий список", "Индивидуально", "", "Отчёты"];
    setSelectedSection({ ...selectedSection, Selected: { Name: indexNames[index] } });
  }
  const hideSetionButtons = (tabIndex2) => {
    const div = document.getElementById("SectionSalary" + props.id);
    const buttonsToHide = div.querySelectorAll(tabIndex2 > 1 ? "[toolsbutton]" : "[documentsectionbutton]");
    buttonsToHide.forEach((item) => {
      item.style.display = "none";
    });
    const buttonsToShow = div.querySelectorAll(tabIndex2 <= 1 ? "[toolsbutton]" : "[documentsectionbutton]");
    buttonsToShow.forEach((item) => {
      item.style.display = "";
    });
  };
  const handleCloseAnchorEl = () => {
    setAnchor(null);
  };
  const controlButtonClick = async () => {
    if (selectedRecordsRef.current.length > 0) {
      stateOfViewRef.current = !stateOfViewRef.current;
      setButtonState({ salarySelected: stateOfViewRef.current });
      await resetSelection();
      await resetRenderingGrid();
    }
  };
  async function handleMarkSelected(grid, selectedRecordsRef2) {
    const multiSelect = grid.getMultiSelect();
    if (multiSelect.length > 0) {
      for (const index of multiSelect) {
        const RenderingID = await grid.getActiveSource().getFieldValue("RenderingID", Number(index));
        const indexSelected = selectedRecordsRef2.current.indexOf(RenderingID);
        if (indexSelected === -1) selectedRecordsRef2.current.push(RenderingID);
      }
      controlButtonClick();
    } else {
      await ondblclick();
      await grid.updateGridSize();
    }
  }
  async function handleSpecialSelection(props2, date2) {
    let params = /* @__PURE__ */ new Map();
    params.set("prefix", "salary");
    params.set("comand", "SpecialSelection");
    params.set("SectionID", props2.id);
    params.set("Year", date2.year);
    params.set("Month", date2.month);
    params.set("WSM", "1");
    const response = await AxiosRequest(true, params);
    tokenProcessingTest(response, { func: resetRenderingGrid });
  }
  async function handleClearSelection(grid, selectedRecordsRef2) {
    selectedRecordsRef2.current = [];
    stateOfViewRef.current = false;
    await resetSelection();
    await resetRenderingGrid();
  }
  async function handleClearMonth(date2) {
    let params = /* @__PURE__ */ new Map();
    params.set("prefix", "salary");
    params.set("comand", "ClearRange");
    params.set("List", "1");
    params.set("Year", date2.year);
    params.set("Month", date2.month);
    params.set("ObjType", rangeObjType);
    params.set("WSM", "1");
    const response = await AxiosRequest(true, params);
    tokenProcessingTest(response);
  }
  async function handleJobHistory(grid) {
    const personId = grid.source.getFieldValueSync("PersonID");
    const title = grid.source.getFieldTextSync("PersonID");
    smetaModals.open(/* @__PURE__ */ jsxRuntimeExports.jsx(JobHistoryList, { personId, title, onSelect: updateSalaryAfterSearch }), {
      Title: "История",
      blockMaximize: true,
      blockResize: true,
      blockSaveLocation: true,
      style: getStyleWindow(),
      hiddenButton: true
    });
  }
  const activateRangeClick = async () => {
    if (date.year && date.month) {
      const wsmResponse = await smetaAxios.get("ActivateRange", {
        prefix: Prefixes.salary,
        params: { Year: date.year, Month: date.month, ObjType: rangeObjType, WSM: "1" },
        loadMask: true
      });
      if (wsmResponse.Token) tokenProcessingTest(wsmResponse);
    }
  };
  async function contextMenuHandler(data) {
    const command = data.value;
    const grid = mainGridRef.current.grid;
    const commandHandlers = {
      ОтметитьВыбранных: (grid2, selectedRecordsRef2) => handleMarkSelected(grid2, selectedRecordsRef2),
      ДопУсловияОтбора: (props2, date2) => handleSpecialSelection(props2, date2),
      СнятьВсюОтметку: (grid2, selectedRecordsRef2) => handleClearSelection(grid2, selectedRecordsRef2),
      ОчиститьМесяц: (grid2, selectedRecordsRef2, props2, date2) => handleClearMonth(date2),
      ИсторияНазначений: (mainGridRef2) => handleJobHistory(mainGridRef2),
      openLeaves: handleCollapseLeaves,
      openChartOfCalculations,
      handleCollapseSearch,
      handleCollapseTree,
      handleInputTariffication: () => setInputTariffication(!inputTariffication),
      activateRange: activateRangeClick
    };
    if (commandHandlers[command]) {
      await commandHandlers[command](grid, selectedRecordsRef, props, date);
    }
  }
  async function onResizeEnd() {
    await mainGridRef.current.grid.updateGridSize();
  }
  async function openChartOfCalculations() {
    if (withOutRanges) {
      const messageText = canModifyRange ? "Закрыть выбранный месяц?" : "Открыть выбранный месяц?";
      renderMessageBox({
        dlgType: DlgType.Confirmation,
        buttons: Button$1.Yes + Button$1.No,
        message: messageText,
        selectF: (ev) => {
          if (ev.target.value == DlgRes.Yes)
            resetRenderingGrid(void 0, void 0, void 0, canModifyRange ? "1" : "2");
        }
      });
    } else {
      const resp = await smetaAxios.get("GetDialogParams", {
        prefix: Prefixes.salary,
        params: { OnlyView: "1", ObjType: rangeObjType, ObjRef: tabIndex === 1 ? selectedRange : "0" },
        loadMask: true
      });
      smetaModals.open(
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          HandleTable,
          {
            json: resp,
            subData: {
              props: {
                SectionID: getModalSectionID(),
                Module: "salary",
                ObjType: rangeObjType,
                Buttons: Button$1.Cancel,
                NewModalWindow: true
              }
            }
          }
        ),
        {
          Title: resp.Title,
          blockMaximize: true,
          blockSaveLocation: true,
          hiddenButton: true,
          style: getStyleWindow("params")
        }
      );
    }
  }
  async function handleCollapseSearch() {
    setCollapsedSearch(!collapsedSearch);
    await mainGridRef.current.grid.updateGridSize();
  }
  const handleCollapseTree = async () => {
    setTreeOpen(!treeOpen);
    await mainGridRef.current.grid.updateGridSize();
  };
  const handleCollapseLeaves = async () => {
    updateSalarySliceLeaves(!leavesOpen);
    setLeavesOpen(!leavesOpen);
    await mainGridRef.current.grid.updateGridSize();
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "div",
    {
      id: "SectionSalary" + props.id,
      style: { display: "flex", flexDirection: "column", height: "100%", width: "100%" },
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          SectionToolsJS,
          {
            ID: props.id,
            postData: {
              Params: { SectionID: props.id, current: selectedRecordRenderingID, Year: date.year, Month: date.month },
              Module: "Salary",
              GroupID: groupID,
              Token: "SetRendSelection"
            },
            defaultButton: tabIndex <= 1 && /* @__PURE__ */ jsxRuntimeExports.jsx(
              SalaryButtons,
              {
                rangeObjType,
                canModifyRange,
                withOutRanges,
                onClick: contextMenuHandler,
                salaryCallBack: resetRenderingGrid,
                postData: {
                  SectionID: props.id,
                  Current: selectedRecordRenderingID,
                  Year: date.year || "",
                  Month: date.month || ""
                }
              }
            )
          }
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          SmetaTabs,
          {
            id: "tabsDocumentDetails" + props.id,
            tabIndex,
            onTabIndexChange: onTabChange,
            onTabReClick,
            style: {
              flex: tabIndex === 0 || tabIndex === 1 ? "0" : "1 1 auto"
            },
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                SmetaTabItem,
                {
                  style: {
                    textTransform: "none",
                    width: "100%",
                    height: "0px",
                    padding: "0px",
                    overflowX: "hiden",
                    display: "none"
                  },
                  label: "Общий список"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                SmetaTabItem,
                {
                  style: {
                    textTransform: "none",
                    width: "100%",
                    height: "0%",
                    padding: "0px",
                    display: "none",
                    overflowX: "hidden"
                  },
                  label: "Индивидуально"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                SmetaTabItem,
                {
                  label: "Документы",
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    SectionDocumentsChose,
                    {
                      id: props.id,
                      sectionTools: false,
                      setParentFunc: (func) => {
                        setDocsTabIndex.current = func;
                      }
                    }
                  )
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                SmetaTabItem,
                {
                  style: {
                    textTransform: "none",
                    width: "100%",
                    height: "100%",
                    padding: "0px",
                    display: "inline-block",
                    overflowX: "hidden"
                  },
                  label: "Отчёты",
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                    SectionReports,
                    {
                      id: props.id
                    }
                  )
                }
              )
            ]
          },
          "tabsDocumentDetails" + props.id
        ),
        /* @__PURE__ */ jsxRuntimeExports.jsxs(
          SplitterLocal,
          {
            style: {
              width: "100%",
              borderTop: "1px solid rgb(208, 208, 208)",
              flex: "1 1 auto",
              display: tabIndex > 1 ? "none" : ""
            },
            hideSplitterCollapsed: tabIndex > 0,
            orientation: "vertical",
            collapsed: treeOpen,
            onExpand: handleCollapseTree,
            onCollapse: handleCollapseTree,
            onResizeEnd,
            sizeSecondary: "20%",
            primaryIndex: 1,
            blockResize: false,
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Grid2, { children: tree }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Grid2,
                {
                  container: true,
                  direction: "column",
                  sx: {
                    justifyContent: "flex-start",
                    alignItems: "flex-start"
                  },
                  children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                    SplitterLocal,
                    {
                      collapsed: !collapsedSearch,
                      primaryIndex: 1,
                      sizeSecondary: "265px",
                      orientation: "vertical",
                      onExpand: handleCollapseSearch,
                      onCollapse: handleCollapseSearch,
                      onResizeEnd,
                      hideButtons: true,
                      hideSplitterCollapsed: true,
                      transitionDuration: 250,
                      children: [
                        /* @__PURE__ */ jsxRuntimeExports.jsx(
                          SearchPersons,
                          {
                            module: Prefixes.salary,
                            orientation: "horizontal",
                            sectionId: props.id,
                            objType: 2010,
                            colapseSearch: handleCollapseSearch,
                            selectedPeriod: date,
                            onSelect: updateSalaryAfterSearch
                          }
                        ),
                        /* @__PURE__ */ jsxRuntimeExports.jsxs(
                          "div",
                          {
                            style: {
                              display: "flex",
                              flexDirection: "column"
                            },
                            children: [
                              /* @__PURE__ */ jsxRuntimeExports.jsx("div", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                                ContextMenu,
                                {
                                  data: [
                                    {
                                      Caption: "Активировать период",
                                      value: "activateRange"
                                    }
                                  ],
                                  onMenuItemClick: contextMenuHandler,
                                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(MonthYearPicker, { value: date, onChange: onMonthOrYearChange, todayValue: activePeriod })
                                }
                              ) }),
                              /* @__PURE__ */ jsxRuntimeExports.jsx(Grid2, { sx: { height: "36px" }, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(Grid2, { sx: { height: "36px", display: "flex", width: "100%" }, children: [
                                /* @__PURE__ */ jsxRuntimeExports.jsxs(
                                  ButtonsForGridComponent,
                                  {
                                    id: props.id,
                                    onClick: controlButtonClick,
                                    grid: mainGridRef.current && mainGridRef.current.grid ? {
                                      grid: mainGridRef.current.grid,
                                      source: mainGridRef.current.grid.source
                                    } : void 0,
                                    style: { width: "100%" },
                                    theme: getTheme(),
                                    selectedRecord: selectedRecordRenderingID,
                                    buttonsState: buttonState,
                                    onTheRightText: tabIndex === 0 ? payTypeSetSelected.Name : individualName,
                                    buttons: {
                                      navigate: true,
                                      salaryCategory: true,
                                      salarySelected: tabIndex === 0
                                    },
                                    children: [
                                      " ",
                                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                                        Button,
                                        {
                                          className: cn("buttonStimate", {
                                            light: theme === "light"
                                          }),
                                          variant: "outlined",
                                          onClick: (e) => {
                                            if (payTypeSet === void 0) getPayTypeSets();
                                            setAnchor(e.target);
                                          },
                                          style: {
                                            textTransform: "none",
                                            borderRadius: "15px",
                                            height: "20px"
                                          },
                                          children: "Категория"
                                        }
                                      ),
                                      " ",
                                      /* @__PURE__ */ jsxRuntimeExports.jsx(
                                        Menu,
                                        {
                                          anchorEl: anchor,
                                          open: Boolean(anchor),
                                          onClose: handleCloseAnchorEl,
                                          MenuListProps: {
                                            "aria-labelledby": "basic-button"
                                          },
                                          children: anchor && payTypeSet !== void 0 && MenuItems(payTypeSet, onPayTypeSetClick)
                                        }
                                      )
                                    ]
                                  }
                                ),
                                tabIndex === 1 && isPermanentAccrualsTabActive && /* @__PURE__ */ jsxRuntimeExports.jsx(
                                  Link,
                                  {
                                    fontSize: "small",
                                    component: "button",
                                    underline: "hover",
                                    onClick: () => setIsHistoryInput(!isHistoryInput),
                                    children: isHistoryInput ? "Ввод начислений периодами" : "Ввод начислений историей"
                                  }
                                )
                              ] }) }),
                              /* @__PURE__ */ jsxRuntimeExports.jsxs(
                                SplitterLocal,
                                {
                                  collapsed: !leavesOpen,
                                  style: {
                                    width: "100%",
                                    borderTop: "1px solid rgb(208, 208, 208)",
                                    flex: "1 1"
                                  },
                                  orientation: "horizontal",
                                  onExpand: handleCollapseLeaves,
                                  onCollapse: handleCollapseLeaves,
                                  onResizeEnd,
                                  sizeSecondary: "25%",
                                  primaryIndex: 0,
                                  blockResize: false,
                                  children: [
                                    /* @__PURE__ */ jsxRuntimeExports.jsxs(
                                      Grid2,
                                      {
                                        sx: {
                                          width: "100%",
                                          flex: "1 0 auto"
                                        },
                                        children: [
                                          /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { position: "relative", height: "100%", display: tabIndex === 1 && "none" }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                                            ContextMenu,
                                            {
                                              for: "grid",
                                              data: {
                                                Table: [
                                                  {
                                                    Caption: "Отметить выбранных",
                                                    value: "ОтметитьВыбранных",
                                                    Disabled: stateOfViewRef.current === true
                                                  },
                                                  {
                                                    Caption: "Дополнительные условия отбора",
                                                    value: "ДопУсловияОтбора"
                                                  },
                                                  {
                                                    Caption: "Снять всю отметку",
                                                    value: "СнятьВсюОтметку",
                                                    Disabled: selectedRecordsRef.current.length === 0
                                                  },
                                                  { Caption: "Divider" },
                                                  {
                                                    Caption: "Очистить месяц",
                                                    value: "ОчиститьМесяц",
                                                    Disabled: selectedRecordRenderingID === "0" || selectedRecordRenderingID === void 0 || !canModifyRange
                                                  },
                                                  { Caption: "Divider" },
                                                  {
                                                    Caption: "История назначений",
                                                    value: "ИсторияНазначений",
                                                    Disabled: selectedRecordRenderingID === "0" || selectedRecordRenderingID === void 0
                                                  },
                                                  { Caption: "Divider" }
                                                ]
                                              },
                                              onMenuItemClick: contextMenuHandler,
                                              id: props.id,
                                              children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                                                "div",
                                                {
                                                  id: "gridpanel" + props.id,
                                                  ref: mainGridRef,
                                                  tabIndex: "0",
                                                  salary_grid: "",
                                                  style: {
                                                    height: "100%",
                                                    width: "100%"
                                                  },
                                                  rcsgrid_panel: ""
                                                }
                                              )
                                            }
                                          ) }),
                                          /* @__PURE__ */ jsxRuntimeExports.jsx(
                                            SalaryIndividual,
                                            {
                                              showSalaryFooterData,
                                              setSelectedRange,
                                              tabIndex,
                                              payTypeSet: payTypeSetSelected,
                                              date,
                                              renderingID: selectedRecordRenderingID,
                                              id: props.id,
                                              mainListGrid: ((_a = mainGridRef.current) == null ? void 0 : _a.grid) && mainGridRef.current.grid,
                                              canModifyRange,
                                              inputTariffication,
                                              isHistoryInput,
                                              setIsHistoryInput,
                                              setIsPermanentAccrualsTabActive
                                            }
                                          )
                                        ]
                                      }
                                    ),
                                    /* @__PURE__ */ jsxRuntimeExports.jsx(
                                      Leaves,
                                      {
                                        SectionID: props.id,
                                        GroupID: selectedRecordRenderingID,
                                        Year: date && date.year ? date.year : "",
                                        Month: date && date.month ? date.month : "",
                                        Date: date,
                                        open: leavesOpen
                                      }
                                    )
                                  ]
                                }
                              )
                            ]
                          }
                        )
                      ]
                    }
                  )
                }
              )
            ]
          }
        )
      ]
    }
  );
}
export {
  SalaryComponent as default
};
//# sourceMappingURL=SalaryComponent-Dn6QrfyR.js.map
