import { r as reactExports, ah as AxiosRequest, cy as createRecordSource, cA as createGrid, cU as RightArrowRed, cV as LeftArrowBlue, aN as ObjType, bv as EditStyle, bg as smetaAxios, bf as Prefixes, af as parseColumns, aE as ViewClass, ae as getRightsData, cW as reactDomExports, j as jsxRuntimeExports, b9 as SectionDocuments, aU as ContextMenu, aI as Tabs, aM as checkCurrentUserRights, a7 as TabItem, cS as GetDocDialogParams, ap as smetaModals, aS as Button, ar as getStyleWindow, cX as getAmountDocTypes } from "./index-D15x63tD.js";
import DialogDoc from "./DialogDoc-BCKCegu0.js";
import DialogDocTabs from "./DialogDocTabs-ExyRNCmU.js";
function onDetailsByReq(objType) {
  return async (data) => {
    var _a;
    const params = /* @__PURE__ */ new Map();
    params.set("prefix", "tables").set("comand", "GetObjectParamList").set("ObjType", objType).set("ID", data.ID);
    const json = await AxiosRequest(true, params);
    if ((_a = json == null ? void 0 : json.Items) == null ? void 0 : _a.items) {
      return {
        Items: json.Items.items,
        OnCloseUpListCustom: onCloseUpListCustom(objType),
        OnEditCustom: onEditCustom(objType),
        OnListCustom: onListCustom
      };
    }
    return {};
  };
}
function onEditCustom(objType) {
  return async (data) => {
    const params = /* @__PURE__ */ new Map();
    params.set("prefix", "tables").set("comand", "SetObjectParamValue").set("ID", data.parentID).set("ObjType", objType).set("Name", data.fieldname);
    if (data.CheckState !== void 0) {
      params.set("ObjRef", data.CheckState);
    } else if (!data.tag && data.Value) {
      params.set("TextChanged", data.TextChanged).set("Text", data.Value);
    } else params.set("ObjRef", data.tag);
    return AxiosRequest(true, params);
  };
}
async function onListCustom(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 == null ? void 0 : json.Items) {
    return Object.values(json.Items).map((item, index) => {
      if (typeof item !== "object") {
        if (checklist) return { label: item, id: `${Math.pow(2, index)}` };
        return { label: item, id: `${index}` };
      }
      return { label: item.text, id: item.id };
    });
  }
  return {};
}
function onCloseUpListCustom(objType) {
  return async (data) => {
    const params = /* @__PURE__ */ new Map();
    params.set("prefix", "tables").set("comand", "SetObjectParamValue").set("ID", data.parentID).set("ObjType", objType).set("Name", data.fieldname).set("ObjRef", data.tag);
    return AxiosRequest(true, params);
  };
}
async function hourTypeDropDownList() {
  const params = /* @__PURE__ */ new Map();
  params.set("prefix", "tables").set("comand", "GetTimeCfgList");
  const json = await AxiosRequest(true, params);
  return Object.values(json).map((item) => {
    return { label: item.text, id: item.id };
  });
}
async function rendModesInfoDropDownList(data) {
  const params = /* @__PURE__ */ new Map();
  const grid = data.addInfo.Field.fieldInfo.Grid;
  const workModeId = await grid.source.getFieldValue("WorkMode") || "0";
  params.set("prefix", "schedule").set("comand", "GetWorkModeItems").set("ID", workModeId);
  const json = await AxiosRequest(true, params);
  return Object.values(json).map((item) => {
    return { label: item.text, id: item.id };
  });
}
async function hourTimesSourceDropDownList(data) {
  const params = /* @__PURE__ */ new Map();
  const grid = data.addInfo.Field.fieldInfo.Grid;
  const timeRange = await grid.source.getFieldValue("TimeRange") || "0";
  params.set("prefix", "ABLUtils").set("comand", "GetRangeSourceList").set("Range", timeRange);
  const json = await AxiosRequest(true, params);
  if (json == null ? void 0 : json.Items) {
    return Object.values(json.Items).map((item) => {
      if (typeof item === "object") return { label: item.text, id: item.id };
      return { label: item, id: "" };
    });
  }
  return {};
}
const documentEditButtonClick = async (subData, currentGroupID) => {
  if (subData.props.ObjRef !== "0") {
    const json = await GetDocDialogParams(subData.props.ObjType, subData.props.ObjRef, true);
    smetaModals.open(
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        DialogDoc,
        {
          props: {
            ...json,
            NewModalWindow: true,
            detailsOpen: true,
            setValue: true,
            setInputValue: true,
            Buttons: Button.Cancel
          }
        }
      ),
      {
        Title: json.Title,
        hiddenButton: true,
        style: getStyleWindow(json.CLSID),
        setFocus: true
      }
    );
  } else {
    const json = await getAmountDocTypes(currentGroupID);
    const selectDocument = Object.values(json.Types).map((item) => {
      return { DocCfgID: item.id, Name: item.text };
    });
    smetaModals.open(
      /* @__PURE__ */ jsxRuntimeExports.jsx(
        DialogDocTabs,
        {
          props: {
            CLSID: ViewClass.DocSite,
            SelectDocument: selectDocument,
            NewModalWindow: true,
            onEdit: async (values) => {
              const grid = subData.props.addInfo.Field.fieldInfo.Grid, fieldName = subData.props.addInfo.FieldName;
              await grid.postSomeData(fieldName, {
                id: values.tag
              });
              await grid.postExicstedEditRec(true);
            }
          }
        }
      ),
      {
        hiddenButton: true,
        blockSaveLocation: true,
        style: getStyleWindow(ViewClass.DocSite),
        setFocus: true
      }
    );
  }
};
const defaultColumns = [
  [
    //Отклонение от графика
    {
      Title: "Вид отвлечения",
      FieldName: "AbsenceMask",
      Width: "100",
      EditStyle: "customColorList",
      squareColorField: "Color"
    },
    {
      Title: " ",
      FieldName: "IsExcluded",
      Width: "20",
      EditStyle: "4",
      TextAjust: "1",
      customDefaultIcons: {
        0: LeftArrowBlue,
        1: RightArrowRed
      },
      Image: "30"
    },
    {
      Title: "Начало",
      FieldName: "FirstDate",
      EditStyle: "2",
      Width: "100"
    },
    {
      Title: "Конец",
      FieldName: "LastDate",
      EditStyle: "2",
      Width: "100"
    },
    {
      Title: "Основание",
      FieldName: "BaseDocument",
      EditStyle: "16",
      Width: "100",
      DataType: ObjType.Document,
      tag: 1
    },
    {
      Title: "Документ",
      FieldName: "Document",
      EditStyle: "16",
      Width: "100",
      DataType: ObjType.Document,
      tag: 1
    },
    {
      Title: "Дополнительные значения",
      FieldName: "CalcParams",
      EditStyle: "1",
      Width: "100",
      Module: "tables",
      DataType: "2640",
      tag: 1,
      DetailsByReq: onDetailsByReq(ObjType.RendLeave)
    },
    {
      Title: "Пользователь",
      FieldName: "UpdateUser",
      EditStyle: "64",
      Width: "100"
    },
    {
      Title: "Время изменения",
      FieldName: "UpdateTime",
      EditStyle: "64",
      Width: "100"
    }
  ],
  [
    //Изменения режима работы
    {
      Title: "Режим работы",
      FieldName: "WorkMode",
      EditStyle: "1",
      DataType: "2004",
      Module: "schedule",
      Width: "100"
    },
    {
      Title: "Начало",
      FieldName: "FirstDate",
      EditStyle: "2",
      Width: "100"
    },
    {
      Title: "Конец",
      FieldName: "LastDate",
      EditStyle: "2",
      Width: "100"
    },
    {
      Title: "Начало работы",
      FieldName: "Info",
      EditStyle: "1",
      DataType: "2004",
      //GET /schedule~GetWorkModeItems?LicGUID=319EDF4E4FDF49FC62471A9D53144953&ID=101 HTTP/1.0
      Width: "100",
      OnDropDownList: rendModesInfoDropDownList
    },
    {
      Title: "Документ",
      FieldName: "Document",
      Width: "100"
    },
    {
      Title: "Настройка графика",
      FieldName: "WMSetting",
      Width: "100"
    },
    {
      Title: "Пользователь",
      FieldName: "UpdateUser",
      EditStyle: "64",
      Width: "100",
      tag: 1
    },
    {
      Title: "Время изменения",
      FieldName: "UpdateTime",
      EditStyle: "64",
      Width: "100",
      tag: 1
    }
  ],
  [
    //Изменения режима работы
    {
      Title: "Вид отработки",
      FieldName: "HourType",
      //GET /tables~GetTimeCfgList?LicGUID=319EDF4E4FDF49FC62471A9D53144953 HTTP/1.0
      EditStyle: "17",
      Module: "tables",
      DataType: "2721",
      Width: "100",
      OnDropDownList: hourTypeDropDownList
    },
    {
      Title: "Начало",
      FieldName: "FirstDay",
      EditStyle: "8",
      Width: "100"
    },
    {
      Title: "Конец",
      FieldName: "LastDay",
      EditStyle: "8",
      Width: "100"
    },
    {
      Title: "Факт",
      FieldName: "FactTime",
      Width: "100"
    },
    {
      Title: "Дни",
      FieldName: "CalcFactDays",
      Level: "1",
      Width: "100",
      tag: 1
    },
    {
      Title: "Часы",
      FieldName: "CalcFactHours",
      Level: "1",
      Width: "100",
      tag: 1
    },
    {
      Title: "УЕТ",
      FieldName: "UnitVal",
      Level: "1",
      Width: "100",
      tag: 1
    },
    {
      Title: "Норма",
      FieldName: "NormTime",
      Width: "100"
    },
    {
      Title: "Дни",
      FieldName: "CalcNormDays",
      Level: "1",
      Width: "100"
    },
    {
      Title: "Часы",
      FieldName: "CalcNormDays",
      Level: "1",
      Width: "100"
    },
    {
      Title: "УЕТ",
      FieldName: "NormUnits",
      Level: "1",
      Width: "100"
    },
    {
      Title: "%",
      FieldName: "PercVal",
      Width: "100"
    },
    {
      Title: "Дополнительные значения",
      FieldName: "CalcParams",
      EditStyle: "1",
      Width: "100",
      Module: "tables",
      DataType: ObjType.HourTime,
      DetailsByReq: onDetailsByReq(ObjType.HourTime),
      tag: 1
    },
    {
      Title: "Мес. оплаты",
      FieldName: "Source",
      EditStyle: "1",
      Width: "100",
      OnDropDownList: hourTimesSourceDropDownList,
      tag: 1
    },
    {
      Title: "Результаты расчетов",
      FieldName: "Result",
      Width: "100"
    },
    {
      Title: "Документ",
      FieldName: "Document",
      Width: "100",
      tag: 1
    },
    {
      Title: "Переносить",
      FieldName: "Fixed",
      EditStyle: "4",
      Width: "100"
    },
    {
      Title: "Пользователь",
      FieldName: "UpdateUser",
      EditStyle: "64",
      Width: "100"
    },
    {
      Title: "Время изменения",
      FieldName: "UpdateTime",
      EditStyle: "64",
      Width: "100"
    }
  ]
];
function Leaves({ SectionID, GroupID, Full, Date, open, CLSID = "", noRefs = false }) {
  const [portal, setPortal] = reactExports.useState([]);
  const tabsRef = reactExports.useRef(null);
  const tabs = reactExports.useRef(null);
  const tabsObjType = [2640, 2646, 2644];
  const currentGroupID = reactExports.useRef(GroupID);
  reactExports.useEffect(() => {
    getSectionList().then((res) => {
      processSectionList({
        "Отклонения от графика": {},
        "Изменения режима работы": {},
        "Дополнительное рабочее время": {},
        ...res.Items
      });
    });
  }, [Date]);
  reactExports.useEffect(() => {
    if (open && (Date == null ? void 0 : Date.year)) createLeavesGrid();
    currentGroupID.current = GroupID;
  }, [GroupID, Full, Date, open]);
  const canModifyRendMode = (flag, column, grid) => {
    if ((column == null ? void 0 : column.tag) === 1) return false;
    const rendModesDocument = Number(grid.source.getFieldValueSync("Document"));
    const wmSetting = Number(grid.source.getFieldTextSync("WMSetting"));
    if (flag === 2) return rendModesDocument === 0 && wmSetting === 0;
    return true;
  };
  const canModifyRendLeave = (flag, column, grid) => {
    let canModify;
    const document = Number(grid.source.getFieldValueSync("Document") || 0);
    const baseDocument = Number(grid.source.getFieldValueSync("BaseDocument") || 0);
    if ([1, 2].includes(flag)) canModify = document === 0 && baseDocument === 0;
    else canModify = true;
    if (!canModify && flag === 1) canModify = column.tag === 1;
    return canModify;
  };
  const canModifyRendLeaves = (flag, column, grid) => {
    let canModify = true;
    const renderingId = Number(grid.source.getFieldTextSync("RenderingID"));
    if (canModify) {
      if (grid && checkCurrentUserRights(tabsObjType[grid.leavesMode], flag)) {
        canModify = renderingId !== 0;
        if (grid.leavesMode === 0) canModify = canModifyRendLeave(flag, column, grid);
        else if (grid.leavesMode === 1) canModify = canModifyRendMode(flag, column, grid);
      } else canModify = false;
    }
    return canModify;
  };
  const canModifyHourTimes = (flag, column, grid) => {
    let canModify = canModifyRendLeaves(flag, column, grid);
    if (canModify) {
      const field = grid.source.findField(column.fieldName);
      if (field) {
        canModify = grid.source.getFieldText("canModify");
        return canModify === "1";
      }
      const id = Number(grid.source.getFieldTextSync("ID"));
      const document = Number(grid.source.getFieldValueSync("Document"));
      const flags = [
        () => true,
        //insert
        (column2) => column2.Tag === 1 || document === 0,
        //edit
        () => id > 0 && document === 0
        //delete
      ];
      return flags[flag](column);
    }
    return canModify;
  };
  async function getSectionList() {
    let params = /* @__PURE__ */ new Map();
    params.set("prefix", "tables").set("comand", "GetSectionList");
    const json = await AxiosRequest(true, params);
    return json;
  }
  function processSectionList(data) {
    let tabsJsx = [];
    for (const [key, value] of Object.entries(data)) {
      let tabContent;
      if (!value.CLSID) {
        tabContent = /* @__PURE__ */ jsxRuntimeExports.jsx(
          "div",
          {
            tabIndex: "0",
            style: {
              height: "100%",
              width: "100%"
            },
            rcsgrid_panel: ""
          }
        );
      }
      tabsJsx.push(
        /* @__PURE__ */ jsxRuntimeExports.jsx(
          TabItem,
          {
            style: {
              textTransform: "none",
              width: "100%",
              height: "100%",
              padding: "0px",
              display: "inline-block",
              overflow: "hidden"
            },
            label: key,
            tabInfo: value,
            name: key,
            children: tabContent
          },
          key + "Leaves"
        )
      );
    }
    tabs.current = tabsJsx;
  }
  async function createLeavesGrid() {
    const tabIndex = getTabIndex();
    let source, grid, tabContent = getCurrentTabContent(), objType = tabsObjType[tabIndex];
    const newTab = tabContent ? tabContent.parentElement : void 0;
    if (newTab && newTab.tabInfo && newTab.tabInfo.CLSID) {
      leaveTabChange(newTab.tabInfo).then((res) => {
        createTabContent(res, newTab.tabInfo, newTab);
      });
    } else {
      if (tabContent && tabContent.firstChild.grid) {
        tabContent.firstChild.grid.source.onHandleRequest = onHandleRequestDocuments(SectionID, objType);
        tabContent.firstChild.grid.refreshSource("!");
      } else {
        const canModify = [canModifyRendLeaves, canModifyRendLeaves, canModifyHourTimes];
        source = new createRecordSource();
        source.onHandleRequest = onHandleRequestDocuments(SectionID, objType);
        tabContent.firstChild.grid = new createGrid(tabContent.firstChild);
        source.onRecordIndexChanged = function(source2) {
          source2.getFieldText("ID").then((id) => {
          });
        };
        grid = tabContent.firstChild.grid;
        grid.leavesMode = tabIndex;
        grid.canModify = canModify[tabIndex];
        let cols = defaultColumns[tabIndex];
        if (tabIndex === 0) {
          cols = cols.map((item) => {
            const isDocumentField = item.FieldName === "Document" || item.FieldName === "BaseDocument";
            if (noRefs && isDocumentField) {
              return { ...item, EditStyle: EditStyle.ReadOnly.toString() };
            }
            if (item.FieldName === "AbsenceMask") {
              return {
                ...item,
                OnListCustom: async () => smetaAxios.get("GetAbsenceList", {
                  prefix: Prefixes.tables,
                  params: { SectionID, GroupID: currentGroupID.current },
                  loadMask: true
                })
              };
            }
            return item;
          });
        }
        setCollumsForGrid(cols, grid);
        await grid.setSource(source);
        grid.refreshSource("0");
      }
    }
  }
  function setCollumsForGrid(Columns, grid) {
    if (Columns) {
      const funcOnEditButtonClick = { BaseDocument: true, Document: true };
      const columns = parseColumns(
        {
          Columns: Columns.filter((value) => {
            if (funcOnEditButtonClick[value.FieldName])
              value.OnEditButtonClick = (subData) => documentEditButtonClick(subData, currentGroupID.current);
            return !(ViewClass.TimeTable === CLSID && value.FieldName === "Result");
          })
        },
        {
          docOpts: true,
          widthMultiply: 1.33
        }
      );
      grid == null ? void 0 : grid.setColumns(columns, true);
      return columns;
    } else grid.defaultColumns = true;
  }
  function getCurrentTabContent() {
    const selectedIndex = getTabIndex();
    const currentTabContent = tabsRef.current.nativeElement.getTabContent(selectedIndex);
    return currentTabContent;
  }
  const getTabIndex = () => {
    return Number(tabsRef.current.nativeElement.getAttribute("selected-index"));
  };
  function onHandleRequestDocuments(id, objType) {
    return async function(request, load, wsmFromGrid) {
      let params = /* @__PURE__ */ new Map();
      params.set("prefix", "tables");
      params.set("comand", "HandleTable");
      params.set("SectionID", id ? id : SectionID);
      params.set("ObjType", objType);
      params.set("GroupID", GroupID);
      params.set("Year", Date.year ? Date.year : "");
      params.set("Month", Date.month ? Date.month : "");
      params.set("Full", Full ? Full : "0");
      if (wsmFromGrid) params.set("WSM", "1");
      const result = await AxiosRequest(load === void 0 ? true : load, params, request);
      if (result.Rights) {
        const grid = getCurrentTabContent().firstChild;
        grid.grid.source.rights = getRightsData(result.Rights);
      }
      return result;
    };
  }
  function onTabChange(e) {
    const newTab = getCurrentTabContent().parentElement;
    if (newTab.tabInfo && newTab.tabInfo.CLSID) {
      leaveTabChange(newTab.tabInfo).then((res) => {
        createTabContent(res, newTab.tabInfo, newTab);
      });
    } else {
      if (open && (Date == null ? void 0 : Date.year)) createLeavesGrid();
    }
  }
  function createTabContent(res, data, tabContent) {
    console.log(res, data, tabContent);
    if (data.CLSID === "{48C155C0-1336-11D6-9CF2-DB1D5BC3046D}" && tabContent.firstChild.children.length === 0) {
      setPortal(
        reactDomExports.createPortal(
          /* @__PURE__ */ jsxRuntimeExports.jsx(
            SectionDocuments,
            {
              DocCfgID: res.ObjType ? res.ObjType : "-1",
              HideParams: true,
              SectionToolsJS: false,
              id: data.tag,
              HideControlButtons: true
            }
          ),
          tabContent.firstChild
        )
      );
    } else {
      if (tabContent.firstChild && tabContent.firstChild.firstChild && tabContent.firstChild.firstChild.refreshMainGrid) {
        tabContent.firstChild.firstChild.refreshMainGrid({
          DocCfgID: res.ObjType,
          ParentID: res.ParentID
        });
        console.log("else", tabContent.firstChild);
      }
    }
  }
  async function leaveTabChange(data) {
    let params = /* @__PURE__ */ new Map();
    params.set("prefix", "tables");
    params.set("comand", "LeaveTabChange");
    params.set("ID", GroupID);
    params.set("CLSID", data.CLSID);
    params.set("ProgID", data.Tag);
    params.set("Year", Date.year ? Date.year : "");
    params.set("Month", Date.month ? Date.month : "");
    const response = await AxiosRequest(true, params);
    return response;
  }
  return /* @__PURE__ */ jsxRuntimeExports.jsx(
    ContextMenu,
    {
      for: "grid",
      children: /* @__PURE__ */ jsxRuntimeExports.jsxs(
        Tabs,
        {
          scrollMode: "paging",
          id: "tabsDocumentDetails",
          animation: "simple",
          ref: tabsRef,
          onChange: onTabChange,
          tabPosition: "top",
          style: {
            borderBottom: "0px",
            height: "100%",
            width: "100%"
          },
          children: [
            tabs.current,
            portal
          ]
        },
        "tabsDocumentDetails"
      )
    }
  );
}
export {
  Leaves as L
};
//# sourceMappingURL=Leaves-BvV0zspE.js.map
