import { message,Upload } from 'antd';

// 验证上传文件大小是否符合要求
// 参数说明:
// file: 上传的文件
// maxSize: 最大文件大小
// type: 文件类型,支持*表示所有类型
const FileTypeMap = {
  'application/pdf': 'pdf',
  'image/jpeg': 'jpg',
  'image/png': 'png',
  'application/msword': 'doc',
  'application/zip': 'zip',
  'application/vnd.openxmlformats-officedocument.wordprocessingml.document': 'docx',
  'application/vnd.ms-excel': 'xls',
  'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet': 'xlsx',
  'application/vnd.ms-powerpoint': 'ppt',
  'application/vnd.openxmlformats-officedocument.presentationml.presentation': 'pptx',

}
export const validateFileSize = (file: File, maxSize: number,type: string[]) => {
  const { LIST_IGNORE } = Upload;
  const isLtMaxSize = file.size / 1024 / 1024 < maxSize;
  if (!isLtMaxSize) {
    message.error(`文件大小不能超过${maxSize}MB!`);
    return LIST_IGNORE;
  }
  const isValidFormat = type.includes('*') || type.includes(FileTypeMap[file.type as keyof typeof FileTypeMap]);
  if (!isValidFormat) {
    message.error(`只能上传${type.join(',')}格式文件!`);
    return LIST_IGNORE;
  }
  return isValidFormat && isLtMaxSize;
};


// 生成固定位数的 UUID
export const generateUUID = (length: number) => {
  // 使用更复杂的字符集
  const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const charactersLength = characters.length;

  // 使用加密安全的随机数生成
  let result = '';

  // 添加时间戳前缀，确保唯一性
  const timestamp = Date.now().toString(36);
  result += timestamp.substring(timestamp.length - Math.min(6, length / 4));

  // 获取随机字符
  const randomPart = [];
  if (typeof window !== 'undefined' && window.crypto && window.crypto.getRandomValues) {
    const array = new Uint8Array(length);
    window.crypto.getRandomValues(array);
    for (let i = 0; i < length - result.length; i++) {
      randomPart.push(characters.charAt(array[i] % charactersLength));
    }
  } else {
    for (let i = 0; i < length - result.length; i++) {
      randomPart.push(characters.charAt(Math.floor(Math.random() * charactersLength)));
    }
  }

  return result + randomPart.join('');
};
