import {nextTick, ref} from 'vue';

import {message} from 'ant-design-vue';
import {uploadChatFile} from "#/api/core/upload";
import { prepareImageForUpload } from '#/utils/prepare-image-upload';

export function useFileUpload() {
  const uploadPreview = ref(null);
  const imageInput = ref(null);
  const videoInput = ref(null);
  const currentFileType = ref('');

  const triggerFileInput = (type) => {
    currentFileType.value = type;

    nextTick(() => {
      if (type === 'image' && imageInput.value) {
        imageInput.value.value = '';
        imageInput.value.click();
      } else if (type === 'video' && videoInput.value) {
        videoInput.value.value = '';
        videoInput.value.click();
      }
    });
  };

  const handleFileUpload = async (event) => {
    if (!event.target.files || event.target.files.length === 0) return;

    const file = event.target.files[0];

    // 确定文件类型
    let detectedType = currentFileType.value;
    if (event.target === imageInput.value) {
      detectedType = 'image';
    } else if (event.target === videoInput.value) {
      detectedType = 'video';
    }

    // 文件大小检查
    const maxSize =
      detectedType === 'image' ? 10 * 1024 * 1024 : 50 * 1024 * 1024;
    if (file.size > maxSize) {
      const maxSizeMB = maxSize / 1024 / 1024;
      message.error(
        `文件大小超过限制！${detectedType === 'image' ? '图片' : '视频'}最大${maxSizeMB}MB`,
      );
      event.target.value = '';
      return;
    }

    // 文件类型检查
    const validImageTypes = [
      'image/jpeg',
      'image/jpg',
      'image/png',
      'image/gif',
      'image/webp',
      'image/bmp',
    ];
    const validVideoTypes = [
      'video/mp4',
      'video/avi',
      'video/mov',
      'video/wmv',
      'video/flv',
      'video/webm',
      'video/mkv',
    ];

    if (detectedType === 'image' && !validImageTypes.includes(file.type)) {
      message.error('请选择有效的图片格式 (JPEG, PNG, GIF, WebP, BMP)');
      event.target.value = '';
      return;
    }

    if (detectedType === 'video' && !validVideoTypes.includes(file.type)) {
      message.error(
        '请选择有效的视频格式 (MP4, AVI, MOV, WMV, FLV, WebM, MKV)',
      );
      event.target.value = '';
      return;
    }

    let uploadFile = file;
    let compressMeta = null;

    if (detectedType === 'image') {
      const prepared = await prepareImageForUpload(file);
      if (!prepared.file) {
        event.target.value = '';
        return;
      }
      uploadFile = prepared.file;
      compressMeta = prepared.meta;
    }

    uploadChatFile({
      file: uploadFile,
    }).then((res) => {
      uploadPreview.value = {
        type: detectedType,
        url: res.url,
        name: file.name,
        size: uploadFile.size,
        file: uploadFile,
        compressMeta,
      };
    });
    // const reader = new FileReader();
    // reader.addEventListener('load', (e) => {
    //   console.log(file, '上传file')
    //   console.log(e, '上传')
    //   uploadPreview.value = {
    //     type: detectedType,
    //     url: e.target.result,
    //     name: file.name,
    //     size: file.size,
    //     file,
    //   };
    // });
    //
    // console.log('上传文件')
    // reader.onerror = (error) => {
    //   console.error('文件读取失败:', error);
    //   message.error('文件读取失败，请重试');
    // };
    //
    // reader.readAsDataURL(file);
    event.target.value = '';
  };

  const cancelUpload = () => {
    uploadPreview.value = null;
  };

  return {
    uploadPreview,
    imageInput,
    videoInput,
    triggerFileInput,
    handleFileUpload,
    cancelUpload,
  };
}
