import { ICommandService as I, CanceledError as b, IUniverInstanceService as $, RichTextValue as j, DOCS_NORMAL_EDITOR_UNIT_ID_KEY as T, LifecycleService as ie, DisposableCollection as B, LifecycleStages as O, UniverInstanceType as oe, ILogService as U, toDisposable as C, awaitTime as se, InterceptorEffectEnum as ae, generateRandomId as ce } from "@univerjs/core";
import { FUniver as q, FEventName as de } from "@univerjs/core/facade";
import { RichTextEditingMutation as he } from "@univerjs/docs";
import { IRenderManagerService as S, DeviceInputEventType as z, SHEET_VIEWPORT_KEY as le, sheetContentViewportKeys as ge } from "@univerjs/engine-render";
import { SheetsSelectionsService as ue, COMMAND_LISTENER_SKELETON_CHANGE as ve, getSkeletonChangedEffectedRange as Se, SetWorksheetRowIsAutoHeightCommand as Ce, InterceptCellContentPriority as me, SheetInterceptorService as Ee, INTERCEPTOR_POINT as be } from "@univerjs/sheets";
import { SetCellEditVisibleOperation as f, IEditorBridgeService as R, SetZoomRatioCommand as A, HoverManagerService as p, DragManagerService as M, SheetScrollManagerService as x, SheetPasteShortKeyCommand as L, ISheetClipboardService as Q, SheetSkeletonManagerService as _, SHEET_VIEW_KEY as w, ISheetSelectionRenderService as y, SheetsScrollRenderController as pe, SetWorksheetColAutoWidthCommand as we, SetColumnHeaderHeightCommand as fe, SetRowHeaderWidthCommand as ke, SheetCanvasPopManagerService as N, CellAlertManagerService as Ie, IMarkSelectionService as _e, ISheetCellDropdownManagerService as Pe } from "@univerjs/sheets-ui";
import { FSheetHooks as W, FWorkbook as ee, FWorksheet as te, FPermission as re, FRange as ne } from "@univerjs/sheets/facade";
import { KeyCode as D, CutCommand as F, CopyCommand as V, PasteCommand as Z, IClipboardInterfaceService as Re, PLAIN_TEXT_CLIPBOARD_MIME_TYPE as K, HTML_CLIPBOARD_MIME_TYPE as Y, supportClipboardAPI as X, ISidebarService as He, IDialogService as Me, ComponentManager as J } from "@univerjs/ui";
import { filter as u, combineLatest as ye } from "rxjs";
class Ue extends q {
  // eslint-disable-next-line max-lines-per-function
  _initSheetUIEvent(e) {
    const r = e.get(I);
    this.registerEventHandler(
      this.Event.BeforeSheetEditStart,
      () => r.beforeCommandExecuted((t) => {
        if (t.id !== f.id) return;
        const i = this.getActiveSheet();
        if (!i) return;
        const { workbook: o, worksheet: s } = i, d = e.get(R), l = t.params, { visible: h, keycode: g, eventType: a } = l, n = d.getEditLocation();
        if (h) {
          const c = {
            row: n.row,
            column: n.column,
            eventType: a,
            keycode: g,
            workbook: o,
            worksheet: s,
            isZenEditor: !1
          };
          if (this.fireEvent(this.Event.BeforeSheetEditStart, c), c.cancel)
            throw new b();
        }
      })
    ), this.registerEventHandler(
      this.Event.BeforeSheetEditEnd,
      () => r.beforeCommandExecuted((t) => {
        if (t.id !== f.id) return;
        const i = this.getActiveSheet();
        if (!i) return;
        const { workbook: o, worksheet: s } = i, d = e.get(R), l = e.get($), h = t.params, { visible: g, keycode: a, eventType: n } = h, c = d.getEditLocation();
        if (!g) {
          const P = {
            row: c.row,
            column: c.column,
            eventType: n,
            keycode: a,
            workbook: o,
            worksheet: s,
            isZenEditor: !1,
            value: j.create(l.getUnit(T).getSnapshot()),
            isConfirm: a !== D.ESC
          };
          if (this.fireEvent(this.Event.BeforeSheetEditEnd, P), P.cancel)
            throw new b();
        }
      })
    ), this.registerEventHandler(
      this.Event.SheetEditStarted,
      () => r.onCommandExecuted((t) => {
        if (t.id !== f.id) return;
        const i = this.getCommandSheetTarget(t);
        if (!i) return;
        const { workbook: o, worksheet: s } = i, d = e.get(R), l = t.params, { visible: h, keycode: g, eventType: a } = l, n = d.getEditLocation();
        if (h) {
          const c = {
            row: n.row,
            column: n.column,
            eventType: a,
            keycode: g,
            workbook: o,
            worksheet: s,
            isZenEditor: !1
          };
          this.fireEvent(this.Event.SheetEditStarted, c);
        }
      })
    ), this.registerEventHandler(
      this.Event.SheetEditEnded,
      () => r.onCommandExecuted((t) => {
        if (t.id !== f.id) return;
        const i = this.getCommandSheetTarget(t);
        if (!i) return;
        const { workbook: o, worksheet: s } = i, d = e.get(R), l = t.params, { visible: h, keycode: g, eventType: a } = l, n = d.getEditLocation();
        if (!h) {
          const c = {
            row: n.row,
            column: n.column,
            eventType: a,
            keycode: g,
            workbook: o,
            worksheet: s,
            isZenEditor: !1,
            isConfirm: g !== D.ESC
          };
          this.fireEvent(this.Event.SheetEditEnded, c);
        }
      })
    ), this.registerEventHandler(
      this.Event.SheetEditChanging,
      () => r.onCommandExecuted((t) => {
        if (t.id !== he.id) return;
        const i = this.getActiveSheet();
        if (!i) return;
        const { workbook: o, worksheet: s } = i, d = e.get(R), l = e.get($), h = t.params;
        if (!d.isVisible().visible) return;
        const { unitId: g } = h;
        if (g === T) {
          const { row: a, column: n } = d.getEditLocation(), c = {
            workbook: o,
            worksheet: s,
            row: a,
            column: n,
            value: j.create(l.getUnit(T).getSnapshot()),
            isZenEditor: !1
          };
          this.fireEvent(this.Event.SheetEditChanging, c);
        }
      })
    ), this.registerEventHandler(
      this.Event.BeforeSheetZoomChange,
      () => r.beforeCommandExecuted((t) => {
        if (t.id !== A.id) return;
        const i = this.getCommandSheetTarget(t);
        if (!i) return;
        const { workbook: o, worksheet: s } = i, d = {
          zoom: t.params.zoomRatio,
          workbook: o,
          worksheet: s
        };
        if (this.fireEvent(this.Event.BeforeSheetZoomChange, d), d.cancel)
          throw new b();
      })
    ), this.registerEventHandler(
      this.Event.SheetZoomChanged,
      () => r.onCommandExecuted((t) => {
        if (t.id !== A.id) return;
        const i = this.getCommandSheetTarget(t);
        if (!i) return;
        const { workbook: o, worksheet: s } = i;
        this.fireEvent(this.Event.SheetZoomChanged, {
          zoom: s.getZoom(),
          workbook: o,
          worksheet: s
        });
      })
    );
  }
  // eslint-disable-next-line max-lines-per-function
  _initObserverListener(e) {
    const r = e.get(S), t = e.get(ie), i = new B();
    this.disposeWithMe(t.lifecycle$.subscribe((l) => {
      if (l !== O.Rendered) return;
      i.dispose();
      const h = e.get(p), g = e.get(M);
      h && (this.registerEventHandler(
        this.Event.CellClicked,
        () => {
          var a;
          return (a = h.currentClickedCell$) == null ? void 0 : a.pipe(u((n) => !!n)).subscribe((n) => {
            const c = this.getSheetTarget(n.location.unitId, n.location.subUnitId);
            c && this.fireEvent(this.Event.CellClicked, {
              ...c,
              ...n,
              row: n.location.row,
              column: n.location.col
            });
          });
        }
      ), this.registerEventHandler(
        this.Event.CellHover,
        () => {
          var a;
          return (a = h.currentRichText$) == null ? void 0 : a.pipe(u((n) => !!n)).subscribe((n) => {
            const c = this.getSheetTarget(n.unitId, n.subUnitId);
            c && this.fireEvent(this.Event.CellHover, {
              ...c,
              ...n,
              row: n.row,
              column: n.col
            });
          });
        }
      ), this.registerEventHandler(
        this.Event.CellPointerDown,
        () => {
          var a;
          return (a = h.currentPointerDownCell$) == null ? void 0 : a.pipe(u((n) => !!n)).subscribe((n) => {
            const c = this.getSheetTarget(n.unitId, n.subUnitId);
            c && this.fireEvent(this.Event.CellPointerDown, {
              ...c,
              ...n,
              row: n.row,
              column: n.col
            });
          });
        }
      ), this.registerEventHandler(
        this.Event.CellPointerUp,
        () => {
          var a;
          return (a = h.currentPointerUpCell$) == null ? void 0 : a.pipe(u((n) => !!n)).subscribe((n) => {
            const c = this.getSheetTarget(n.unitId, n.subUnitId);
            c && this.fireEvent(this.Event.CellPointerUp, {
              ...c,
              ...n,
              row: n.row,
              column: n.col
            });
          });
        }
      ), this.registerEventHandler(
        this.Event.CellPointerMove,
        () => {
          var a;
          return (a = h.currentCellPosWithEvent$) == null ? void 0 : a.pipe(u((n) => !!n)).subscribe((n) => {
            const c = this.getSheetTarget(n.unitId, n.subUnitId);
            c && this.fireEvent(this.Event.CellPointerMove, {
              ...c,
              ...n,
              row: n.row,
              column: n.col
            });
          });
        }
      ), this.registerEventHandler(
        this.Event.DragOver,
        () => {
          var a;
          return (a = g.currentCell$) == null ? void 0 : a.pipe(u((n) => !!n)).subscribe((n) => {
            const c = this.getSheetTarget(n.location.unitId, n.location.subUnitId);
            c && this.fireEvent(this.Event.DragOver, {
              ...c,
              ...n,
              row: n.location.row,
              column: n.location.col
            });
          });
        }
      ), this.registerEventHandler(
        this.Event.Drop,
        () => {
          var a;
          return (a = g.endCell$) == null ? void 0 : a.pipe(u((n) => !!n)).subscribe((n) => {
            const c = this.getSheetTarget(n.location.unitId, n.location.subUnitId);
            c && this.fireEvent(this.Event.Drop, {
              ...c,
              ...n,
              row: n.location.row,
              column: n.location.col
            });
          });
        }
      ), this.registerEventHandler(
        this.Event.RowHeaderClick,
        () => {
          var a;
          return (a = h.currentRowHeaderClick$) == null ? void 0 : a.pipe(u((n) => !!n)).subscribe((n) => {
            const c = this.getSheetTarget(n.unitId, n.subUnitId);
            c && this.fireEvent(this.Event.RowHeaderClick, {
              ...c,
              row: n.index
            });
          });
        }
      ), this.registerEventHandler(
        this.Event.RowHeaderPointerDown,
        () => {
          var a;
          return (a = h.currentRowHeaderPointerDown$) == null ? void 0 : a.pipe(u((n) => !!n)).subscribe((n) => {
            const c = this.getSheetTarget(n.unitId, n.subUnitId);
            c && this.fireEvent(this.Event.RowHeaderPointerDown, {
              ...c,
              row: n.index
            });
          });
        }
      ), this.registerEventHandler(
        this.Event.RowHeaderPointerUp,
        () => {
          var a;
          return (a = h.currentRowHeaderPointerUp$) == null ? void 0 : a.pipe(u((n) => !!n)).subscribe((n) => {
            const c = this.getSheetTarget(n.unitId, n.subUnitId);
            c && this.fireEvent(this.Event.RowHeaderPointerUp, {
              ...c,
              row: n.index
            });
          });
        }
      ), this.registerEventHandler(
        this.Event.RowHeaderHover,
        () => {
          var a;
          return (a = h.currentHoveredRowHeader$) == null ? void 0 : a.pipe(u((n) => !!n)).subscribe((n) => {
            const c = this.getSheetTarget(n.unitId, n.subUnitId);
            c && this.fireEvent(this.Event.RowHeaderHover, {
              ...c,
              row: n.index
            });
          });
        }
      ), this.registerEventHandler(
        this.Event.ColumnHeaderClick,
        () => {
          var a;
          return (a = h.currentColHeaderClick$) == null ? void 0 : a.pipe(u((n) => !!n)).subscribe((n) => {
            const c = this.getSheetTarget(n.unitId, n.subUnitId);
            c && this.fireEvent(this.Event.ColumnHeaderClick, {
              ...c,
              column: n.index
            });
          });
        }
      ), this.registerEventHandler(
        this.Event.ColumnHeaderPointerDown,
        () => {
          var a;
          return (a = h.currentColHeaderPointerDown$) == null ? void 0 : a.pipe(u((n) => !!n)).subscribe((n) => {
            const c = this.getSheetTarget(n.unitId, n.subUnitId);
            c && this.fireEvent(this.Event.ColumnHeaderPointerDown, {
              ...c,
              column: n.index
            });
          });
        }
      ), this.registerEventHandler(
        this.Event.ColumnHeaderPointerUp,
        () => {
          var a;
          return (a = h.currentColHeaderPointerUp$) == null ? void 0 : a.pipe(u((n) => !!n)).subscribe((n) => {
            const c = this.getSheetTarget(n.unitId, n.subUnitId);
            c && this.fireEvent(this.Event.ColumnHeaderPointerUp, {
              ...c,
              column: n.index
            });
          });
        }
      ), this.registerEventHandler(
        this.Event.ColumnHeaderHover,
        () => {
          var a;
          return (a = h.currentHoveredColHeader$) == null ? void 0 : a.pipe(u((n) => !!n)).subscribe((n) => {
            const c = this.getSheetTarget(n.unitId, n.subUnitId);
            c && this.fireEvent(this.Event.ColumnHeaderHover, {
              ...c,
              column: n.index
            });
          });
        }
      ));
    })), this.disposeWithMe(i);
    const o = /* @__PURE__ */ new Map();
    let s;
    const d = ye([
      r.created$,
      t.lifecycle$
    ]);
    this.disposeWithMe(d.subscribe(([l, h]) => {
      var P;
      if (l.type === oe.UNIVER_SHEET && (s = l), h <= O.Rendered || !s) return;
      const g = new B(), a = this.getWorkbook(s.unitId);
      if (!a) return;
      o.get(s.unitId) && ((P = o.get(s.unitId)) == null || P.dispose()), o.set(s.unitId, g);
      const n = s.with(x), c = s.with(ue);
      g.add(this.registerEventHandler(
        this.Event.Scroll,
        () => n.validViewportScrollInfo$.subscribe((v) => {
          v && this.fireEvent(this.Event.Scroll, {
            workbook: a,
            worksheet: a.getActiveSheet(),
            ...v
          });
        })
      )), g.add(this.registerEventHandler(
        this.Event.SelectionMoveStart,
        () => c.selectionMoveStart$.subscribe((v) => {
          var m;
          this.fireEvent(this.Event.SelectionMoveStart, {
            workbook: a,
            worksheet: a.getActiveSheet(),
            selections: (m = v == null ? void 0 : v.map((k) => k.range)) != null ? m : []
          });
        })
      )), g.add(this.registerEventHandler(
        this.Event.SelectionMoving,
        () => c.selectionMoving$.subscribe((v) => {
          var m;
          this.fireEvent(this.Event.SelectionMoving, {
            workbook: a,
            worksheet: a.getActiveSheet(),
            selections: (m = v == null ? void 0 : v.map((k) => k.range)) != null ? m : []
          });
        })
      )), g.add(this.registerEventHandler(
        this.Event.SelectionMoveEnd,
        () => c.selectionMoveEnd$.subscribe((v) => {
          var m;
          this.fireEvent(this.Event.SelectionMoveEnd, {
            workbook: a,
            worksheet: a.getActiveSheet(),
            selections: (m = v == null ? void 0 : v.map((k) => k.range)) != null ? m : []
          });
        })
      )), g.add(this.registerEventHandler(
        this.Event.SelectionChanged,
        () => c.selectionChanged$.subscribe((v) => {
          var m;
          this.fireEvent(this.Event.SelectionChanged, {
            workbook: a,
            worksheet: a.getActiveSheet(),
            selections: (m = v == null ? void 0 : v.map((k) => k.range)) != null ? m : []
          });
        })
      )), s = null, this.disposeWithMe(g);
    })), this.disposeWithMe(r.disposed$.subscribe((l) => {
      var h;
      (h = o.get(l)) == null || h.dispose(), o.delete(l);
    })), this.disposeWithMe(() => {
      o.forEach((l) => {
        l.dispose();
      });
    });
  }
  /**
   * @ignore
   */
  _initialize(e) {
    this._initSheetUIEvent(e), this._initObserverListener(e);
    const r = e.get(I);
    this.registerEventHandler(
      this.Event.BeforeClipboardChange,
      () => r.beforeCommandExecuted((t) => {
        switch (t.id) {
          case V.id:
          case F.id:
            this._beforeClipboardChange();
            break;
        }
      })
    ), this.registerEventHandler(
      this.Event.ClipboardChanged,
      () => r.onCommandExecuted((t) => {
        switch (t.id) {
          case V.id:
          case F.id:
            this._clipboardChanged();
            break;
        }
      })
    ), this.registerEventHandler(
      this.Event.BeforeClipboardPaste,
      () => r.beforeCommandExecuted((t) => {
        switch (t.id) {
          case L.id:
            this._beforeClipboardPaste(t.params);
            break;
          case Z.id:
            this._beforeClipboardPasteAsync();
            break;
        }
      })
    ), this.registerEventHandler(
      this.Event.ClipboardPasted,
      () => r.onCommandExecuted((t) => {
        switch (t.id) {
          case L.id:
            this._clipboardPaste(t.params);
            break;
          case Z.id:
            this._clipboardPasteAsync();
            break;
        }
      })
    ), this.registerEventHandler(
      this.Event.SheetSkeletonChanged,
      () => r.onCommandExecuted((t) => {
        if (ve.indexOf(t.id) > -1) {
          const i = this.getActiveSheet();
          if (!i) return;
          const o = Se(t, i.worksheet.getMaxColumns()).map((s) => {
            var d, l;
            return (l = (d = this.getWorkbook(s.unitId)) == null ? void 0 : d.getSheetBySheetId(s.subUnitId)) == null ? void 0 : l.getRange(s.range);
          }).filter(Boolean);
          if (!o.length) return;
          this.fireEvent(this.Event.SheetSkeletonChanged, {
            workbook: i.workbook,
            worksheet: i.worksheet,
            payload: t,
            skeleton: i.worksheet.getSkeleton(),
            effectedRanges: o
          });
        }
      })
    );
  }
  _generateClipboardCopyParam() {
    const e = this.getActiveWorkbook(), r = e == null ? void 0 : e.getActiveSheet(), t = e == null ? void 0 : e.getActiveRange();
    if (!e || !r || !t)
      return;
    const o = this._injector.get(Q).generateCopyContent(e.getId(), r.getSheetId(), t.getRange());
    if (!o)
      return;
    const { html: s, plain: d } = o;
    return {
      workbook: e,
      worksheet: r,
      text: d,
      html: s,
      fromSheet: r,
      fromRange: t
    };
  }
  _beforeClipboardChange() {
    const e = this._generateClipboardCopyParam();
    if (e && (this.fireEvent(this.Event.BeforeClipboardChange, e), e.cancel))
      throw new b();
  }
  _clipboardChanged() {
    const e = this._generateClipboardCopyParam();
    e && this.fireEvent(this.Event.ClipboardChanged, e);
  }
  _generateClipboardPasteParam(e) {
    if (!e)
      return;
    const { htmlContent: r, textContent: t } = e, i = this.getActiveWorkbook(), o = i == null ? void 0 : i.getActiveSheet();
    return !i || !o ? void 0 : {
      workbook: i,
      worksheet: o,
      text: t,
      html: r
    };
  }
  async _generateClipboardPasteParamAsync() {
    const e = this.getActiveWorkbook(), r = e == null ? void 0 : e.getActiveSheet();
    if (!e || !r)
      return;
    const o = (await this._injector.get(Re).read())[0];
    let s;
    if (o) {
      const d = o.types, l = d.indexOf(K) !== -1 ? await o.getType(K).then((g) => g && g.text()) : "", h = d.indexOf(Y) !== -1 ? await o.getType(Y).then((g) => g && g.text()) : "";
      s = {
        workbook: e,
        worksheet: r,
        text: l,
        html: h
      };
    }
    return s;
  }
  _beforeClipboardPaste(e) {
    const r = this._generateClipboardPasteParam(e);
    if (r && (this.fireEvent(this.Event.BeforeClipboardPaste, r), r.cancel))
      throw new b();
  }
  _clipboardPaste(e) {
    const r = this._generateClipboardPasteParam(e);
    if (r && (this.fireEvent(this.Event.ClipboardPasted, r), r.cancel))
      throw new b();
  }
  async _beforeClipboardPasteAsync() {
    if (!X()) {
      this._injector.get(U).warn("[Facade]: The navigator object only supports the browser environment");
      return;
    }
    const e = await this._generateClipboardPasteParamAsync();
    if (e && (this.fireEvent(this.Event.BeforeClipboardPaste, e), e.cancel))
      throw new b();
  }
  async _clipboardPasteAsync() {
    if (!X()) {
      this._injector.get(U).warn("[Facade]: The navigator object only supports the browser environment");
      return;
    }
    const e = await this._generateClipboardPasteParamAsync();
    if (e && (this.fireEvent(this.Event.ClipboardPasted, e), e.cancel))
      throw new b();
  }
  customizeColumnHeader(e) {
    var h, g;
    const r = this.getActiveWorkbook();
    if (!r) {
      console.error("WorkBook not exist");
      return;
    }
    const t = r == null ? void 0 : r.getId(), i = this._injector.get(S), o = r.getActiveSheet(), s = o.getSheetId(), d = i.getRenderById(t);
    d && ((h = e.headerStyle) != null && h.size) && (d.with(_).setColumnHeaderSize(d, s, (g = e.headerStyle) == null ? void 0 : g.size), o == null || o.refreshCanvas()), this._getSheetRenderComponent(t, w.COLUMN).setCustomHeader(e), o == null || o.refreshCanvas();
  }
  customizeRowHeader(e) {
    const r = this.getActiveWorkbook();
    if (!r) {
      console.error("WorkBook not exist");
      return;
    }
    const t = r == null ? void 0 : r.getId();
    this._getSheetRenderComponent(t, w.ROW).setCustomHeader(e);
  }
  registerSheetRowHeaderExtension(e, ...r) {
    const t = this._getSheetRenderComponent(e, w.ROW), i = t.register(...r);
    return C(() => {
      i.dispose(), t.makeDirty(!0);
    });
  }
  registerSheetColumnHeaderExtension(e, ...r) {
    const t = this._getSheetRenderComponent(e, w.COLUMN), i = t.register(...r);
    return C(() => {
      i.dispose(), t.makeDirty(!0);
    });
  }
  registerSheetMainExtension(e, ...r) {
    const t = this._getSheetRenderComponent(e, w.MAIN), i = t.register(...r);
    return C(() => {
      i.dispose(), t.makeDirty(!0);
    });
  }
  /**
   * Get sheet render component from render by unitId and view key.
   * @private
   * @param {string} unitId The unit id of the spreadsheet.
   * @param {SHEET_VIEW_KEY} viewKey The view key of the spreadsheet.
   * @returns {Nullable<RenderComponentType>} The render component.
   */
  _getSheetRenderComponent(e, r) {
    const i = this._injector.get(S).getRenderById(e);
    if (!i)
      throw new Error(`Render Unit with unitId ${e} not found`);
    const { components: o } = i, s = o.get(r);
    if (!s)
      throw new Error("Render component not found");
    return s;
  }
  /**
   * Get sheet hooks.
   * @returns {FSheetHooks} FSheetHooks instance
   */
  getSheetHooks() {
    return this._injector.createInstance(W);
  }
}
q.extend(Ue);
class xe extends ee {
  openSiderbar(e) {
    return this._logDeprecation("openSiderbar"), this._injector.get(He).open(e);
  }
  openDialog(e) {
    this._logDeprecation("openDialog");
    const t = this._injector.get(Me).open({
      ...e,
      onClose: () => {
        t.dispose();
      }
    });
    return t;
  }
  _logDeprecation(e) {
    this._injector.get(U).warn("[FWorkbook]", `${e} is deprecated. Please use the function of the same name on "FUniver".`);
  }
  generateCellParams(e) {
    const r = this.getActiveSheet();
    return {
      row: e.row,
      column: e.col,
      workbook: this,
      worksheet: r
    };
  }
  onCellClick(e) {
    const r = this._injector.get(p);
    return C(
      r.currentClickedCell$.pipe(u((t) => !!t)).subscribe((t) => {
        e(t);
      })
    );
  }
  onCellHover(e) {
    const r = this._injector.get(p);
    return C(
      r.currentRichText$.pipe(u((t) => !!t)).subscribe(e)
    );
  }
  onCellPointerDown(e) {
    const r = this._injector.get(p);
    return C(
      r.currentPointerDownCell$.subscribe(e)
    );
  }
  onCellPointerUp(e) {
    const r = this._injector.get(p);
    return C(
      r.currentPointerUpCell$.subscribe(e)
    );
  }
  onCellPointerMove(e) {
    const r = this._injector.get(p);
    return C(
      r.currentCellPosWithEvent$.pipe(u((t) => !!t)).subscribe((t) => {
        e(t, t.event);
      })
    );
  }
  onDragOver(e) {
    const r = this._injector.get(M);
    return C(
      r.currentCell$.pipe(u((t) => !!t)).subscribe((t) => {
        e(t);
      })
    );
  }
  onDrop(e) {
    const r = this._injector.get(M);
    return C(
      r.endCell$.pipe(u((t) => !!t)).subscribe((t) => {
        e(t);
      })
    );
  }
  startEditing() {
    return this._injector.get(I).syncExecuteCommand(f.id, {
      eventType: z.Dblclick,
      unitId: this._workbook.getUnitId(),
      visible: !0
    });
  }
  async endEditing(e) {
    return this._injector.get(I).syncExecuteCommand(f.id, {
      eventType: z.Keyboard,
      keycode: e ? D.ENTER : D.ESC,
      visible: !1,
      unitId: this._workbook.getUnitId()
    }), await se(0), !0;
  }
  endEditingAsync(e = !0) {
    return this.endEditing(e);
  }
  abortEditingAsync() {
    return this.endEditingAsync(!1);
  }
  /**
   * Get scroll state of specified sheet.
   * @param {string} sheetId - sheet id
   * @returns {IScrollState} scroll state
   * @example
   * ``` ts
   * univerAPI.getActiveWorkbook().getScrollStateBySheetId($sheetId)
   * ```
   */
  getScrollStateBySheetId(e) {
    const r = this._workbook.getUnitId(), i = this._injector.get(S).getRenderById(r);
    return i ? i.with(x).getScrollStateByParam({ unitId: r, sheetId: e }) : null;
  }
  disableSelection() {
    const e = this._workbook.getUnitId(), t = this._injector.get(S).getRenderById(e);
    return t && t.with(y).disableSelection(), this;
  }
  enableSelection() {
    const e = this._workbook.getUnitId(), t = this._injector.get(S).getRenderById(e);
    return t && t.with(y).enableSelection(), this;
  }
  transparentSelection() {
    const e = this._workbook.getUnitId(), t = this._injector.get(S).getRenderById(e);
    return t && t.with(y).transparentSelection(), this;
  }
  showSelection() {
    const e = this._workbook.getUnitId(), t = this._injector.get(S).getRenderById(e);
    return t && t.with(y).showSelection(), this;
  }
}
ee.extend(xe);
class De extends te {
  refreshCanvas() {
    const e = this._injector.get(S), r = this._fWorkbook.id, t = e.getRenderById(r);
    if (!t)
      throw new Error(`Render Unit with unitId ${r} not found`);
    t.with(_).reCalculate();
    const i = t.mainComponent;
    if (!i)
      throw new Error("Main component not found");
    return i.makeDirty(), this;
  }
  zoom(e) {
    const r = this._injector.get(I), t = Math.min(Math.max(e, 0.1), 4);
    return r.executeCommand(A.id, {
      unitId: this._workbook.getUnitId(),
      subUnitId: this._worksheet.getSheetId(),
      zoomRatio: t
    }), this;
  }
  getZoom() {
    return this._worksheet.getZoomRatio();
  }
  getVisibleRange() {
    const e = this._workbook.getUnitId(), t = this._injector.get(S).getRenderById(e);
    let i = {
      startColumn: 0,
      startRow: 0,
      endColumn: 0,
      endRow: 0
    };
    if (!t) return i;
    const s = t.with(_).getCurrentSkeleton();
    if (!s) return i;
    const d = s == null ? void 0 : s.getVisibleRanges();
    if (!d) return i;
    i = s.getVisibleRangeByViewport(le.VIEW_MAIN);
    for (const [l, h] of d)
      ge.indexOf(l) !== -1 && (i.startColumn = Math.min(i.startColumn, h.startColumn), i.startRow = Math.min(i.startRow, h.startRow), i.endColumn = Math.max(i.endColumn, h.endColumn), i.endRow = Math.max(i.endRow, h.endRow));
    return i;
  }
  scrollToCell(e, r) {
    const t = this._workbook.getUnitId(), o = this._injector.get(S).getRenderById(t);
    return o && (o == null ? void 0 : o.with(pe)).scrollToCell(e, r), this;
  }
  getScrollState() {
    const e = {
      offsetX: 0,
      offsetY: 0,
      sheetViewStartColumn: 0,
      sheetViewStartRow: 0
    }, r = this._workbook.getUnitId(), t = this._worksheet.getSheetId(), o = this._injector.get(S).getRenderById(r);
    return o && o.with(x).getScrollStateByParam({ unitId: r, sheetId: t }) || e;
  }
  onScroll(e) {
    var o;
    const r = this._workbook.getUnitId(), i = (o = this._injector.get(S).getRenderById(r)) == null ? void 0 : o.with(x);
    if (i) {
      const s = i.validViewportScrollInfo$.subscribe((d) => {
        e(d);
      });
      return C(s);
    }
    return C(() => {
    });
  }
  getSkeleton() {
    var r, t;
    const e = (r = this._injector.get(S).getRenderById(this._workbook.getUnitId())) == null ? void 0 : r.with(_);
    return (t = e == null ? void 0 : e.getWorksheetSkeleton(this._worksheet.getSheetId())) == null ? void 0 : t.skeleton;
  }
  autoResizeColumn(e) {
    return this.autoResizeColumns(e, 1);
  }
  autoResizeColumns(e, r) {
    const t = this._workbook.getUnitId(), i = this._worksheet.getSheetId(), o = [
      {
        startColumn: e,
        endColumn: e + r - 1,
        startRow: 0,
        endRow: this._worksheet.getRowCount() - 1
      }
    ];
    return this._commandService.syncExecuteCommand(we.id, {
      unitId: t,
      subUnitId: i,
      ranges: o
    }), this;
  }
  setColumnAutoWidth(e, r) {
    return this.autoResizeColumns(e, r);
  }
  autoResizeRows(e, r) {
    const t = this._workbook.getUnitId(), i = this._worksheet.getSheetId(), o = [
      {
        startRow: e,
        endRow: e + r - 1,
        startColumn: 0,
        endColumn: this._worksheet.getColumnCount() - 1
      }
    ];
    return this._commandService.syncExecuteCommand(Ce.id, {
      unitId: t,
      subUnitId: i,
      ranges: o
    }), this;
  }
  customizeColumnHeader(e) {
    var l, h;
    const r = this, t = this._fWorkbook.getId(), i = this._injector.get(S), o = r.getSheetId(), s = i.getRenderById(t);
    s && ((l = e.headerStyle) != null && l.size) && (s.with(_).setColumnHeaderSize(s, o, (h = e.headerStyle) == null ? void 0 : h.size), r == null || r.refreshCanvas());
    const d = this._getSheetRenderComponent(t, w.COLUMN);
    d && (d.setCustomHeader(e), r == null || r.refreshCanvas());
  }
  customizeRowHeader(e) {
    const r = this._fWorkbook.getId();
    this._getSheetRenderComponent(r, w.ROW).setCustomHeader(e);
  }
  setColumnHeaderHeight(e) {
    const r = this, t = this._fWorkbook.getId(), i = r.getSheetId();
    return this._commandService.executeCommand(fe.id, {
      unitId: t,
      subUnitId: i,
      size: e
    }), r == null || r.refreshCanvas(), this;
  }
  setRowHeaderWidth(e) {
    const r = this, t = this._fWorkbook.getId(), i = r.getSheetId();
    this._commandService.executeCommand(ke.id, {
      unitId: t,
      subUnitId: i,
      size: e
    });
    const o = this._getSheetRenderComponent(t, w.ROW);
    return o && o.setCustomHeader({ headerStyle: { size: e } }), r == null || r.refreshCanvas(), this;
  }
  /**
   * Get sheet render component from render by unitId and view key.
   * @private
   * @param {string} unitId The unit id of the spreadsheet.
   * @param {SHEET_VIEW_KEY} viewKey The view key of the spreadsheet.
   * @returns {Nullable<RenderComponentType>} The render component.
   */
  _getSheetRenderComponent(e, r) {
    const i = this._injector.get(S).getRenderById(e);
    if (!i)
      throw new Error(`Render Unit with unitId ${e} not found`);
    const { components: o } = i, s = o.get(r);
    if (!s)
      throw new Error("Render component not found");
    return s;
  }
}
te.extend(De);
class Te extends re {
  setPermissionDialogVisible(e) {
    this._permissionService.setShowComponents(e);
  }
}
re.extend(Te);
class Be extends W {
  onCellPointerMove(e) {
    return C(this._injector.get(p).currentPosition$.subscribe(e));
  }
  onCellPointerOver(e) {
    return C(this._injector.get(p).currentCell$.subscribe(e));
  }
  onCellDragOver(e) {
    return C(this._injector.get(M).currentCell$.subscribe(e));
  }
  onCellDrop(e) {
    return C(this._injector.get(M).endCell$.subscribe(e));
  }
  onCellRender(e, r = ae.Style, t = me.DATA_VALIDATION) {
    return this._injector.get(Ee).intercept(be.CELL_CONTENT, {
      effect: r,
      handler: (i, o, s) => (i && !i.customRender && e && (i.customRender = [...e]), s(i)),
      priority: t
    });
  }
  onBeforeCellEdit(e) {
    return this._injector.get(I).beforeCommandExecuted((r) => {
      const t = r.params;
      r.id === f.id && t.visible && e(t);
    });
  }
  onAfterCellEdit(e) {
    return this._injector.get(I).onCommandExecuted((r) => {
      const t = r.params;
      r.id === f.id && !t.visible && e(t);
    });
  }
}
W.extend(Be);
const H = {
  CellClicked: "CellClicked",
  CellPointerDown: "CellPointerDown",
  CellPointerUp: "CellPointerUp",
  CellPointerMove: "CellPointerMove",
  CellHover: "CellHover"
};
class Ae {
  get BeforeClipboardChange() {
    return "BeforeClipboardChange";
  }
  get ClipboardChanged() {
    return "ClipboardChanged";
  }
  get BeforeClipboardPaste() {
    return "BeforeClipboardPaste";
  }
  get ClipboardPasted() {
    return "ClipboardPasted";
  }
  get BeforeSheetEditStart() {
    return "BeforeSheetEditStart";
  }
  get SheetEditStarted() {
    return "SheetEditStarted";
  }
  get SheetEditChanging() {
    return "SheetEditChanging";
  }
  get BeforeSheetEditEnd() {
    return "BeforeSheetEditEnd";
  }
  get SheetEditEnded() {
    return "SheetEditEnded";
  }
  get CellClicked() {
    return H.CellClicked;
  }
  get CellHover() {
    return H.CellHover;
  }
  get CellPointerDown() {
    return H.CellPointerDown;
  }
  get CellPointerUp() {
    return H.CellPointerUp;
  }
  get CellPointerMove() {
    return H.CellPointerMove;
  }
  get DragOver() {
    return "DragOver";
  }
  get Drop() {
    return "Drop";
  }
  get Scroll() {
    return "Scroll";
  }
  get SelectionMoveStart() {
    return "SelectionMoveStart";
  }
  get SelectionChanged() {
    return "SelectionChanged";
  }
  get SelectionMoving() {
    return "SelectionMoving";
  }
  get SelectionMoveEnd() {
    return "SelectionMoveEnd";
  }
  get RowHeaderClick() {
    return "RowHeaderClick";
  }
  get RowHeaderPointerDown() {
    return "RowHeaderPointerDown";
  }
  get RowHeaderPointerUp() {
    return "RowHeaderPointerUp";
  }
  get RowHeaderHover() {
    return "RowHeaderHover";
  }
  get ColumnHeaderClick() {
    return "ColumnHeaderClick";
  }
  get ColumnHeaderPointerDown() {
    return "ColumnHeaderPointerDown";
  }
  get ColumnHeaderPointerUp() {
    return "ColumnHeaderPointerUp";
  }
  get ColumnHeaderHover() {
    return "ColumnHeaderHover";
  }
  get SheetSkeletonChanged() {
    return "SheetSkeletonChanged";
  }
  get BeforeSheetZoomChange() {
    return "BeforeSheetZoomChange";
  }
  get SheetZoomChanged() {
    return "SheetZoomChanged";
  }
}
de.extend(Ae);
class We extends ne {
  getCell() {
    var d;
    const e = this._injector.get(S), r = this._injector.get(U), t = this._workbook.getUnitId(), i = this._worksheet.getSheetId(), o = e.getRenderById(t), s = (d = o == null ? void 0 : o.with(_).getSkeletonParam(i)) == null ? void 0 : d.skeleton;
    if (!s)
      throw r.error("[Facade]: `FRange.getCell` can only be called in current worksheet"), new Error("`FRange.getCell` can only be called in current worksheet");
    return s.getCellWithCoordByIndex(this._range.startRow, this._range.startColumn);
  }
  getCellRect() {
    const { startX: e, startY: r, endX: t, endY: i } = this.getCell(), o = { x: e, y: r, width: t - e, height: i - r, top: r, left: e, bottom: i, right: t };
    return { ...o, toJSON: () => JSON.stringify(o) };
  }
  generateHTML() {
    var t;
    const r = this._injector.get(Q).generateCopyContent(
      this._workbook.getUnitId(),
      this._worksheet.getSheetId(),
      this._range
    );
    return (t = r == null ? void 0 : r.html) != null ? t : "";
  }
  attachPopup(e) {
    var s, d, l;
    e.direction = (s = e.direction) != null ? s : "horizontal", e.extraProps = (d = e.extraProps) != null ? d : {}, e.offset = (l = e.offset) != null ? l : [0, 0];
    const { key: r, disposableCollection: t } = G(e, this._injector.get(J)), o = this._injector.get(N).attachPopupToCell(
      this._range.startRow,
      this._range.startColumn,
      { ...e, componentKey: r },
      this.getUnitId(),
      this._worksheet.getSheetId()
    );
    return o ? (t.add(o), t) : (t.dispose(), null);
  }
  attachAlertPopup(e) {
    const r = this._injector.get(Ie), t = {
      workbook: this._workbook,
      worksheet: this._worksheet,
      row: this._range.startRow,
      col: this._range.startColumn,
      unitId: this.getUnitId(),
      subUnitId: this._worksheet.getSheetId()
    };
    return r.showAlert({
      ...e,
      location: t
    }), {
      dispose: () => {
        r.removeAlert(e.key);
      }
    };
  }
  /**
   * attachDOMPopup
   * @param popup
   * @returns {IDisposable} disposable
      let sheet = univerAPI.getActiveWorkbook().getActiveSheet();
      let range = sheet.getRange(2, 2, 3, 3);
      univerAPI.getActiveWorkbook().setActiveRange(range);
      let disposable = range.attachDOMPopup({
      componentKey: 'univer.sheet.single-dom-popup',
      extraProps: { alert: { type: 0, title: 'This is an Info', message: 'This is an info message' } },
      });
   */
  attachRangePopup(e) {
    var s, d, l;
    e.direction = (s = e.direction) != null ? s : "top-center", e.extraProps = (d = e.extraProps) != null ? d : {}, e.offset = (l = e.offset) != null ? l : [0, 0];
    const { key: r, disposableCollection: t } = G(e, this._injector.get(J)), o = this._injector.get(N).attachRangePopup(
      this._range,
      { ...e, componentKey: r },
      this.getUnitId(),
      this._worksheet.getSheetId()
    );
    return o ? (t.add(o), t) : (t.dispose(), null);
  }
  highlight(e, r) {
    const t = this._injector.get(_e), i = t.addShape({ range: this._range, style: e, primary: r });
    if (!i)
      throw new Error("Failed to highlight current range");
    return C(() => {
      t.removeShape(i);
    });
  }
  showDropdown(e) {
    return this._injector.get(Pe).showDropdown(e);
  }
}
ne.extend(We);
function G(E, e) {
  const { componentKey: r, isVue3: t } = E;
  let i;
  const o = new B();
  return typeof r == "string" ? i = r : (i = `External_${ce(6)}`, o.add(e.register(i, r, { framework: t ? "vue3" : "react" }))), {
    key: i,
    disposableCollection: o
  };
}
export {
  G as transformComponentKey
};
