import Viewer from 'viewerjs';
import 'viewerjs/dist/viewer.css';

interface PreviewOptions {
  toolbar?: boolean;
  navbar?: boolean;
  transition?: boolean;
  transitionDuration?: number;
  // 其他选项
}

export function previewImage(
  sources: string | File | (string | File)[],
  index = 0,
  options: PreviewOptions = {}
) {
  const container = document.createElement('div');
  container.style.display = 'none';
  document.body.appendChild(container);
  
  const processSource = async (source: string | File) => {
    const img = document.createElement('img');
    img.src = typeof source === 'string' 
      ? source 
      : await readFileAsDataURL(source);
    container.appendChild(img);
  };
  
  const readFileAsDataURL = (file: File): Promise<string> => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = e => resolve(e.target?.result as string);
      reader.onerror = reject;
      reader.readAsDataURL(file);
    });
  };
  
  Promise.all(
    (Array.isArray(sources) ? sources : [sources])
      .map(source => processSource(source))
  ).then(() => {
    const viewer = new Viewer(container, {
        zoomRatio: 0.8,
        transition: false,
        transitionDuration: 100, // 默认是300，设置更小的值可以加快动画速度
      ...options,
      hidden() {
        viewer.destroy();
        document.body.removeChild(container);
      },
    });
    viewer.view(index);
  });
}