import { shallowMount } from '@vue/test-utils';

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

import FormulaForm from '../FormulaForm.vue';
import FormulaCatalogPage from '../index.vue';
import pageSource from '../index.vue?raw';

const apiMocks = vi.hoisted(() => ({ getFormulaPage: vi.fn() }));
const tableState = vi.hoisted(() => ({ config: undefined as any, reload: vi.fn() }));
const drawerState = vi.hoisted(() => ({ openDrawer: vi.fn() }));

vi.mock('#/api/x/eln/formulas', () => ({
  disableFormula: vi.fn(),
  enableFormula: vi.fn(),
  getFormulaPage: apiMocks.getFormulaPage,
}));
vi.mock('@jnpf/hooks', () => ({
  useMessage: () => ({ createMessage: { success: vi.fn(), warning: vi.fn() } }),
  usePermission: () => ({ hasBtnP: vi.fn(() => true) }),
}));
vi.mock('@jnpf/ui/form', () => ({
  BasicForm: { name: 'BasicForm', template: '<div />' },
  useForm: () => [vi.fn(), { getFieldsValue: () => ({}), resetFields: vi.fn() }],
}));
vi.mock('@jnpf/ui/modal', () => ({
  BasicModal: { name: 'BasicModal', template: '<div><slot /></div>' },
  useModal: () => [vi.fn(), { closeModal: vi.fn(), openModal: vi.fn() }],
}));
vi.mock('@jnpf/ui/drawer', () => ({ useDrawer: () => [vi.fn(), { openDrawer: drawerState.openDrawer }] }));
vi.mock('@jnpf/ui/vxeTable', () => ({
  BasicVxeTable: { name: 'BasicVxeTable', template: '<div><slot name="tableTitle" /><slot name="action" /></div>' },
  TableAction: { name: 'TableAction', template: '<div />' },
  useVxeTable: (config: any) => {
    tableState.config = config;
    return [vi.fn(), { reload: tableState.reload }];
  },
}));

describe('eLN formula catalog page', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    tableState.config = undefined;
    apiMocks.getFormulaPage.mockResolvedValue({ data: { list: [], pagination: { currentPage: 1, pageSize: 20, total: 0 } } });
  });

  it('initially loads the backend formula page and normalizes searches', async () => {
    shallowMount(FormulaCatalogPage, { global: { stubs: { 'a-button': true, 'a-form-item': true, 'a-tag': true, 'a-textarea': true } } });
    expect(tableState.config.immediate).toBe(true);
    const query = tableState.config.beforeFetch({ bizEnabled: 'enabled', currentPage: 2, keyword: '  含量计算 ', pageSize: 50 });
    expect(query).toEqual({ bizEnabled: 'enabled', currentPage: 2, keyword: '含量计算', pageSize: 50 });
    await tableState.config.api(query);
    expect(apiMocks.getFormulaPage).toHaveBeenCalledWith(query);
  });

  it('uses the platform low-code list skeleton and renders real reference count', () => {
    expect(pageSource).toContain('<div class="jnpf-content-wrapper">');
    expect(pageSource).toContain('<BasicForm');
    expect(pageSource).toContain('<BasicVxeTable');
    expect(pageSource).toContain("dataIndex: 'mubanYinyongShu'");
    expect(pageSource).not.toContain('a-card');
  });

  it('relies on menu reachability instead of button permissions', () => {
    expect(pageSource).not.toContain('usePermission');
    expect(pageSource).not.toContain('hasBtnP');
    expect(pageSource).not.toContain('auth:');
  });

  it('reloads and opens the returned V1 draft when the creation form emits created', async () => {
    const wrapper = shallowMount(FormulaCatalogPage, { global: { stubs: { 'a-button': true, 'a-form-item': true, 'a-tag': true, 'a-textarea': true } } });

    wrapper.findComponent(FormulaForm).vm.$emit('created', { id: 'formula-draft-1' });
    await wrapper.vm.$nextTick();

    expect(tableState.reload).toHaveBeenCalledTimes(1);
    expect(drawerState.openDrawer).toHaveBeenCalledWith(true, { formulaId: 'formula-draft-1', openDraft: true });
  });
});
