/* @vitest-environment happy-dom */

import { flushPromises, mount } from '@vue/test-utils';
import { defineComponent, h } from 'vue';
import { createMemoryHistory, createRouter } from 'vue-router';

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

const viewMocks = vi.hoisted(() => ({
  requestClose: vi.fn(),
}));

vi.mock('#/router', () => ({
  router: { push: vi.fn(), replace: vi.fn() },
}));

vi.mock('@jnpf/hooks', () => ({
  useMessage: () => ({ createMessage: { warning: vi.fn() } }),
}));

vi.mock('@jnpf/ui/popup', async () => {
  const { defineComponent, h } = await import('vue');
  return {
    BasicPopup: defineComponent({
      name: 'BasicPopup',
      props: { loading: Boolean, open: Boolean },
      setup: (props) => () => h('section', { 'data-open': String(props.open), 'data-test': 'custom-view-popup' }),
    }),
  };
});

import { onlineUtils } from '#/utils/jnpf';

import GlobalCustomViewModal from '../index.vue';

describe('GlobalCustomViewModal', () => {
  let contentTarget: HTMLElement;

  beforeEach(() => {
    viewMocks.requestClose.mockReset();
    contentTarget = document.createElement('div');
    contentTarget.className = 'app-main';
    document.body.append(contentTarget);
  });

  afterEach(() => {
    vi.useRealTimers();
    contentTarget.remove();
  });

  it('切换菜单或页签前等待自定义页面完成关闭，拒绝关闭时取消导航', async () => {
    const Page = defineComponent({ setup: () => () => h('div') });
    const router = createRouter({
      history: createMemoryHistory(),
      routes: [
        { component: Page, path: '/result-entry' },
        { component: Page, path: '/result-review' },
      ],
    });
    await router.push('/result-entry');
    await router.isReady();
    const wrapper = mount(GlobalCustomViewModal, { global: { plugins: [router] } });

    onlineUtils.openCustomView({ page: 'x/eln/records/editor', title: '填写电子记录' });
    await flushPromises();
    expect(contentTarget.querySelector('[data-test="custom-view-popup"]')?.getAttribute('data-open')).toBe('true');
    (wrapper.vm as any).viewRef = { requestClose: viewMocks.requestClose };

    viewMocks.requestClose.mockResolvedValueOnce(false);
    await router.push('/result-review');
    await flushPromises();

    expect(router.currentRoute.value.fullPath).toBe('/result-entry');
    expect(contentTarget.querySelector('[data-test="custom-view-popup"]')?.getAttribute('data-open')).toBe('true');

    viewMocks.requestClose.mockResolvedValueOnce('pending');
    await router.push('/result-review');
    await flushPromises();

    expect(viewMocks.requestClose).toHaveBeenCalledTimes(2);
    expect(router.currentRoute.value.fullPath).toBe('/result-entry');
    expect(contentTarget.querySelector('[data-test="custom-view-popup"]')?.getAttribute('data-open')).toBe('true');

    await (wrapper.vm as any).handleCloseStarted();
    await (wrapper.vm as any).handleCloseReady();
    await flushPromises();

    expect(router.currentRoute.value.fullPath).toBe('/result-review');
    expect(contentTarget.querySelector('[data-test="custom-view-popup"]')?.getAttribute('data-open')).toBe('false');
    wrapper.unmount();
  });

  it('OnlyOffice 未确认关闭时让旧导航目标过期', async () => {
    const Page = defineComponent({ setup: () => () => h('div') });
    const router = createRouter({
      history: createMemoryHistory(),
      routes: [
        { component: Page, path: '/result-entry' },
        { component: Page, path: '/result-review' },
      ],
    });
    await router.push('/result-entry');
    await router.isReady();
    const wrapper = mount(GlobalCustomViewModal, { global: { plugins: [router] } });

    onlineUtils.openCustomView({ page: 'x/eln/records/editor', title: '填写电子记录' });
    await flushPromises();
    (wrapper.vm as any).viewRef = { requestClose: viewMocks.requestClose };
    viewMocks.requestClose.mockResolvedValueOnce('pending');
    vi.useFakeTimers();

    await router.push('/result-review');
    await flushPromises();
    await vi.advanceTimersByTimeAsync(30_001);
    await (wrapper.vm as any).handleCloseReady();
    await flushPromises();

    expect(router.currentRoute.value.fullPath).toBe('/result-entry');
    expect(contentTarget.querySelector('[data-test="custom-view-popup"]')?.getAttribute('data-open')).toBe('false');
    wrapper.unmount();
  });
});
