/* @vitest-environment happy-dom */

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

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

import { normalizeOfficeDocumentConfig, resolveFileName, validateOfficeDocumentConfig } from '../helpers/officeDocument';

vi.mock('#/router', () => ({ router: { push: vi.fn() } }));
vi.mock('#/api/request', () => ({ defHttp: { get: vi.fn() } }));

const FILE = { fileId: 'file_001', name: '检验报告.docx' };

describe('onlineUtils.openOfficeDocument', () => {
  it('emits OPEN_OFFICE_DOCUMENT with config', () => {
    const emitter = onlineUtils.getEmitter();
    const listener = vi.fn();
    emitter.on('OPEN_OFFICE_DOCUMENT', listener);

    const config = { file: FILE, mode: 'view' as const };
    onlineUtils.openOfficeDocument(config);

    expect(listener).toHaveBeenCalledWith(config);
    emitter.off('OPEN_OFFICE_DOCUMENT', listener);
  });

  it('does not emit when fileId is missing', () => {
    const emitter = onlineUtils.getEmitter();
    const listener = vi.fn();
    const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
    emitter.on('OPEN_OFFICE_DOCUMENT', listener);

    onlineUtils.openOfficeDocument({ file: { name: '无 id.docx' } as any });

    expect(listener).not.toHaveBeenCalled();
    expect(errorSpy).toHaveBeenCalledWith('[onlineUtils.openOfficeDocument] file.fileId is required');
    emitter.off('OPEN_OFFICE_DOCUMENT', listener);
    errorSpy.mockRestore();
  });
});

describe('officeDocument helpers', () => {
  it('文件名缺失时从 url 兜底截取（后端靠扩展名定 documentType，丢了就打不开）', () => {
    expect(resolveFileName({ file: { fileId: 'f1', name: '' } } as any)).toBe('');
    expect(resolveFileName({ file: { fileId: 'f1', name: '', url: '/api/file/annex/a.docx?s=k' } } as any)).toBe('a.docx');
    expect(resolveFileName({ file: { fileId: 'f1', name: '', url: '/api/file/annex/noext' } } as any)).toBe('');
  });

  it('校验必填项', () => {
    expect(() => validateOfficeDocumentConfig({ file: { name: 'a.docx' } } as any)).toThrow('file.fileId is required');
    expect(() => validateOfficeDocumentConfig({ file: { fileId: 'f1', name: '' } } as any)).toThrow('file.name is required');
    expect(() => validateOfficeDocumentConfig({ file: FILE })).not.toThrow();
  });

  it('归一化：mode 默认 edit，标题默认取文件名', () => {
    expect(normalizeOfficeDocumentConfig({ file: FILE })).toMatchObject({ mode: 'edit', title: '检验报告.docx' });
    expect(normalizeOfficeDocumentConfig({ file: FILE, mode: 'view', title: ' 自定义 ' })).toMatchObject({
      mode: 'view',
      title: '自定义',
    });
    // 非法 mode 一律按 edit（最终以后端返回的模式为准，前端不做权限判断）
    expect(normalizeOfficeDocumentConfig({ file: FILE, mode: 'readonly' as any }).mode).toBe('edit');
  });
});
