import * as cornerstone from 'cornerstone-core'
var taskPool = [] // 请求池
let numRequest = 0 // 正在执行数量
const maxRequest = 1 // 可配置
let taskTimer // 轮询的定时器
var pendingList =[]
var cachedTask = {} // 存放的任务数据
const maxTask = 1
// var currentAutoLoadTaskStauts = false


// 预加载池的添加
function addTaskIntoPool(task) {
  return new Promise((resolve, reject) => {
    taskPool.forEach(task=>{
      task.priority = task.priority
    })
    const cache = cachedTask[task.key]
    const callback = (executeRes) => {
      if (executeRes.success) {
        resolve(executeRes.res)
      } else {
        reject(executeRes.err)
      }
    }
    const priority = task.priority || 0;
    if (cache) {
      cache.priority = priority
      task.callback =callback
    } else {
      task.callback =callback
      cachedTask[task.key] = task
      taskPool.push(task)
    }
  })
}
// 执行下载
function executeTask() {
  if (taskPool.length > 0) {
    // console.log(numRequest)
    numRequest = 0
    const executeRequest = maxRequest - numRequest

    if (executeRequest > 0) {

      for (let i = 0; i < executeRequest; i++) {
        sortTaskPool()

        const task = taskPool.shift()
        if (!task) {
          return
        }
        numRequest++
        task.execute().then((res) => {
          numRequest--
          task.callback({ success: true, res })
          executeTask()
        }, (err) => {
          numRequest--
          task.callback({ success: false,err })
          // delete cachedTask[task.key]
          executeTask()
        })
      }
    }
  } else if(pendingList.length > 0) {
    putPendingTaskIntoPool()
    executeTask()
  }else{
    startTaskTimer()
  }
}
function sortTaskPool() {
  if (taskPool.length > 0) {
    taskPool.sort((a, b) =>  b.priority-a.priority )

  }
}

// 轮询检查请求池中是否有请求需要执行
function startTaskTimer() {
  if(taskTimer){
    clearInterval(taskTimer)
    taskTimer = null
  }
  taskTimer = setInterval(() => {
    if (taskPool.length > 0) {
      stopTaskTimer()
      executeTask()
    }else{
      return
      // if(currentAutoLoadTaskStauts) return
      // 判断当前任务是否有序列未下载完成
      // var visitTaskList = sessionStorage.getItem('visitTaskList')
      // if(visitTaskList){
      //   visitTaskList = JSON.parse(visitTaskList)
      //   var idx = visitTaskList.findIndex(i => i.IsCurrentTask)
      //   var studyList = visitTaskList[idx].StudyList
      //   var series = getUnloadedSeries(studyList)
      //   if(series){
      //     var priority = Date.parse(new Date())
      //     series.imageIds.map(imageId => {
      //       loadAndCacheImagePlus(imageId,series.seriesId,priority)
      //     })
      //   }
      // }
    }
  }, 50)
}
// function getUnloadedSeries(studyList){
//   var series = null
//   for(var i = 0;i<studyList.length;i++){
//     var study = studyList[i]
//     var idx = study.SeriesList.findIndex(s=>{
//       var sliceThickness = isNaN(parseInt(s.sliceThickness)) ? null : parseInt(s.sliceThickness)
//       return (sliceThickness === 5 || s.instanceCount < 100) && !s.loadStatus
//     })
//     if(idx > -1){
//       series =  study.SeriesList[idx]
//       break
//     }
//   }
//   if(!series){
//     currentAutoLoadTaskStauts = true
//   }
//   return series
// }
// 停止轮询
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 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 resetRequestPool(){
  taskPool = []
  pendingList =[]
  cachedTask = {}
}
function setPendingList(arr){
  pendingList = [...arr]
  pendingList.sort((a, b) =>  b.priority-a.priority )
}
function putPendingTaskIntoPool(){
  if(pendingList.length > 0){
   var tasks =  pendingList.slice(0,maxTask)
   tasks.forEach(task=>{
    loadAndCacheImagePlus(task.imageId,task.seriesId,task.priority)
    var idx = pendingList.findIndex(i=>i.imageId===task.imageId)
    if(idx > -1){
      pendingList.splice(idx,1)
    }

   })
  }
}
// function updateTaskPriority(seriesId,priority){
//   if (taskPool.length > 0) {
//     for(var i =0; i<taskPool.length;i++){
//       if(taskPool[i] && taskPool[i].seriesId === seriesId){
//         taskPool[i].priority = priority
//       }else{
//         break
//       }
//     }
//   }
//   executeTask()
// }
function buildImageRequestTask(imageId,seriesId, config = {}) {
  return {
      key: imageId,
      seriesId:seriesId,
      ...config,
      execute: () => {
          return cornerstone.loadAndCacheImage(imageId)
      }
  };
}

export default {
  addTaskIntoPool,
  executeTask,
  startTaskTimer,
  stopTaskTimer,
  loadAndCacheImagePlus,
  removeTask,
  setPendingList,
  resetRequestPool
}
