import { useDropZone } from '@vueuse/core'
import { getRandomStr, imageToBase64 } from '@/utils';
import { ElLoading } from 'element-plus'

const SUPPORT_FILE_TYPE = ['image/*', 'application/pdf']
export default function useDropFiles(elRef, callback) {
  useDropZone(elRef, onDrop);

  async function onDrop(files) {
    if (!Array.isArray(files) || files.length === 0) return;
    const validFiles = files.filter(file => SUPPORT_FILE_TYPE.some(i => new RegExp(i).test(file.type)));
    if (validFiles.length === 0) return;
    const loadingInstance = ElLoading.service({ fullscreen: true })
    const list = [];
    for (let file of validFiles) {
      const item = { file, type: file.type, size: file.size, name: file.name };
      if (/image\/*/.test(file.type)) {
        item.url = getRandomStr()
        const base64String = await imageToBase64(file);
        const base64WithPrefix = `data:${file.type};base64,${base64String}`;
        item.base64 = base64WithPrefix;
        item.isImage = true;
      } else if ('application/pdf' === file.type) {
        item.isPdf = true;
      }
      list.push(item);
    }
    loadingInstance.close()
    callback(list);
  }
}