import { r as reactExports, u as useAtomValue, bi as salaryRangeAtom, j as jsxRuntimeExports, x as Grid2, aU as ContextMenu, d as Box, B as Button, ap as smetaModals, b1 as getParamColumnsOptions, a6 as GridLoader, ac as tokenProcessingTest, ah as AxiosRequest, bj as getIntOfStrDate } from "./index-D15x63tD.js";
const items = [
  {
    Caption: "Новый расчётный год",
    value: "newYearRange"
  },
  {
    Caption: "Новый расчётный месяц",
    value: "newMonthRange"
  },
  {
    Caption: "Новый день расчёта",
    value: "newDayRange"
  },
  {
    Caption: "Новый расчётный период",
    value: "newPeriodRange"
  },
  {
    Caption: "Новый расчётный период",
    value: "newPeriodRange",
    Disabled: true
  }
];
const contextMenuItems = {
  Table: [
    {
      Caption: "Новый расчётный год",
      value: "newYearRange",
      ID: "1",
      ImageIndex: 43
    },
    {
      Caption: "Новый расчётный месяц",
      value: "newMonthRange",
      ID: "1",
      ImageIndex: 44
    },
    { Caption: "Divider" },
    {
      Caption: "Активировать расчёт",
      value: "activeteRange",
      ID: "1",
      ImageIndex: 9
    },
    {
      Caption: "Обновить расчёт",
      value: "refreshRange"
    },
    {
      Caption: "Очистить расчёт",
      value: "clearRange",
      Disabled: true
    },
    { Caption: "Divider" }
  ]
};
const getTableLaout = async (module, id, objtype) => {
  const params = /* @__PURE__ */ new Map();
  params.set("prefix", module).set("comand", "GetTableLayout").set("ObjType", objtype).set("SectionID", id);
  const response = await AxiosRequest(true, params);
  return response;
};
const DialogChartOfCalculations = ({ props, smetaModalId }) => {
  const gridRef = reactExports.useRef(null);
  const rangeRef = reactExports.useRef("");
  const currentRangeRef = reactExports.useRef("");
  const salaryRange = useAtomValue(salaryRangeAtom);
  const getImageIndex = async (grid) => {
    if (grid == null ? void 0 : grid.source) {
      const calcRange = await grid.source.getFieldValue("CalcRange");
      if (currentRangeRef.current !== void 0 && calcRange === currentRangeRef.current) {
        return ["9"];
      }
    }
  };
  reactExports.useEffect(() => {
    var _a, _b;
    if ((salaryRange == null ? void 0 : salaryRange.range) !== "" && (salaryRange == null ? void 0 : salaryRange.range) !== currentRangeRef.current) {
      currentRangeRef.current = salaryRange == null ? void 0 : salaryRange.range;
      (_b = (_a = gridRef.current) == null ? void 0 : _a.grid) == null ? void 0 : _b.updateGridSize();
    }
  }, [salaryRange]);
  const canModifyRange = (flag, column, grid) => {
    if (grid.OnlyViewMode) return false;
    const acceptDate = Number(grid.source.getFieldValueSync("AcceptDate"));
    const flags = [
      () => false,
      //insert
      (column2) => (column2 == null ? void 0 : column2.fieldName) !== "CalcRange" || acceptDate === 0,
      //edit
      () => acceptDate === 0
      //delete
    ];
    return flags[flag](column);
  };
  const getParamsForRequest = (command) => {
    const params = /* @__PURE__ */ new Map();
    return params.set("prefix", "salary").set("comand", command).set("Range", rangeRef.current).set("ObjType", props.ObjType).set("WSM", "1");
  };
  const deleteRange = async () => {
    const params = getParamsForRequest("DeleteRange");
    const resp = await AxiosRequest(true, params);
    tokenProcessingTest(resp, { func: onRangeDataChange });
  };
  const onEditField = async (editData) => {
    const params = getParamsForRequest("SetCloseDate");
    const date = getIntOfStrDate(editData.value);
    if (date !== -1) params.set("Date", date);
    const resp = await AxiosRequest(true, params);
    tokenProcessingTest(resp, { func: onRangeDataChange });
  };
  const createRangeGrid = async () => {
    const { Module, SectionID, ObjType } = props;
    const tableLaout = await getTableLaout(Module, SectionID, ObjType);
    currentRangeRef.current = tableLaout.Range;
    const cols = tableLaout.Columns.map((item) => {
      return {
        fieldName: item.FieldName,
        title: item.Name,
        width: Number(item.Width) * 1.3,
        orderNo: item.OrderNo,
        fieldInfo: {
          options: getParamColumnsOptions(item.Options || 0),
          EditStyle: item.EditStyle || "",
          Module: item.Module || "",
          DataType: item.DataType || "",
          columnID: item.ID || "",
          mapId: item.MapID || ""
        }
      };
    });
    const { grid, source } = await GridLoader(gridRef.current, props, {
      Columns: cols,
      onGetImageIndex: getImageIndex
    });
    rangeRef.current = await source.getFieldValue("CalcRange");
    source.onRecordIndexChanged = async (sour) => {
      rangeRef.current = await sour.getFieldValue("CalcRange");
    };
    grid.onDeleteRecord = deleteRange;
    grid.onEditField = onEditField;
    grid.OnlyViewMode = true;
    grid.canModify = canModifyRange;
  };
  reactExports.useEffect(() => {
    createRangeGrid();
  }, []);
  const createRange = (child) => {
    const params = getParamsForRequest("CreateRange");
    params.set("Child", child);
    return AxiosRequest(true, params);
  };
  const contextMenuRequest = (command) => {
    const params = getParamsForRequest(command);
    return AxiosRequest(true, params);
  };
  const onRangeDataChange = async (rangeData) => {
    await gridRef.current.grid.refreshSource(rangeData.ID || "!");
  };
  const contextMenuHandler = async (data) => {
    const command = data.value;
    const commands = {
      newYearRange: (child) => createRange(child),
      newMonthRange: (child) => createRange(child),
      newDayRange: (child) => createRange(child),
      newPeriodRange: (child) => createRange(child),
      activeteRange: () => contextMenuRequest("ActivateRange"),
      refreshRange: () => contextMenuRequest("RefreshRange"),
      clearRange: () => contextMenuRequest("ClearRange")
    };
    const wsmResponse = await commands[command](data.ImageIndex === 44 ? "1" : "0");
    if (wsmResponse.Token) tokenProcessingTest(wsmResponse, { func: onRangeDataChange });
    else await onRangeDataChange(wsmResponse);
  };
  const changeDataOfItem = (contextMenuItem) => {
    var _a;
    const processedValues = ["newYearRange", "newMonthRange", "activeteRange"];
    if (!processedValues.includes(contextMenuItem.value)) {
      return contextMenuItem;
    }
    const isEmptyGrid = ((_a = gridRef.current) == null ? void 0 : _a.grid.source.recordCount) === 0;
    if (isEmptyGrid) {
      if (contextMenuItem.value === "newMonthRange" || contextMenuItem.value === "activeteRange") {
        return { ...contextMenuItem, Disabled: true };
      }
      return contextMenuItem;
    }
    if (contextMenuItem.value === "activeteRange") return contextMenuItem;
    const recordInfo = gridRef.current.grid.source.getRecordInfo();
    let key = -1;
    for (const value of Object.values(recordInfo.rangeInfo)) {
      if (value !== 0) {
        key += 1;
      }
    }
    if (contextMenuItem.value === "newMonthRange") {
      key += 1;
    }
    return items[key];
  };
  const onSelect = async () => {
    const tag = await gridRef.current.grid.source.getFieldValue("CalcRange");
    if (props.onEdit) {
      props.onEdit({
        tag,
        name: props.Name,
        record: props.record,
        textchanged: "0",
        setValue: props.setValue,
        setInputValue: props.setInputValue,
        type: props.Module,
        requestId: props.RequestID,
        addInfo: props.addInfo,
        CheckState: "0"
      });
      if (props.NewModalWindow) smetaModals.close(smetaModalId);
      return;
    }
    if (props.RequestID) {
      await formEdit(
        "1",
        props.func,
        {
          Name: "ObjRef",
          Value: tag
        },
        props.RequestID,
        props.from
      );
    }
    if (props.NewModalWindow) smetaModals.close(smetaModalId);
  };
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    Grid2,
    {
      container: true,
      direction: "column",
      sx: {
        justifyContent: "flex-start",
        alignItems: "flex-start",
        height: "100%"
      },
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(Grid2, { sx: { height: "90%", width: "98%", position: "relative" }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
          ContextMenu,
          {
            for: "grid",
            changeDataOfItem,
            data: contextMenuItems,
            onMenuItemClick: contextMenuHandler,
            id: props.id,
            children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { ref: gridRef, salary_grid: "", rcsgrid_panel: "", style: { position: "relative", height: "100%" } })
          }
        ) }),
        /* @__PURE__ */ jsxRuntimeExports.jsx(Grid2, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          Box,
          {
            style: {
              marginLeft: "auto",
              position: "absolute",
              bottom: "8px",
              right: "10px"
            },
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  onClick: onSelect,
                  size: "small",
                  variant: "outlined",
                  style: {
                    textTransform: "none",
                    marginRight: "10px",
                    display: props.Buttons && (props.Buttons & 1) === 0 ? "none" : ""
                  },
                  value: "1",
                  className: "button_Modal_Select",
                  children: "Выбрать"
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Button,
                {
                  size: "small",
                  variant: "outlined",
                  value: 2,
                  onClick: () => {
                    if (props.NewModalWindow) smetaModals.close(smetaModalId);
                  },
                  style: { textTransform: "none" },
                  className: "button_Modal_Close",
                  children: "Закрыть"
                }
              )
            ]
          }
        ) })
      ]
    }
  );
};
export {
  DialogChartOfCalculations as default
};
//# sourceMappingURL=DialogChartOfCalculations-WTMwmnKG.js.map
