const CHUNK_SIZE = 1024*1024*5 // 5MB
const THREAD_COUNT = 12// 线程数量设置
/**
 * 将文件切片
 * @param file
 * @returns {Promise<void>}
 */
export  function cutFile(file){
    return new Promise((resolve, reject)=>{
        const chunkCount  = Math.ceil(file.size / CHUNK_SIZE);
        const threadChunkCount  = Math.ceil(chunkCount / THREAD_COUNT);
        let finishedCount = 0 ;//  记录完成的线程数量
        let result = []; // 存储分片结果
        for(let i =  0 ; i<Math.min(THREAD_COUNT,chunkCount);i++){
            // 创建对应数量的线程  分配任务
            const worker = new Worker('./worker.js',{
                type:'module'
            })
            let start = i*threadChunkCount
            let end = (i+1)*threadChunkCount
            if(end > chunkCount) end = chunkCount
            worker.postMessage({
                file,
                CHUNK_SIZE,
                startChunkIndex: start,
                endChunkIndex:end ,// (i+1) * threadChunckCount
            });
            // 汇总结束
            worker.onmessage= e=>{
                for(let  i = start ; i<end;i++){
                    result[i] = e.data[i-start];
                }
                worker.terminate(); //线程完成
                finishedCount++; //完成一个线程数量+1
                if(finishedCount == Math.min(THREAD_COUNT,chunkCount)){
                    // 函数结束
                    resolve(result)
                }
            }
        }
    })

}