/* @vitest-environment happy-dom */

import { mount } from '@vue/test-utils';
import { defineComponent, h, KeepAlive, nextTick, ref } from 'vue';

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';

import Editor from '../Editor.vue';

const mocks = vi.hoisted(() => ({
  destroyEditor: vi.fn(),
  editorConfig: undefined as Record<string, any> | undefined,
  grabFocus: vi.fn(),
  requestClose: vi.fn(),
}));

vi.mock('../loadDocsApi', () => ({ loadDocsApi: vi.fn().mockResolvedValue(undefined) }));

describe('onlyOfficeEditor', () => {
  beforeEach(() => {
    mocks.destroyEditor.mockClear();
    mocks.grabFocus.mockClear();
    mocks.requestClose.mockClear();
    mocks.editorConfig = undefined;
    (window as any).DocsAPI = {
      DocEditor: vi.fn((_containerId: string, config: Record<string, any>) => {
        mocks.editorConfig = config;
        return { destroyEditor: mocks.destroyEditor, grabFocus: mocks.grabFocus, requestClose: mocks.requestClose };
      }),
    };
  });

  afterEach(() => {
    delete (window as any).DocsAPI;
  });

  it('将宿主关闭请求转发给 ONLYOFFICE 编辑器', async () => {
    const wrapper = mount(Editor, { props: { config: { document: { key: 'key-1' } } } });
    await nextTick();
    await nextTick();

    wrapper.vm.requestClose();

    expect(mocks.requestClose).toHaveBeenCalledTimes(1);
    wrapper.unmount();
  });

  it('恢复焦点使用文档API，销毁后不再操作旧编辑器', async () => {
    const wrapper = mount(Editor, { props: { config: { document: { key: 'key-1' } } } });
    await nextTick();
    await nextTick();
    const grabFocus = wrapper.vm.grabFocus;

    grabFocus();
    expect(mocks.grabFocus).toHaveBeenCalledTimes(1);
    expect(mocks.destroyEditor).not.toHaveBeenCalled();

    wrapper.unmount();
    grabFocus();
    expect(mocks.grabFocus).toHaveBeenCalledTimes(1);
  });

  it('文档由已修改恢复为未修改时只报告编辑状态', async () => {
    const wrapper = mount(Editor, { props: { config: { document: { key: 'key-1' } } } });
    await nextTick();
    await nextTick();

    mocks.editorConfig?.events.onDocumentStateChange({ data: true });
    mocks.editorConfig?.events.onDocumentStateChange({ data: false });

    expect(wrapper.emitted('modified')).toEqual([[true], [false]]);
    expect(wrapper.emitted('save')).toBeUndefined();
    expect(mocks.editorConfig?.events.onSaveDocument).toBeUndefined();
    wrapper.unmount();
  });

  it('切换 KeepAlive 缓存页时销毁 ONLYOFFICE 编辑器', async () => {
    const editorActive = ref(true);
    const OtherPage = defineComponent({ name: 'OtherPage', setup: () => () => h('div', '其他页面') });
    const Host = defineComponent({
      setup: () => () =>
        h(KeepAlive, null, {
          default: () => (editorActive.value ? h(Editor, { config: { document: { key: 'key-1' } } }) : h(OtherPage)),
        }),
    });
    const wrapper = mount(Host);
    await nextTick();
    await nextTick();

    expect((window as any).DocsAPI.DocEditor).toHaveBeenCalledTimes(1);
    expect(mocks.destroyEditor).not.toHaveBeenCalled();

    editorActive.value = false;
    await nextTick();

    expect(mocks.destroyEditor).toHaveBeenCalledTimes(1);

    editorActive.value = true;
    await nextTick();
    await nextTick();

    expect((window as any).DocsAPI.DocEditor).toHaveBeenCalledTimes(2);
    expect(mocks.destroyEditor).toHaveBeenCalledTimes(1);
    wrapper.unmount();
  });
});
