import {ref} from 'vue'

function getFileFromBase64(base64URL, filename) {
    var arr = base64URL.split(","),
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
    while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename.split(".")[0]+".png", { type: "image/png" });
}


/**
 * 获取视频的第一帧图片
 */
export function useVideoThumbnail(){
    console.log('执行到了')
    const screenshot = ref()
    const videoDom = document.createElement('video')
    videoDom.setAttribute('crossOrigin', 'anonymous') //处理跨域 必须添加 否则 toDataURL toBlob 不生效
    videoDom.setAttribute('src', 'https://jtzx001.oss-accelerate.aliyuncs.com/huijiaoyan_test/20260114_50007/14091714_b39124aa-2380-4547-af97-06159fcf6e40.mp4')
    videoDom.currentTime = 1

    // document.body.appendChild(videoDom)

    console.log('视频元素',videoDom)
    videoDom.addEventListener('loadeddata',function(){
        console.log('加载了')

        let canvas = document.createElement('canvas')
        //使用视频的宽高作为canvas、预览图的宽高
        let width = videoDom.videoWidth 
        let height = videoDom.videoHeight
        canvas.width = width
        canvas.height = height
        console.log('画布宽度',width)
        console.log('画布高度',height)
            
        canvas?.getContext('2d')?.drawImage(videoDom, 0, 0, width, height) //绘制canvas
        
        let base64URL = canvas.toDataURL('image/jpeg') //转换为base64，图片格式默认为png，这里修改为jpeg
        
        // blob链接
        canvas.toBlob((blob)=>{
            let url = URL.createObjectURL(blob)
            screenshot.value = url
        })

        // base64链接
        //   screenshot.value = base64URL
        //   const imgfile = getFileFromBase64(base64URL,'截图.jpg')
        //   console.log('获取到的文件----',imgfile)
    })

    return screenshot
}