export const blobToJson = (blob) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()

    reader.onload = function (event) {
      const jsonString = event.target.result
      const jsonObject = JSON.parse(jsonString)
      resolve(jsonObject)
    }

    reader.onerror = function (error) {
      reject(error)
    }

    reader.readAsText(blob)
  })
}

// 判断是图片还是视频
export const checkIsImage = (url) => {
  var link = new URL(url)
  var path = link.pathname
  var extension = path.split('.').pop().toLowerCase()
  var imageExtensions = ['jpg', 'jpeg', 'gif', 'png']
  var videoExtensions = ['mp4', 'wmv', 'avi', 'mov']

  // 图片
  if (imageExtensions.includes(extension)) {
    return true
  }

  // 视频
  if (videoExtensions.includes(extension)) {
    return false
  }

  return null
}

// 预览文件
import { Base64 } from 'js-base64'
export const previewFile = (url) => {
  const baseUrl = import.meta.env.VITE_PREVIEW_URL
  window.open(`${baseUrl}/onlinePreview?url=${encodeURIComponent(Base64.encode(url))}`)
}

export const generateUUID = () => {
  var d = new Date().getTime()
  if (window.performance && typeof window.performance.now === "function") {
    d += performance.now(); //use high-precision timer if available
  }
  var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = (d + Math.random() * 16) % 16 | 0
    d = Math.floor(d / 16)
    return (c == 'x' ? r : (r & 0x3 | 0x8)).toString(16)
  })
  return uuid.replace(/-/g, "")
}