const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./CodeEditor-DGKjdonB.js","./index-D15x63tD.js","./index-C1k6Yf2q.css"])))=>i.map(i=>d[i]);
import { r as reactExports, u as useAtomValue, bt as animationsAtom, c8 as FooterDataShow, j as jsxRuntimeExports, G as Grid, T as Tooltip, B as Button, I as IconButton, bR as ImgURL, bS as getIcons, bM as SectionToolsJS, c9 as SmetaSplitter, ca as SmetaSplitterItem, a3 as Tree, bG as SmetaTabs, bH as SmetaTabItem, bC as ButtonsForGridComponent, aU as ContextMenu, v as renderMessageBox, bg as smetaAxios, bf as Prefixes, a6 as GridLoader, cb as __vitePreload } from "./index-D15x63tD.js";
const CodeEditor = reactExports.lazy(() => __vitePreload(() => import("./CodeEditor-DGKjdonB.js"), true ? __vite__mapDeps([0,1,2]) : void 0, import.meta.url));
function SectionsDBview(props) {
  var _a;
  const [treeID, setTreeId] = reactExports.useState();
  const [sources, setSources] = reactExports.useState({});
  const gridref = reactExports.useRef(null);
  const treeRef = reactExports.useRef(null);
  const [collapsedTextArea, setCollapsedTextArea] = reactExports.useState(true);
  const [isReq, setIsReq] = reactExports.useState(false);
  const animationsOn = useAtomValue(animationsAtom);
  const [fieldText, setFieldText] = reactExports.useState("");
  const [activeTab, setActiveTab] = reactExports.useState(0);
  const [timerUpdateGrid, setTimerUpdateGrid] = reactExports.useState(void 0);
  const [controlButtonsState, setControlButtonsState] = reactExports.useState({
    filter: false
  });
  reactExports.useEffect(() => {
    var _a2;
    if (treeID) {
      if (activeTab === 0) {
        if (sources[treeID]) {
          gridref.current.style.display = "";
          gridref.current.grid.setSource(sources[treeID]);
          footerData(gridref.current.grid.getActiveSource().recordCount);
        } else {
          gridref.current.style.display = "none";
          setFieldText("");
          footerData();
        }
      } else {
        footerData((_a2 = sources[treeID]) == null ? void 0 : _a2.recordCount);
      }
    }
  }, [treeID]);
  function footerData(numberRecords) {
    FooterDataShow(props.id, ["Число записей:", `${numberRecords || "0"}`]);
  }
  const onButtonsStateChange = (grid) => {
    if (grid) {
      setControlButtonsState({
        filter: grid.filter.style.display === "grid"
      });
    }
  };
  const openData = () => {
    if (treeID) {
      if (isReq) {
        renderMessageBox({
          dlgType: 3,
          buttons: 12,
          message: "Выполнить запрос на изменение данных?",
          selectF: (ev) => {
            const target = ev.target;
            if (target.value === "6")
              smetaAxios.get("ExecuteSQL", { prefix: Prefixes.db, params: { ID: treeID }, loadMask: true });
          }
        });
      } else {
        gridref.current.style.display = "";
        setTimeout(async () => {
          const res = await GridLoader(gridref.current, { Module: "dbview" }, { id: treeID });
          setSources({ ...sources, [treeID]: res.source });
          res.grid.setOptions(2);
          res.grid.onButtonsStateChange = onButtonsStateChange;
          res.source.onRecordIndexChanged = (source) => {
            setTimeout(async () => {
              const fieldName = gridref.current.grid.getSelectedField();
              setFieldText(await source.getFieldText(fieldName));
            }, 1);
          };
          footerData(res.grid.getActiveSource().recordCount);
        }, 251);
      }
    }
  };
  const loadTable = () => {
    if (treeID && sources[treeID]) {
      const fileSelector = document.createElement("input");
      fileSelector.setAttribute("type", "file");
      fileSelector.onchange = (ev) => {
        const target = ev.target;
        const file = target.files[0];
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = async (ev2) => {
          const target2 = ev2.target;
          const rcdata = target2.result.split(",");
          ({ RCDATA: rcdata[1] });
          gridref.current.grid.refreshSource("!");
          fileSelector.remove();
        };
      };
      fileSelector.oncancel = () => {
        fileSelector.remove();
      };
      fileSelector.click();
    }
  };
  const saveTable = async () => {
    if (treeID && sources[treeID]) {
      const answer = await smetaAxios.get("SaveTable", {
        prefix: Prefixes.db,
        params: { ID: treeID },
        loadMask: true
      });
      const rcdata = "data:application/octet-stream;base64," + answer.RCDATA;
      const a = document.createElement("a");
      a.href = rcdata;
      a.download = treeRef.current.getSelectData().label + ".trs";
      a.click();
      a.remove();
    }
  };
  const updateSizeForGrid = () => {
    if (animationsOn) {
      clearTimeout(timerUpdateGrid);
      setTimerUpdateGrid(
        setTimeout(() => {
          var _a2;
          (_a2 = gridref.current.grid) == null ? void 0 : _a2.updateGridSize();
        }, 251)
      );
    } else {
      clearTimeout(timerUpdateGrid);
      setTimerUpdateGrid(
        setTimeout(() => {
          var _a2;
          (_a2 = gridref.current.grid) == null ? void 0 : _a2.updateGridSize();
        }, 1)
      );
    }
  };
  const collapseTextArea = () => {
    setCollapsedTextArea(!collapsedTextArea);
    updateSizeForGrid();
  };
  const handleTabIndexChange = async (index) => {
    setActiveTab(index);
    if (index === 0) {
      if (treeID && sources[treeID]) {
        gridref.current.grid.setSource(sources[treeID]);
      } else gridref.current.style.display = "none";
    }
  };
  const defaultButton = /* @__PURE__ */ jsxRuntimeExports.jsxs(Grid, { style: { marginLeft: "5px", marginRight: "1px" }, children: [
    /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { title: "Показать данные", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Button, { style: { textTransform: "none" }, size: "small", onClick: openData, children: "Открыть" }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { title: "Загрузить данные", children: /* @__PURE__ */ jsxRuntimeExports.jsx(IconButton, { onClick: loadTable, children: ImgURL(getIcons(57)) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { title: "Сохранить данные", children: /* @__PURE__ */ jsxRuntimeExports.jsx(IconButton, { onClick: saveTable, children: ImgURL(getIcons(58)) }) }),
    /* @__PURE__ */ jsxRuntimeExports.jsx(Tooltip, { title: "Текстовое поле", children: /* @__PURE__ */ jsxRuntimeExports.jsx(IconButton, { onClick: collapseTextArea, children: ImgURL(getIcons(34)) }) })
  ] });
  return /* @__PURE__ */ jsxRuntimeExports.jsxs(
    "div",
    {
      id: "SectionsDBview" + props.id,
      style: { display: "flex", flexDirection: "column", height: "100%", width: "100%" },
      children: [
        /* @__PURE__ */ jsxRuntimeExports.jsx(SectionToolsJS, { ID: props.id, defaultButton }),
        /* @__PURE__ */ jsxRuntimeExports.jsx("div", { style: { flex: 1, position: "relative" }, children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          SmetaSplitter,
          {
            onResizeEnd: updateSizeForGrid,
            onCollapse: updateSizeForGrid,
            onExpand: updateSizeForGrid,
            primaryIndex: "end",
            orientation: "vertical",
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaSplitterItem, { size: "25%", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                Tree,
                {
                  props: {
                    CLSID: props.CLSID,
                    multiCheck: false,
                    SectionID: props.id,
                    Module: "DBView",
                    selectID: setTreeId,
                    ref: treeRef,
                    noExpandFirst: true
                  }
                }
              ) }),
              /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaSplitterItem, { children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                SmetaTabs,
                {
                  style: { height: "100%", marginRight: "10px" },
                  onTabIndexChange: handleTabIndexChange,
                  children: [
                    /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaTabItem, { label: "Данные", children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
                      Grid,
                      {
                        container: true,
                        direction: "column",
                        justifyContent: "flex-start",
                        alignItems: "flex-start",
                        style: { width: "100%", height: "100%" },
                        children: [
                          /* @__PURE__ */ jsxRuntimeExports.jsx(Grid, { item: true, style: { width: "100%", height: "36px" }, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                            ButtonsForGridComponent,
                            {
                              id: props.id,
                              grid: ((_a = gridref.current) == null ? void 0 : _a.grid) ? {
                                grid: gridref.current.grid,
                                source: gridref.current.grid.source
                              } : void 0,
                              buttons: {
                                navigate: true,
                                save: false,
                                filter: true
                              },
                              buttonsState: controlButtonsState
                            }
                          ) }),
                          /* @__PURE__ */ jsxRuntimeExports.jsxs(
                            SmetaSplitter,
                            {
                              primaryIndex: "start",
                              orientation: "horizontal",
                              hideButtons: true,
                              onResizeEnd: updateSizeForGrid,
                              style: { flex: 1 },
                              hideSplitterCollapsed: true,
                              children: [
                                /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaSplitterItem, { children: /* @__PURE__ */ jsxRuntimeExports.jsx(ContextMenu, { for: "grid", refs: gridref.current, children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                                  "div",
                                  {
                                    id: "gridpane" + props.id,
                                    ref: gridref,
                                    style: { height: "100%", width: "100%", position: "relative" }
                                  }
                                ) }) }),
                                /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaSplitterItem, { collapsed: collapsedTextArea, size: "10%", children: /* @__PURE__ */ jsxRuntimeExports.jsx(
                                  "textarea",
                                  {
                                    name: "dbviewtextarea",
                                    style: { width: "100%", height: "100%", resize: "none" },
                                    value: fieldText,
                                    readOnly: true
                                  }
                                ) })
                              ]
                            }
                          )
                        ]
                      }
                    ) }),
                    /* @__PURE__ */ jsxRuntimeExports.jsx(SmetaTabItem, { label: "SQL-скрипт", children: /* @__PURE__ */ jsxRuntimeExports.jsx(CodeEditor, { selectedID: treeID, isReq, setIsReq }) })
                  ]
                },
                "Section" + props.id
              ) })
            ]
          }
        ) })
      ]
    }
  );
}
export {
  SectionsDBview as default
};
//# sourceMappingURL=dbview-BtC8SWly.js.map
