import { t as React, bb as clsx, cY as sectionsStyles, j as jsxRuntimeExports, bd as CheckBoxMultiCheck, cZ as ClickAwayListener, bY as Scrollbars, aK as LoadingMask, I as IconButton, c_ as ExpandMoreIcon, bN as clientExports, ai as Editor, c$ as setColor, ac as tokenProcessingTest } from "./index-D15x63tD.js";
const FontStyle_Bold = 1;
const FontStyle_Italic = 2;
const FontStyle_Underline = 4;
const FontStyle_StrikeOut = 8;
const ParamSetOption_Disabled = 1;
const ParamSetOption_Detalization = 8;
const ParamSetOption_Collapsed = 32;
const ParamSetOption_RedNegative = 128;
const ParamSetOption_Hidden = 8192;
const ParamSetOption_History = 16384;
var resize = {};
function onMouseDown(ev) {
  const record = ev.target.closest("TR");
  const table = record.parentElement;
  const el = record.querySelector(".td-name");
  const elements = table.querySelectorAll(".td-name");
  resize.resizeMode = true;
  resize.target = ev.target;
  resize.cells = elements;
  resize.cell = el;
}
function onMouseUp(ev, setWidth) {
  if (resize.size !== void 0) {
    if (resize.ctrlKey) {
      resize = {};
      return;
    }
    setWidth(resize.size);
    resize = {};
  }
}
function onMouseMove(ev) {
  if (resize.resizeMode) {
    const x = ev.clientX;
    const targetWidth = resize.target.clientWidth;
    const targetX = resize.target.getBoundingClientRect().x;
    if (ev.ctrlKey) {
      resize.ctrlKey = true;
      let size = x - targetWidth - targetX;
      size = resize.cell.clientWidth / resize.cell.parentElement.clientWidth * 100 + size / resize.cell.parentElement.clientWidth * 100;
      if (size < 30) size = 30;
      if (size > 70) size = 70;
      resize.size = size;
      resize.cell.style.width = `${size}%`;
      return;
    }
    resize.cells.forEach((el) => {
      let size = x - targetWidth - targetX;
      if (el.style.clientWidth === 0) return;
      size = el.clientWidth / el.parentElement.clientWidth * 100 + size / el.parentElement.clientWidth * 100;
      if (size < 30) size = 30;
      if (size > 70) size = 70;
      resize.size = size;
      el.style.width = `${size}%`;
    });
  }
}
function getPadding(items, item, index) {
  let padding = 15;
  const level = item.Level ? item.Level : 0;
  if (items.length - 1 > index && level < items[index + 1].Level && checkNextItemsVisible(items, item, index)) {
    padding -= 15;
  }
  if (item.Level) {
    padding += item.Level * 15;
  }
  return padding;
}
function getStyleName(item) {
  return {
    display: "flex",
    flex: "1 1 0",
    color: item.NameColor ? setColor(item.NameColor) : "",
    fontWeight: item.NameStyle & FontStyle_Bold ? "bold" : "",
    fontStyle: item.NameStyle & FontStyle_Italic ? "italic" : "",
    textDecoration: item.NameStyle & FontStyle_Underline ? "underline" : item.NameStyle & FontStyle_StrikeOut ? "line-through" : ""
  };
}
function getStyleColor(item) {
  if (item.TextColor !== void 0) {
    return setColor(item.TextColor);
  }
  return "";
}
function getStyleText(item) {
  const style = {};
  if (item.TextStyle !== void 0) {
    style.fontWeight = item.TextStyle & FontStyle_Bold ? "bold" : "";
    style.fontStyle = item.TextStyle & FontStyle_Italic ? "italic" : "";
    style.textDecoration = item.TextStyle & FontStyle_Underline ? "underline" : item.TextStyle & FontStyle_StrikeOut ? "line-through" : "";
    style.fontSize = "0.75rem";
  }
  return style;
}
function checkNextItemsVisible(items, item, index) {
  let result = false;
  const level = item.Level ? Number(item.Level) : 0;
  for (let i = index + 1; i < items.length; i++) {
    if (level + 1 !== Number(items[i].Level)) return result;
    if (items[i].Options & 1) {
      result = false;
    } else {
      return true;
    }
  }
  return result;
}
function LocalParams(props) {
  const [paramsData, setParamData] = React.useState();
  const [paramsItems, setParamsItems] = React.useState();
  const [paramsJsx, setParamsJsx] = React.useState();
  const [width, setWidth] = React.useState(35);
  const [buttonBlockWidth, setbuttonBlockWidth] = React.useState(0);
  const editor = React.useRef();
  const paramsAnswerObject = React.useRef({});
  const [editionMap, setEditionMap] = React.useState();
  const [getEdition, setGetEdition] = React.useState();
  const mouseDown = React.useRef(null);
  const paramsBox = React.useRef();
  React.useEffect(() => {
    if (props.data) {
      setParamData(props.data);
    }
    paramsBox.current.update = (data) => {
      deleteEditor(editor);
      setParamData(data);
    };
    paramsBox.current.apply = async () => {
      return props.onApply(paramsAnswerObject.current);
    };
    setEditionMap(/* @__PURE__ */ new Map());
  }, []);
  React.useEffect(() => {
    if (props.data) {
      deleteEditor(editor);
      setParamData(props.data);
    }
  }, [props.data]);
  React.useEffect(() => {
    if (paramsData) {
      if (editor.current) {
        deleteEditor(editor.current);
      }
      paramsData.Items.forEach((item) => {
        paramsAnswerObject.current[item.FieldName] = item.Value;
      });
      setParamsItems(paramsData.Items);
    }
  }, [paramsData]);
  React.useEffect(() => {
    if (paramsItems) {
      setParamsJsx(getJsxParams(paramsItems));
    }
  }, [paramsItems]);
  React.useEffect(() => {
    if (getEdition) {
      editionMap.set(getEdition.id, {
        setValue: getEdition.setValue,
        setInputValue: getEdition.setInputValue,
        value: getEdition.value,
        inputValue: getEdition.inputValue,
        setSelection: getEdition.setSelection
      });
    }
  }, [getEdition]);
  React.useLayoutEffect(() => {
    if (paramsJsx) {
      paramsBox.current.querySelectorAll("#expandButtonParams").forEach((el) => {
        if ((Number(el.dataset.collapsed) & ParamSetOption_Collapsed) !== ParamSetOption_Collapsed) {
          el.closest("TR").dataset.collapsed = "1";
          expandRec({ target: el });
        }
      });
    }
  }, [paramsJsx]);
  function getExpandOrMarkButton(items, item, index) {
    const level = item.Level ? item.Level : 0;
    if (items.length - 1 > index && level < items[index + 1].Level && checkNextItemsVisible(items, item, index)) {
      return /* @__PURE__ */ jsxRuntimeExports.jsx(
        IconButton,
        {
          id: "expandButtonParams",
          "data-collapsed": item.Options,
          name: "expandButton",
          onClick: async (ev) => {
            expandRec(ev);
          },
          className: clsx(
            sectionsStyles.paramsExpandButton,
            Number(item.Options) & ParamSetOption_Collapsed && sectionsStyles.paramsExpandButtonRotate
          ),
          children: /* @__PURE__ */ jsxRuntimeExports.jsx(ExpandMoreIcon, { style: { height: "15px", width: "15px" } })
        }
      );
    }
  }
  function expandRec(ev) {
    let button = ev.target.closest("BUTTON");
    let record = ev.target.closest("TR");
    const tdName = record.querySelector(".td-name");
    let level = record.dataset.level;
    let nextRec = record.nextElementSibling;
    const condition = record.dataset.collapsed === "1";
    while (nextRec && nextRec.dataset.level > level) {
      const nextButton = nextRec.querySelector("button[name=expandButton]");
      if (nextButton && nextRec.dataset.collapsed === "0") {
        nextRec.dataset.collapsed = "1";
        nextButton.classList.add(clsx.sectionsStyles.paramsExpandButtonRotate);
      }
      if (condition) {
        nextRec.classList.remove(clsx(sectionsStyles.hiddenBlock));
        const td = nextRec.querySelector(".td-name");
        if (td && tdName) td.style.width = tdName.style.width;
      } else {
        nextRec.classList.add(clsx(sectionsStyles.hiddenBlock));
      }
      if (nextRec.dataset.level !== `${Number(level) + 1}` || Number(nextRec.dataset.options) & ParamSetOption_Disabled) {
        nextRec.classList.add(clsx(sectionsStyles.hiddenBlock));
      }
      nextRec = nextRec.nextElementSibling;
    }
    if (condition) button.classList.remove(clsx(sectionsStyles.paramsExpandButtonRotate));
    else button.classList.add(clsx(sectionsStyles.paramsExpandButtonRotate));
    record.dataset.collapsed = condition ? "0" : "1";
  }
  async function onEdit(data) {
    const textValueDiv = data.record.querySelector('[textvalue="true"]');
    if (data.value === void 0) data.value = data.record.dataset.value;
    if (data.tag === void 0) data.tag = data.record.dataset.objref;
    if (data.CheckState === void 0) {
      data.CheckState = data.record.dataset.checkstate;
    }
    mouseDown.current = false;
    if (data.value !== void 0) textValueDiv.innerText = data.value;
    settingValues(
      {
        Values: [
          {
            EditVal: data.value,
            Value: data.value,
            ObjRef: data.tag,
            CheckState: data.CheckState
          }
        ]
      },
      data
    );
  }
  function settingValues(res, data) {
    if (res) {
      if (!res.Values) return;
      res.Values.forEach((item) => {
        const rec = data.record;
        const textValueDiv = rec.querySelector('[textvalue="true"]');
        rec.dataset.editval = item.EditVal !== void 0 ? item.EditVal : item.Value !== void 0 ? item.Value : "";
        rec.dataset.value = item.Value ? item.Value : "";
        rec.dataset.objref = item.ObjRef ? item.ObjRef : "0";
        if (item.CheckState) {
          if (data.setStateCheckBox) data.setStateCheckBox(item.CheckState);
          rec.dataset.checkstate = item.CheckState;
        }
        textValueDiv.innerText = item.Value !== void 0 ? item.Value : item.EditVal !== void 0 ? item.EditVal : "";
        textValueDiv.style.color = textValueDiv.innerText < 0 && rec.dataset.options & ParamSetOption_RedNegative ? "red" : getStyleColor(item);
        if (editor.current) {
          const edition = editionMap.get(rec.id);
          if (edition) {
            edition.setValue({
              label: item.EditVal ? item.EditVal : item.Value !== void 0 ? item.Value : "",
              id: item.ObjRef ? item.ObjRef : "0"
            });
            edition.setInputValue(item.EditVal ? item.EditVal : item.Value !== void 0 ? item.Value : "");
            if (data.multiselect) {
              if (item.Selection !== void 0) {
                edition.setSelection(item.Selection);
              } else {
                edition.setSelection("");
              }
            }
          }
        }
        paramsAnswerObject.current[data.fieldname] = item.Value;
        if (props.onlyModified) {
          props.onApply(data);
        }
      });
    }
  }
  async function onEditButtonClick(data) {
    if (data.json) tokenProcessingTest(data.json, data.subData);
  }
  async function onDropDownList(data, checklist) {
    if (props.onDropDownList) {
      const arr = await props.onDropDownList(data.fieldname);
      return arr;
    }
  }
  function renderEditor(ev) {
    const record = ev.target.closest("TR");
    if (!record) return;
    if (!record.querySelector('div[editor="true"]').classList.contains(clsx(sectionsStyles.hiddenBlock))) return;
    record.style.backgroundColor = "whitesmoke";
    const editorDiv = record.querySelector('[editor="true"]');
    const textValueDiv = record.querySelector('[textvalue="true"]');
    if (editor.current && editor.current !== editorDiv) {
      deleteEditor(editor.current);
    }
    const editRoot = editorDiv.root || clientExports.createRoot(editorDiv);
    editorDiv.root = editRoot;
    editorDiv.classList.remove(clsx(sectionsStyles.hiddenBlock));
    textValueDiv.classList.add(clsx(sectionsStyles.hiddenBlock));
    editRoot.render(
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        Editor,
        {
          placeholder: " ",
          styleInput: getStyleText({ TextStyle: record.dataset.textstyle }),
          disabled: record.dataset.locked === "1" ? true : false,
          groupid: record.dataset.groupid,
          current: record.dataset.current,
          fieldname: record.dataset.fieldname,
          name: record.dataset.name,
          type: record.dataset.module,
          record,
          objref: record.dataset.objref,
          value: record.dataset.editval,
          datatype: record.dataset.datatype,
          editStyle: record.dataset.editstyle,
          checkstate: record.dataset.checkstate,
          onEdit,
          onEditButtonClick,
          onDropDownList,
          getEdition: setGetEdition,
          editParam: record.dataset.onedit,
          multisel: record.dataset.options & ParamSetOption_Detalization,
          selection: record.dataset.selection,
          func: settingValues
        }
      )
    );
    editor.current = editorDiv;
    const input = editorDiv.querySelector("input[type=text]");
    if (input) {
      input.focus();
      if (record.dataset.editstyle & 64) return;
      input.select();
    }
  }
  function deleteEditor(editor2) {
    if (!(editor2 == null ? void 0 : editor2.classList)) return;
    if (!editor2.classList.contains(clsx(sectionsStyles.hiddenBlock))) {
      const record = editor2.closest("TR");
      record.style.backgroundColor = "";
      const textValueDiv = record.querySelector('[textvalue="true"]');
      editor2.classList.add(clsx(sectionsStyles.hiddenBlock));
      textValueDiv.classList.remove(clsx(sectionsStyles.hiddenBlock));
    }
  }
  function onKeyArrow(ev) {
    let record;
    switch (ev.key) {
      case "ArrowDown":
        record = ev.target.closest("TR").nextElementSibling;
        if (record) {
          if (record.classList.contains(clsx(sectionsStyles.hiddenBlock))) {
            while (record !== null) {
              record = record.nextElementSibling;
              if (record && !record.classList.contains(clsx(sectionsStyles.hiddenBlock))) {
                renderEditor({ target: record });
                break;
              }
            }
          } else {
            renderEditor({ target: record });
          }
        }
        break;
      case "ArrowUp":
        record = ev.target.closest("TR").previousElementSibling;
        if (record) {
          if (record.classList.contains(clsx(sectionsStyles.hiddenBlock))) {
            while (record !== null) {
              record = record.previousElementSibling;
              if (record && !record.classList.contains(clsx(sectionsStyles.hiddenBlock))) {
                renderEditor({ target: record });
                break;
              }
            }
          } else {
            renderEditor({ target: record });
          }
        }
        break;
    }
  }
  function getButtonColWidth(options, other) {
    let res = 0;
    if (options & ParamSetOption_History) {
      res += 20;
    }
    if (other) {
      res += other.Conditions ? 20 : 0;
    }
    return res;
  }
  function getJsxParams(items) {
    let colWidth;
    const returnArr = items.map((item, index) => {
      const expandButton = getExpandOrMarkButton(items, item, index);
      const editStyle = item.EditStyle & 4 ? item.EditStyle - 4 : item.EditStyle;
      colWidth = getButtonColWidth(item.Options, {
        Conditions: item.Conditions
      });
      if (buttonBlockWidth < colWidth) {
        setbuttonBlockWidth(colWidth);
      }
      return /* @__PURE__ */ jsxRuntimeExports.jsxs(
        "tr",
        {
          id: `param_${item.ID}_${index}`,
          "data-datatype": item.DataType ?? item.ObjType,
          "data-editstyle": editStyle,
          "data-fieldname": item.FieldName,
          "data-name": item.Name,
          "data-mapid": item.MapID,
          "data-module": item.Module,
          "data-options": item.Options,
          "data-orderno": item.OrderNo,
          "data-shortname": item.ShortName,
          "data-level": item.Level ? item.Level : 0,
          "data-parentid": item.ParentID,
          "data-collapsed": (Number(item.Options) & ParamSetOption_Collapsed) === 32 ? "1" : "0",
          "data-value": item.Value,
          "data-editval": item.EditVal !== void 0 ? item.EditVal : item.Value,
          "data-objref": item.ObjRef,
          "data-groupid": paramsData.GroupID,
          "data-current": item.Current,
          "data-checkstate": item.CheckState,
          "data-marked": "0",
          "data-locked": item.Locked,
          "data-onedit": item.OnEdit,
          "data-condition": item.Condition !== void 0 ? item.Condition : item.Conditions ? "1" : void 0,
          "data-textstyle": item.TextStyle,
          "data-selection": item.Selection,
          onMouseEnter: (ev) => {
            if (mouseDown) {
              if (mouseDown.current) renderEditor(ev);
            }
          },
          onClick: (ev) => {
            renderEditor(ev);
          },
          onKeyDown: (ev) => {
            onKeyArrow(ev);
          },
          className: clsx(
            sectionsStyles.paramsRecord,
            (item.Level && item.Level !== "0" || Number(item.Options) & ParamSetOption_Disabled || Number(item.Options) & ParamSetOption_Hidden) && sectionsStyles.hiddenBlock
          ),
          children: [
            /* @__PURE__ */ jsxRuntimeExports.jsxs(
              "td",
              {
                id: `name_${item.ID}`,
                title: item.Name,
                className: clsx(sectionsStyles.paramsName, "td-name"),
                style: {
                  paddingLeft: getPadding(items, item, index),
                  width: `${width}%`
                },
                children: [
                  expandButton,
                  /* @__PURE__ */ jsxRuntimeExports.jsx("span", { style: getStyleName(item), children: item.Name }),
                  /* @__PURE__ */ jsxRuntimeExports.jsx(
                    "div",
                    {
                      className: clsx(sectionsStyles.paramsConditions),
                      style: {
                        width: getButtonColWidth(item.Options, {
                          Conditions: item.Conditions
                        })
                      }
                    }
                  )
                ]
              }
            ),
            /* @__PURE__ */ jsxRuntimeExports.jsx("td", { onMouseDown, className: clsx(sectionsStyles.paramsSplitter), id: "splitter-ID", children: /* @__PURE__ */ jsxRuntimeExports.jsx("br", {}) }),
            /* @__PURE__ */ jsxRuntimeExports.jsxs("td", { id: `value_${item.ID}`, className: sectionsStyles.paramsValueConteiner, children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: clsx(
                    sectionsStyles.paramsCheckContainer,
                    (item.EditStyle & 4) === 0 && sectionsStyles.hiddenBlock
                  ),
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx(CheckBoxMultiCheck, { onEdit, MultiCheckSet: item.MultiCheckSet, CheckState: item.CheckState })
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: clsx(sectionsStyles.paramsValue),
                  style: {
                    color: item.Value < 0 && item.Options & ParamSetOption_RedNegative ? "red" : getStyleColor(item),
                    ...getStyleText(item)
                  },
                  textvalue: "true",
                  children: item.Value
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  className: clsx(sectionsStyles.paramsEditorContainer, sectionsStyles.hiddenBlock),
                  editor: "true"
                }
              )
            ] })
          ]
        },
        `param-key_${item.ID}_${index}`
      );
    });
    return returnArr;
  }
  return (
    // при клике вне контейнера параметров редактор скроется
    /* @__PURE__ */ jsxRuntimeExports.jsx(
      ClickAwayListener,
      {
        onClickAway: (ev) => {
          mouseDown.current = false;
          resize = {};
          if (!editor.current || editor.current.classList.contains(clsx(sectionsStyles.hiddenBlock))) {
            return;
          }
          if (ev.target.closest("[checklist]") || ev.target.closest("[calendar]") || ev.target.closest(".background_ModalDialog") && ev.target.closest(".background_ModalDialog") !== paramsBox.current.closest(".background_ModalDialog") || ev.target.closest("LI") || ev.target.classList.contains("MuiBackdrop-root") || ev.target.closest("#applyButton")) {
            return;
          }
          if (editor.current) {
            editor.current.closest("TR").style.backgroundColor = "";
            deleteEditor(editor.current);
          }
        },
        children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
          "div",
          {
            id: "paramsBox",
            ref: paramsBox,
            onMouseDown: (ev) => {
              mouseDown.current = true;
            },
            onMouseUp: () => {
              mouseDown.current = false;
            },
            className: clsx(sectionsStyles.paramsBox),
            children: [
              /* @__PURE__ */ jsxRuntimeExports.jsx(
                Scrollbars,
                {
                  autoHide: true,
                  className: clsx(sectionsStyles.paramsTitleScroll, props.NoTitle && sectionsStyles.hiddenBlock),
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(sectionsStyles.paramsTitleContainer, props.NoTitle && sectionsStyles.hiddenBlock), children: /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: clsx(sectionsStyles.paramsTitle), children: [
                    " ",
                    props.Title || "Условия выборки"
                  ] }) })
                }
              ),
              /* @__PURE__ */ jsxRuntimeExports.jsx(Scrollbars, { className: clsx(sectionsStyles.paramsTableContainer), autoHide: true, children: /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: clsx(sectionsStyles.paramsTableContainer), children: paramsJsx ? /* @__PURE__ */ jsxRuntimeExports.jsx(
                "div",
                {
                  onMouseMove,
                  onMouseUp: (ev) => onMouseUp(ev, setWidth),
                  className: clsx(sectionsStyles.paramsTable),
                  children: /* @__PURE__ */ jsxRuntimeExports.jsx("tbody", { children: paramsJsx })
                }
              ) : /* @__PURE__ */ jsxRuntimeExports.jsx(LoadingMask, {}) }) })
            ]
          }
        )
      }
    )
  );
}
export {
  LocalParams as L
};
//# sourceMappingURL=LocalParams-Dz-ktk1o.js.map
