import { r as reactExports, j as jsxRuntimeExports, a3 as Tree, ah as AxiosRequest, bN as clientExports, aK as LoadingMask, aw as Params, bM as SectionToolsJS, T as Tooltip, B as Button, I as IconButton, bO as PrintRoundedIcon, bP as SaveAsButton, ax as SplitterLocal, G as Grid, aX as updateVisibleGrids, bf as Prefixes, bg as smetaAxios, ac as tokenProcessingTest, bQ as ClearAllLoadMask, V as isEmptyObject, bR as ImgURL, bS as getIcons, aL as TabsForReports } from "./index-D15x63tD.js";
function SectionReports(props) {
  const currentId = reactExports.useRef(null);
  const applyButton = reactExports.useRef(null);
  const [tree, setTree] = reactExports.useState(null);
  const [GroupID, setGroupID] = reactExports.useState();
  const [reportButtons, setReportButtons] = reactExports.useState({});
  const [reportButtonsJsx, setReportButtonsJsx] = reactExports.useState([]);
  const activReportButtonsContainer = reactExports.useRef(null);
  const reportButtonsRefs = reactExports.useRef({});
  const reportsRef = reactExports.useRef();
  const viewIdentData = reactExports.useRef({});
  const [viewIdent, setViewIdent] = reactExports.useState();
  const [reportModule, setReportModule] = reactExports.useState("");
  const [currentViewIdent, setCurrentViewIdent] = reactExports.useState();
  reactExports.useEffect(() => {
    if (tree === null) {
      setTree(
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          Tree,
          {
            props: {
              CLSID: props.CLSID,
              multiCheck: false,
              SectionID: props.id,
              Module: "reports",
              selectID: setGroupID,
              Current: currentId.current,
              ObjRef: currentId.current,
              defaultMenu: []
            }
          }
        )
      );
    }
  }, [tree]);
  reactExports.useEffect(() => {
    if (GroupID !== void 0) {
      showParams(GroupID);
      showTabs(GroupID);
      currentId.current = GroupID;
      changeSelected(GroupID);
      if (viewIdentData.current && viewIdentData.current[GroupID]) {
        setCurrentViewIdent(viewIdentData.current[GroupID]);
      } else setCurrentViewIdent(void 0);
    }
  }, [GroupID]);
  reactExports.useEffect(() => {
    if (props.seacrhSelected && props.seacrhSelected.Selected) {
      setGroupID(props.seacrhSelected.Selected.ID);
      currentId.current = props.seacrhSelected.Selected.ID;
      setTree(null);
    }
  }, [props.seacrhSelected]);
  reactExports.useEffect(() => {
    setButtonsForReport();
  }, [reportButtons]);
  reactExports.useEffect(() => {
    if (viewIdent) {
      viewIdentData.current[GroupID] = viewIdent;
      setCurrentViewIdent(viewIdent);
    }
  }, [viewIdent]);
  function setButtonsForReport() {
    if (Object.values(reportButtons).length) {
      const result = [];
      Object.entries(reportButtons).map(([key, value], index) => {
        result.push(
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            "div",
            {
              className: GroupID === key ? "showButtons" : "hideButtons",
              style: {
                height: "100%",
                width: "100%",
                alignItems: "center"
              },
              ref: (el) => {
                reportButtonsRefs.current[key] = el;
                if (GroupID === key) {
                  activReportButtonsContainer.current = el;
                }
              },
              children: value
            },
            `report-button-container_${key}_${index}`
          )
        );
      });
      setReportButtonsJsx(result);
    }
  }
  function changeSelected(id) {
    if (activReportButtonsContainer.current) {
      activReportButtonsContainer.current.classList.remove("showButtons");
      activReportButtonsContainer.current.classList.add("hideButtons");
    }
    if (reportButtonsRefs.current[id]) {
      reportButtonsRefs.current[id].classList.remove("hideButtons");
      reportButtonsRefs.current[id].classList.add("showButtons");
      activReportButtonsContainer.current = reportButtonsRefs.current[id];
    }
  }
  function buttonsForReports(json, subData) {
    let items = [], iconbutton;
    if (json !== void 0 && !isEmptyObject(json)) {
      for (const [key, value] of Object.entries(json)) {
        if (value.Caption !== "-") {
          let hintForButton = value.Hint;
          if (value.ShortCutString) {
            hintForButton += ` (${value.ShortCutString})`;
          }
          iconbutton = value.Width && value.Caption !== void 0 ? (
            //если есть ширина, то рисуем обычную кнопку а не айкон баттон
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                id: value.ID,
                "data-viewident": value.ViewIdent,
                from: subData.from,
                style: {
                  width: value.Width === void 0 ? "" : `${value.Width * 1.286}px`,
                  fontSize: "13px",
                  textTransform: "none",
                  textOverflow: "ellipsis",
                  overflow: "hidden",
                  whiteSpace: "nowrap",
                  height: "inherit"
                },
                component: "span",
                disabled: value.Disabled === "1",
                index: key,
                onClick: (event) => {
                  handleToolButton(event);
                },
                startIcon: ImgURL(getIcons(value.Image)),
                children: value.Caption === void 0 ? "" : ` ${value.Caption}`
              },
              key
            )
          ) : /* @__PURE__ */ jsxRuntimeExports.jsxs(
            IconButton,
            {
              id: value.ID,
              "data-viewident": value.ViewIdent,
              from: subData.from,
              variant: "text",
              style: {
                width: value.Caption === void 0 ? "40px" : `${value.Width}px`,
                //value.Width === undefined ||
                fontSize: "13px",
                height: "inherit"
              },
              component: "span",
              index: key,
              disabled: value.Disabled === "1",
              onClick: (event) => {
                handleToolButton(event);
              },
              children: [
                ImgURL(getIcons(value.Image), { marginLeft: "0px" }),
                value.Caption === void 0 ? "" : ` ${value.Caption}`
              ]
            },
            key
          );
          items.push(
            /* @__PURE__ */ jsxRuntimeExports.jsx(Grid, { style: { height: "100%" }, item: true, children: value.Hint ? /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { title: hintForButton, arrow: true, children: iconbutton }) : iconbutton }, key)
          );
        } else {
          items.push(/* @__PURE__ */ jsxRuntimeExports.jsx(Divider, { orientation: "vertical", flexItem: true, sx: { mr: 0.5 } }, key));
        }
      }
      setReportButtons({ ...reportButtons, [GroupID]: items });
    }
  }
  async function handleToolButton(ev) {
    const bttn = ev.target.closest("span");
    const params = /* @__PURE__ */ new Map();
    params.set("prefix", "reports").set("comand", "HandleToolButton").set("ID", bttn.id).set("ReportID", GroupID).set("SectionID", props.SectionID).set("ViewIdent", bttn.dataset.viewident).set("WSM", "1");
    const json = await AxiosRequest(true, params);
    if (json && json.Token) {
      tokenProcessingTest(json);
    }
  }
  function onResize(ev) {
    updateVisibleGrids();
  }
  function showTabs(ID) {
    const tabsParentBlock = document.getElementById(`print_reports${props.id}`);
    for (const [key, value] of Object.entries(tabsParentBlock.children)) {
      if (value.getAttribute("groupId") !== ID) {
        value.style.display = "none";
      } else {
        value.style.display = "";
      }
    }
  }
  function addTabs(ID, json) {
    const tabsParentBlock = document.getElementById(`print_reports${props.id}`);
    clearTab(ID);
    const div = document.createElement("div");
    div.setAttribute("groupId", ID);
    div.style.height = "100%";
    div.style.width = "100%";
    div.id = "ReportsTabDiv" + ID;
    clientExports.createRoot(div).render(
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        TabsForReports,
        {
          reportData: json,
          ID: props.id,
          groupId: GroupID,
          ReportID: ID,
          onTabIndexChange: updateParams,
          onViewIdentChange: setViewIdent,
          onReportModuleChange: setReportModule
        }
      )
    );
    tabsParentBlock.appendChild(div);
  }
  function clearTab(ID) {
    const tabsParentBlock = document.getElementById("ReportsTabDiv" + ID);
    if (tabsParentBlock) tabsParentBlock.remove();
  }
  function printReport() {
    const tabs = document.getElementById(`ReportsTabs${GroupID}`);
    const frame = tabs.getSelectedContent().firstChild;
    if (frame.contentWindow) {
      frame.contentWindow.print();
    }
  }
  function showParams(id) {
    let param = document.getElementById("item_params_reports" + props.id);
    let reportSection = document.getElementById("print_reports" + props.id);
    document.getElementById("buttons_for_section" + props.id);
    if (param) {
      let paramBox = document.getElementById("item_params_reports" + props.id + "_" + id);
      let reportBox = document.getElementById("print_reports" + props.id + "_" + id);
      document.getElementById("button_report_token" + props.id + "_" + id);
      if (paramBox && reportSection && reportBox) {
        param.querySelectorAll(".ActivParams").forEach((n) => {
          n.classList.remove("ActivParams");
          n.classList.add("NoActivParams");
        });
        paramBox.classList.add("ActivParams");
        paramBox.classList.remove("NoActivParams");
        reportSection.querySelectorAll(".ActivParams").forEach((n) => {
          n.classList.remove("ActivParams");
          n.classList.add("NoActivParams");
        });
        reportBox.classList.add("ActivParams");
        reportBox.classList.remove("NoActivParams");
      } else {
        let parametry = document.createElement("div");
        param.querySelectorAll(".ActivParams").forEach((n) => {
          n.classList.remove("ActivParams");
          n.classList.add("NoActivParams");
        });
        reportSection.querySelectorAll(".ActivParams").forEach((n) => {
          n.classList.remove("ActivParams");
          n.classList.add("NoActivParams");
        });
        parametry.classList.add("Params");
        parametry.classList.add("ActivParams");
        parametry.id = "item_params_reports" + props.id + "_" + id;
        parametry.style.height = "100%";
        param.appendChild(parametry);
        updateParams(parametry);
      }
    }
  }
  async function updateParams(block, needRefresh) {
    let params = /* @__PURE__ */ new Map();
    params.set("prefix", "reports");
    params.set("comand", "GetReportParams");
    params.set("ReportID", GroupID);
    params.set("SectionID", props.id);
    if (needRefresh) params.set("NeedRefresh", "1");
    const res = await AxiosRequest(true, params);
    const blockToRender = block === void 0 ? document.getElementById("item_params_reports" + props.id + "_" + GroupID) : block;
    const activeElement = document.activeElement;
    if (activeElement) activeElement.blur();
    const blockToRenderRoot = blockToRender.root || clientExports.createRoot(blockToRender);
    blockToRender.root = blockToRenderRoot;
    blockToRenderRoot.render(/* @__PURE__ */ jsxRuntimeExports.jsx(LoadingMask, {}));
    let paramBox = /* @__PURE__ */ jsxRuntimeExports.jsx(
      Params,
      {
        Module: "reports",
        reqCommand: "GetReportParams",
        Path: res.Path,
        reportID: GroupID,
        id: GroupID,
        SectionID: props.id,
        data: res,
        NoTitle: true
      }
    );
    blockToRenderRoot.render(paramBox);
    if (activeElement) activeElement.focus();
  }
  async function openReport() {
    const config = {
      prefix: Prefixes.report,
      loadMask: true,
      params: {
        sectionId: props.id,
        reportId: GroupID,
        HTML: 0,
        lazy: 0,
        ArchTypes: "zip",
        WSM: 1
      }
    };
    const json = await smetaAxios.get("ExecuteReport", config);
    showHideLoadReport(props.id);
    clearTab(GroupID);
    switch (json.Token) {
      case "ShowProgressDialog":
        let doc = document.getElementById("RenderModal");
        if (doc !== null) {
          doc.innerHTML = "";
        }
        tokenProcessingTest(json, { func: setDataForCurrentReport });
        break;
      case void 0:
        setDataForCurrentReport(json);
        break;
      default:
        tokenProcessingTest(json, { func: setDataForCurrentReport });
        break;
    }
  }
  function setDataForCurrentReport(json) {
    if (json && json.Tools) {
      buttonsForReports(json.Tools.Buttons, {});
    }
    showHideLoadReport(props.id);
    addTabs(GroupID, json);
    const Mask = document.getElementById("loadMaskReport");
    if (Mask) {
      ClearAllLoadMask();
      Mask.remove();
    }
  }
  function showHideLoadReport(id) {
    const Load = document.getElementById("ReportsLoad" + id);
    if (Load) {
      const LoadStyle = Load.style.display;
      Load.style.display = LoadStyle === "none" ? "flex" : "none";
    }
  }
  function onKeyDown(ev) {
    switch (ev.code) {
      case "KeyD":
        if (ev.ctrlKey) {
          ev.preventDefault();
          const activeElement = document.activeElement;
          activeElement.blur();
          setTimeout(() => {
            applyButton.current.click();
            if (activeElement && activeElement.tagName === "INPUT") {
              activeElement.focus();
              activeElement.select();
            }
          }, 100);
        }
        break;
    }
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { onKeyDown, style: { height: "100%", display: "flex", flexDirection: "column" }, children: [
    props.SectionToolsJS ? /* @__PURE__ */ jsxRuntimeExports.jsx(SectionToolsJS, { ID: props.id }) : null,
    /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "heightForSectionWithTools", style: { flex: "1 0 auto" }, children: [
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "div",
        {
          style: {
            display: "flex",
            flexDirection: "row",
            alignItems: "center",
            border: "1px solid #cccccc",
            borderLeft: "0",
            borderRight: "0"
          },
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { title: "Сформировать отчет", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
              Button,
              {
                id: "applyButton",
                ref: applyButton,
                variant: "outlined",
                size: "small",
                onClick: () => openReport(),
                style: {
                  textTransform: "none",
                  marginLeft: "0.88%"
                },
                children: "Выполнить"
              }
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { title: "Печать", children: /* @__PURE__ */ jsxRuntimeExports.jsx("span", { children: /* @__PURE__ */ jsxRuntimeExports.jsx(IconButton, { disabled: !currentViewIdent, onClick: printReport, children: /* @__PURE__ */ jsxRuntimeExports.jsx(PrintRoundedIcon, {}) }) }) }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(SaveAsButton, { reportModule, ViewIdent: currentViewIdent }),
            /* @__PURE__ */ jsxRuntimeExports.jsx(
              "div",
              {
                style: {
                  display: "flex",
                  height: "40px",
                  width: "100%",
                  flex: "0 1 auto",
                  alignItems: "center"
                },
                children: reportButtonsJsx
              }
            )
          ]
        }
      ),
      /* @__PURE__ */ jsxRuntimeExports.jsxs(
        SplitterLocal,
        {
          onCollapse: onResize,
          onExpand: onResize,
          onResizeEnd: onResize,
          orientation: "vertical",
          primaryIndex: 1,
          defaultCollapsed: false,
          transitionDuration: 250,
          sizeSecondary: "30%",
          style: {
            height: !props.SectionToolsJS ? "calc(100% - 39px)" : "calc(100% - 40px)",
            width: "100%"
          },
          id: "ParamsFor_" + props.id,
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { height: "100%", width: "100%" }, id: "item_tree_params_reports_" + props.id, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
              SplitterLocal,
              {
                onCollapse: onResize,
                onExpand: onResize,
                onResizeEnd: onResize,
                primaryIndex: 0,
                defaultCollapsed: false,
                transitionDuration: 250,
                sizeSecondary: "50%",
                style: { width: "100%", height: "100%" },
                orientation: "horizontal",
                children: [
                  /* @__PURE__ */ jsxRuntimeExports.jsx("div", { id: "item_tree_reports_" + props.id, style: { overflow: "hidden", height: "100%", width: "100%" }, children: tree }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "div",
                    {
                      ref: reportsRef,
                      id: "item_params_reports" + props.id,
                      style: { overflowY: "hidden", height: "100%", width: "100%" }
                    }
                  )
                ]
              }
            ) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { id: "item_print_reports" + props.id, style: { height: "100%", width: "100%" }, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(Grid, { id: `print_reports${props.id}`, style: { height: "100%" } }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(LoadingMask, { bool: true, id: "ReportsLoad" + props.id })
            ] })
          ]
        }
      )
    ] })
  ] });
}
export {
  SectionReports as default
};
//# sourceMappingURL=SectionReports-CR4VT6wR.js.map
