import { ElMessage } from 'element-plus';
import { uploadFileApi, UPLOAD_BIZ_TYPE } from '@/api/minio';

type InsertImageFn = (url: string, alt?: string, href?: string) => void;
type InsertVideoFn = (url: string, poster?: string) => void;

const createUploadFileName = (fileName: string) => {
  const uuid = Math.random().toString(36).substring(2, 9);
  const timestamp = Date.now().toString();
  const random = Math.random().toString(36).substring(2, 4);
  const extension = fileName.split('.').pop();
  return extension ? `${uuid}-${timestamp}-${random}.${extension}` : `${uuid}-${timestamp}-${random}`;
};

const uploadEditorFile = async (file: File) => {
  const uploadName = createUploadFileName(file.name || 'editor-file');
  const res = await uploadFileApi({
    bizType: UPLOAD_BIZ_TYPE.ATTACHMENT,
    fileName: uploadName,
    file,
  });
  return res.url;
};

export const createWangEditorMenuConf = () => ({
  uploadImage: {
    async customUpload(file: File, insertFn: InsertImageFn) {
      try {
        const url = await uploadEditorFile(file);
        insertFn(url, file.name, url);
      } catch (error) {
        console.error('编辑器图片上传失败:', error);
        ElMessage.error('图片上传失败，请重试');
      }
    },
  },
  uploadVideo: {
    async customUpload(file: File, insertFn: InsertVideoFn) {
      try {
        const url = await uploadEditorFile(file);
        insertFn(url);
      } catch (error) {
        console.error('编辑器视频上传失败:', error);
        ElMessage.error('视频上传失败，请重试');
      }
    },
  },
});
