
import { compressionThumbnail } from '@/utils/psdParser/compressor'

const fetchWithTimeout = (url:string, timeout:number)=>{
  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), timeout);

  return fetch(url, { signal: controller.signal })
    .then(response => {
      clearTimeout(timeoutId);
      return response;
    })
    .catch(error => {
      if (error.name === 'AbortError') {
        console.error('Request timed out');
      } else {
        console.error('Fetch error:', error.message);
      }
      throw error;
    });
}
class FileService {
  static downloadLinePdfAsync = async (id: any) => {
    let url = `${process.env.VUE_APP_PDF_URL}/api/pdf/${id}`
    try {
      const response = await fetchWithTimeout(url, 60*1000);
      // 处理响应
      if (response.ok) {
        return true
      } else {
        return false
      }
    } catch (error) {
      return false
    }
  }
  static getImageSizeWithoutDownloading = async (url: string): Promise<{ width: number; height: number }> => {
    const response = await fetch(url, { method: 'GET' }); // Use HEAD request to get metadata
    const contentLength = response.headers.get('Content-Length');

    if (!contentLength) {
      throw new Error('Unable to determine Content-Length');
    }

    const rangeEnd = Math.min(parseInt(contentLength, 10), 1024); // Read the first 1KB of data
    const partialResponse = await fetch(url, {
      headers: {
        Range: `bytes=0-${rangeEnd}`,
      },
    });

    const blob = await partialResponse.blob();
    const objectURL = URL.createObjectURL(blob);
    const image = new Image();

    return new Promise((resolve, reject) => {
      image.onload = () => {
        resolve({ width: image.width, height: image.height });
        URL.revokeObjectURL(objectURL);
      };

      image.onerror = reject;

      image.src = objectURL;
    });
  }

  static convertNetworkToBase64Async = async (url: string): Promise<{ width: number; height: number, url: string }> => {
    let result: { width: number; height: number, url: string } = {
      width: 0,
      height: 0,
      url: ''
    }
    const response = await fetch(url)
    const blob = await response.blob()
    const objectURL = URL.createObjectURL(blob);
    const image = new Image();
    return new Promise(async (resolve, reject) => {

      image.onload = () => {
        result.width = image.width
        result.height = image.height
        const reader = new FileReader();
        reader.onload = async (e) => {
          result.url = reader.result as string
          result.url = await compressionThumbnail(result.url, "image/jpeg", 0, 0.9)
          resolve(result)
        }
        reader.readAsDataURL(blob);
      };
      image.onerror = reject;

      image.src = objectURL;
    })
  }

  static downloadFileStreamAsync = async (url:string) => {
    const response = await fetch(url)
    const blob = await response.blob()
    let fileName = url.substring(url.lastIndexOf('/')+1,url.length)
    let file = new File([blob],fileName)
    return file
  }

  static notifyFontUpdateAsync = async (fileName:string)=>{
    await fetch(`${process.env.VUE_APP_PDF_URL}/api/file/downfont/`+fileName)
  }

  static uploadToFontServerAsync = async (file:File)=>{
      try {
        const formData = new FormData();
        formData.append('file', file);
    
        const response = await fetch(`${process.env.VUE_APP_PDF_URL}/api/file/uploadfont`, {
          method: 'POST',
          body: formData,
        });
        if(response.ok){
          let r = await response.text()
          if(r.indexOf('https://im.oytour.com')!=-1) return r
          return ''
        }
        return ''
      } catch (error) {
        return ''
      }
  }

  static checkDownloadRequestAsync = async (token:string) =>{
    const response = await fetch(`${process.env.VUE_APP_PDF_URL}/api/download/${token}/dw`, {method: 'GET'});
    if(response.ok){
      let r = await response.text()
      return JSON.parse(r)
    }
    return null
  }
}

export default FileService