import * as cornerstone from 'cornerstone-core'
var taskPool = [] // 请求池
let numRequest = 0 // 正在执行数量
const maxRequest = 5 // 可配置
let taskTimer // 轮询的定时器
var cachedTask = {} // 存放的任务数据
let sortType = 1
var i= 0
let startExecuteTask = null
let endExecuteTask = performance.now()
// 执行下载
async function executeTask() {
  // console.log(taskPool)
  endExecuteTask = performance.now()
  i++
  stopTaskTimer()
  if (taskPool.length > 0) {
    // let startSortTime = performance.now()
    // if( sortType ){
    //   maxRequest = 6
    // }
    // let endSortTime = performance.now()
    var requestNum = Math.min(taskPool.length, maxRequest)
    const tasks = taskPool.splice(0, requestNum);

    const taskPromises = tasks.map((task) => {
      return task.execute().then((result) => {
        task.callback({ success: true, res: result })

      }).catch((error) => {
        task.callback({ success: true, err: error })
      })
    })
    // let starLoadTime = performance.now()
    await Promise.all(taskPromises)
    // let endLoadTime = performance.now()
    // let isTest = process.env.VUE_APP_OSS_PATH === '/test/dist'
    // if(i > 1 && isTest){
      
    //   console.log(`第${i}次:${startExecuteTask?endExecuteTask - startExecuteTask:0}:${endSortTime - startSortTime}:${endLoadTime - starLoadTime}`)
    // }
    
    // startExecuteTask = performance.now()
    executeTask()
  }else{
    startTaskTimer()
  }
 
}

function sortTaskPool() {
  if (taskPool.length > 0) {
    taskPool.sort((a, b) =>  b.priority-a.priority )
    
  }
}

// 轮询检查请求池中是否有请求需要执行
function startTaskTimer() {
  if (taskTimer) return; // 如果已存在定时器，则不重复启动

  taskTimer = setInterval(() => {
    if (taskPool.length > 0) {
      stopTaskTimer();
      executeTask();
    }
  }, 50);
}

// 停止轮询
function stopTaskTimer() {
  clearInterval(taskTimer)
  taskTimer = null
}
function loadAndCacheImagePlus(imageId,seriesId, priority) {
  return new Promise((resolve, reject) => {
    const imageLoadObject = cornerstone.imageCache.getImageLoadObject(imageId)
    if (imageLoadObject) {
      imageLoadObject.promise.then((image) => {
        resolve(image)
      }, (err) => {
        reject(err)
      })
    } else {
      const imageTask = buildImageRequestTask(imageId,seriesId, { priority })
      addTaskIntoPool(imageTask).then((res) => {
        resolve(res)
      }).catch(e => {
        reject(e)
      })
    }
  })
}
// 预加载池的添加
function addTaskIntoPool(task) {
  return new Promise((resolve, reject) => {
    const callback = (executeRes) => {
      if (executeRes.success) {
        resolve(executeRes.res)
      } else {
        reject(executeRes.err)
      }
    }
    task.callback =callback
      taskPool.push(task)
  })
}
function removeTask(seriesId){
  stopTaskTimer()
  if (taskPool.length > 0) {
    for(var i =taskPool.length-1; i>=0;i--){
      if(taskPool[i] && taskPool[i].seriesId === seriesId){
        delete cachedTask[taskPool[i].key]
        taskPool.splice(i,1)
       
      }
    }
    
  }
  startTaskTimer()
}
function changePriority(seriesId){
  taskPool.map(task=>{
    if(task.seriesId === seriesId){
      task.priority = parseInt(new Date().getTime()) * 10
    }
  })
  sortTaskPool()
}
function setSortType(type){
  sortType = type
}
function resetRequestPool(){
  taskPool = []
  cachedTask = {}
  sortType = 1
}
function resetCachedTask(){
  taskPool = []
  cachedTask = {}
}
function buildImageRequestTask(imageId,seriesId, config = {}) {
  return {
      key: imageId,
      seriesId:seriesId,
      ...config,
      execute: () => {
          return cornerstone.loadAndCacheImage(imageId)
      }
  };
}

export default {
  addTaskIntoPool,
  executeTask,
  setSortType,
  sortTaskPool,
  changePriority,
  startTaskTimer,
  stopTaskTimer,
  loadAndCacheImagePlus,
  removeTask,
  resetRequestPool,
  resetCachedTask
}
