import {
  getRelatedVisitTask,
  getTableAnswerRowInfoList,
  getDicomReadingQuestionAnswer,
  getReadingQuestionAndAnswer,
  getReadingOrganList
}
  from '@/api/trials'
import { getReadingVisitStudyList } from '@/api/trials'
const hangingAgreement = [
  { name: 'A', row: 1, col: 1 },
  { name: 'A|A', row: 1, col: 2 },
  { name: 'A|B', row: 1, col: 2 },
  { name: 'A|A|A|A', row: 2, col: 2 }
]
const getDefaultState = () => {
  return {
    // visitTaskList: [],
    visitTaskList: sessionStorage.getItem('visitTaskList') ? JSON.parse(sessionStorage.getItem('visitTaskList')) : [],
    organList: [],
    seriesStack: [],
    activeHangingAgreement: hangingAgreement[0],
    currentTaskId: '',
    currentReadingTaskState: 2,
    activeSeries: {},
    lastCanvasTaskId: ''
  }
}
function getQuestions(questions) {
  questions.forEach(item => {
    if (item.Type === 'table' && item.TableQuestions && item.TableQuestions.Answers.length > 0) {
      item.TableQuestions.Answers.forEach(answerObj => {
        answerObj.lesionPart = getQuestionAnswer(item.TableQuestions.Questions, 8, answerObj)
        answerObj.loctation = getQuestionAnswer(item.TableQuestions.Questions, 6, answerObj)
        answerObj.lesionLength = getQuestionAnswer(item.TableQuestions.Questions, 0, answerObj)
        answerObj.lesionShort = getQuestionAnswer(item.TableQuestions.Questions, 1, answerObj)
        answerObj.isDicomReading = answerObj.IsDicomReading === 'True'
        var isLymphLesion = getQuestionAnswer(item.TableQuestions.Questions, 2, answerObj)
        isLymphLesion = isLymphLesion ? parseInt(isLymphLesion) : null
        answerObj.isLymphLesion = isLymphLesion
        answerObj.lesionState = getQuestionAnswer(item.TableQuestions.Questions, 7, answerObj)
        var lesionNum = getQuestionAnswer(item.TableQuestions.Questions, 11, answerObj)
        answerObj.lesionNum = lesionNum
        if (answerObj.RowId) {
          var idx = item.TableQuestions.Questions.findIndex(i => i.QuestionMark === 11)
          if (idx > -1) {
            // pcwg
            answerObj.saveTypeEnum = isNaN(parseInt(answerObj.lesionNum)) ? 1 : 2
          } else {
            answerObj.saveTypeEnum = isNaN(parseInt(answerObj.lesionState)) ? 1 : 2
          }
        } else {
          answerObj.saveTypeEnum = 0
        }
      })
    }
    if (item.Childrens.length > 0) {
      getQuestions(item.Childrens)
    }
  })
  return questions
}
function findQuestionAndRemoveLesion(questions, obj) {
  for (var i = 0; i < questions.length; i++) {
    if (questions[i].Type === 'table' && questions[i].TableQuestions && (questions[i].LesionType === obj.lesionType) && questions[i].TableQuestions.Answers.length > 0) {
      var idx = questions[i].TableQuestions.Answers.findIndex(i => String(i.RowIndex) === String(obj.rowIndex))
      if (idx > -1) {
        questions[i].TableQuestions.Answers.splice(idx, 1)
        break
      }
    }
    if (questions[i].Childrens.length > 0) {
      findQuestionAndRemoveLesion(questions[i].Childrens, obj)
    }
  }
  return questions
}
function findQuestionAndUpdateLesion(questions, obj) {
  for (var i = 0; i < questions.length; i++) {
    var item = questions[i]
    if (item.Type === 'table' && item.Id === obj.questionId) {
      var idx = item.TableQuestions.Answers.findIndex(i => i.RowIndex === obj.rowIndex)
      item.TableQuestions.Answers[idx].isLymphLesion = obj.isLymphLesion
      item.TableQuestions.Answers[idx].loctation = obj.lesionOrgan
      item.TableQuestions.Answers[idx].lesionPart = obj.lesionPart
      item.TableQuestions.Answers[idx].lesionLength = obj.lesionLength
      item.TableQuestions.Answers[idx].lesionShort = obj.lesionShort
      item.TableQuestions.Answers[idx].lesionNum = obj.lesionNum
      item.TableQuestions.Answers[idx].saveTypeEnum = obj.saveTypeEnum
      item.TableQuestions.Answers[idx].lesionState = obj.lesionState
      for (const i in obj.anwsers) {
        if (i === 'MeasureData' && obj.anwsers[i]) {
          item.TableQuestions.Answers[idx].InstanceId = obj.anwsers[i].instanceId
          item.TableQuestions.Answers[idx].SeriesId = obj.anwsers[i].seriesId
          item.TableQuestions.Answers[idx][i] = JSON.stringify(obj.anwsers[i])
        } else {
          item.TableQuestions.Answers[idx][i] = String(obj.anwsers[i])
        }
      }
      break
    }
    if (item.Childrens.length > 0) {
      this.findQuestionAndUpdateLesion(item.Childrens, obj)
    }
  }
  return questions
}
function findQuestionAndAddLesion(questions, obj) {
  for (var i = 0; i < questions.length; i++) {
    if (questions[i].Type === 'table' && questions[i].TableQuestions && (questions[i].LesionType === obj.lesionType)) {
      var sourceObj = {}
      questions[i].TableQuestions.Questions.forEach(item => {
        sourceObj[item.Id] = ''
      })
      var targetObj = Object.assign(sourceObj, obj.lesionObj)
      targetObj.IsCurrentTaskAdd = 'True'
      questions[i].TableQuestions.Answers.push(targetObj)
      break
    }
    if (questions[i].Childrens.length > 0) {
      findQuestionAndAddLesion(questions[i].Childrens, obj)
    }
  }
  return questions
}
function getQuestionAnswer(questions, questionMark, answers) {
  var idx = questions.findIndex(i => i.QuestionMark === questionMark)
  if (idx > -1) {
    var questionId = questions[idx].Id
    return answers[questionId]
  } else {
    return ''
  }
}

const state = getDefaultState

const mutations = {
}

const actions = {
  getOrganInfo({ state }, visitTaskId) {
    return new Promise(resolve => {
      getReadingOrganList({ visitTaskId: visitTaskId }).then(res => {
        state.organList = res.Result
        sessionStorage.setItem('organList', state.organList.length > 0 ? JSON.stringify(state.organList) : '')
        resolve()
      }).catch(() => { resolve() })
    })
  },
  getVisitTasks({ state }, visitTaskId) {
    return new Promise(resolve => {
      getRelatedVisitTask({ visitTaskId: visitTaskId }).then(res => {
        res.Result.forEach(item => {
          item.questionsInit = false
          item.readingQuestionsInit = false
          item.measureDataInit = false
          item.IsInit = false
        })
        state.visitTaskList = res.Result
        sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
        const currentTaskIdx = res.Result.findIndex(item => item.IsCurrentTask)
        if (currentTaskIdx > -1) {
          state.currentTaskId = res.Result[currentTaskIdx].VisitTaskId
          state.currentReadingTaskState = res.Result[currentTaskIdx].ReadingTaskState
        }
        resolve()
      }).catch(() => { resolve() })
    })
  },
  resetVisitTasks({ state }) {
    return new Promise(resolve => {
      sessionStorage.setItem('visitTaskList', '')
      state.visitTaskList = []
      state.currentTaskId = ''
      state.activeSeries = {}
      state.lastCanvasTaskId = ''
      resolve()
    })
  },
  getMasterSeries({ state }, obj) {
    return new Promise(resolve => {
      var seriesInfo = {}
      var i = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      getReadingVisitStudyList(obj.trialId, obj.visitId, obj.visitTaskId).then(res => {
        var studyList = state.visitTaskList[i].StudyList
        var idx = res.Result.findIndex(study => study.IsCriticalSequence)
        if (idx > -1) {
          var study = res.Result[idx]
          seriesInfo.StudyId = study.StudyId
          seriesInfo.StudyCode = study.StudyCode
          seriesInfo.Modalities = study.Modalities
          seriesInfo.SeriesCount = study.SeriesCount
          seriesInfo.InstanceCount = study.InstanceCount
          seriesInfo.InstanceCount = study.InstanceCount
          seriesInfo.IsDicom = study.IsDicom
          seriesInfo.PreviewImageCount = 0
          seriesInfo.IsCriticalSequence = study.IsCriticalSequence
          var seriesList = []
          study.SeriesList.forEach((series, index) => {
            const imageIds = []

            series.InstancePathList.forEach((path) => {
              imageIds.push(`wadouri:${localStorage.getItem('location') !== 'USA' ? process.env.VUE_APP_DICOM_PATH : process.env.VUE_APP_DICOM_USA_PATH}${path}`)
            })
            seriesList.push({
              isDicom: study.IsDicom,
              imageIds: imageIds,
              instanceList: series.InstanceList,
              seriesId: series.Id,
              imageIdIndex: 0,
              seriesUid: series.SeriesInstanceUid,
              seriesNumber: series.SeriesNumber,
              sliceThickness: series.SliceThickness,
              modality: series.Modality,
              description: series.Description,
              previewImageUrl: study.IsDicom ? `/api/series/preview/${series.Id}` : `/api/Common/LocalFilePreview?relativePath=${series.NoneDicomFileFirstFile}`,
              instanceCount: series.InstanceCount,
              prefetchInstanceCount: series.InstanceCount,
              loadStatus: true,
              imageloadedArr: series.InstanceList,
              studyId: study.StudyId,
              studyIndex: 0,
              seriesIndex: index,
              taskBlindName: state.visitTaskList[i].TaskBlindName,
              visitTaskId: obj.visitTaskId,
              readingTaskState: state.visitTaskList[i].ReadingTaskState,
              isBaseLineTask: state.visitTaskList[i].IsBaseLineTask,
              isCurrentTask: state.visitTaskList[i].IsCurrentTask,
              isLoading: false,
              isBeMark: series.IsBeMark
            })
          })
          seriesInfo.SeriesList = seriesList
          studyList.unshift(seriesInfo)
          studyList.forEach((study, sIdx) => {
            study.SeriesList.forEach(series => {
              series.studyIndex = sIdx
            })
          })
        }
        state.visitTaskList[i].StudyList = studyList
        resolve(seriesInfo)
      }).catch(() => { resolve() })
    })
  },
  getNextVisitTask({ state }, obj) {
    return new Promise(resolve => {
      getRelatedVisitTask({ visitTaskId: obj.visitTaskId }).then(res => {
        state.visitTaskList.forEach(item => {
          item.ReadingTaskState = 2
          item.IsCurrentTask = false
        })
        var idx = res.Result.findIndex(item => item.IsCurrentTask === true)
        if (idx > -1) {
          var obj = res.Result[idx]
          obj.questionsInit = false
          obj.readingQuestionsInit = false
          obj.measureDataInit = false
          obj.studyListInit = false
          obj.IsInit = false
          obj.MeasureData = []
          obj.Questions = []
          obj.ReadingQuestions = []
          obj.StudyList = []
          var i = state.visitTaskList.findIndex(i => i.VisitId === res.Result[idx].VisitId)
          if (i > -1) {
            state.visitTaskList.splice(i, 1)
          }
          state.visitTaskList.push(obj)
        }

        sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
        resolve()
      }).catch(() => { resolve() })
    })
  },
  setVisitTaskReadingTaskState({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      if (index > -1) {
        state.visitTaskList[index].ReadingTaskState = obj.readingTaskState
        state.visitTaskList[index].StudyList.forEach(study => {
          study.SeriesList.forEach(series => {
            series.readingTaskState = obj.readingTaskState
          })
        })
      }
      sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      resolve()
    })
  },

  getDicomReadingQuestionAnswer({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      if (state.visitTaskList[index].questionsInit) {
        resolve()
      } else {
        var params = {
          trialId: obj.trialId,
          visitTaskId: obj.visitTaskId
        }
        getDicomReadingQuestionAnswer(params).then(res => {
          state.visitTaskList[index].Questions = res.Result
          state.visitTaskList[index].questionsInit = true
          sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
          resolve()
        }).catch(() => { resolve() })
      }
    })
  },
  refreshDicomReadingQuestionAnswer({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)

      var params = {
        trialId: obj.trialId,
        visitTaskId: obj.visitTaskId
      }
      getDicomReadingQuestionAnswer(params).then(res => {
        state.visitTaskList[index].Questions = res.Result
        state.visitTaskList[index].questionsInit = true
        sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
        resolve()
      }).catch(() => { resolve() })
    })
  },
  getReadingQuestionAndAnswer({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      if (state.visitTaskList[index].readingQuestionsInit) {
        resolve()
      } else {
        var params = {
          trialId: obj.trialId,
          visitTaskId: obj.visitTaskId
        }
        getReadingQuestionAndAnswer(params).then(res => {
          var list = getQuestions(res.Result.SinglePage)
          state.visitTaskList[index].ReadingQuestions = list
          state.visitTaskList[index].readingQuestionsInit = true
          sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
          resolve()
        }).catch(() => { resolve() })
      }
    })
  },
  refreshReadingQuestionAndAnswer({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      var params = {
        trialId: obj.trialId,
        visitTaskId: obj.visitTaskId
      }
      getReadingQuestionAndAnswer(params).then(res => {
        var list = getQuestions(res.Result.SinglePage)
        state.visitTaskList[index].ReadingQuestions = list
        state.visitTaskList[index].readingQuestionsInit = true
        sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
        resolve()
      }).catch(() => { resolve() })
    })
  },
  setReadingQuestionAndAnswer({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      if (index > -1) {
        state.visitTaskList[index].ReadingQuestions = obj.questions
      }
      sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      resolve()
    })
  },
  addReadingQuestionAndAnswer({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      if (index > -1) {
        var questions = state.visitTaskList[index].ReadingQuestions
        questions = findQuestionAndAddLesion(questions, obj)
        state.visitTaskList[index].ReadingQuestions = questions
      }
      sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      resolve()
    })
  },
  updateReadingQuesstionAndAnswer({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      if (index > -1) {
        var questions = state.visitTaskList[index].ReadingQuestions
        questions = findQuestionAndUpdateLesion(questions, obj)
        state.visitTaskList[index].ReadingQuestions = questions
      }
      sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      resolve()
    })
  },
  removeReadingQuestionAndAnswer({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      if (index > -1) {
        var questions = state.visitTaskList[index].ReadingQuestions
        questions = findQuestionAndRemoveLesion(questions, obj)
        state.visitTaskList[index].ReadingQuestions = questions
      }
      sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      resolve()
    })
  },

  getMeasuredData({ state }, visitTaskId) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === visitTaskId)
      if (state.visitTaskList[index].measureDataInit) {
        resolve()
      } else {
        getTableAnswerRowInfoList(visitTaskId).then(res => {
          var arr = []
          res.Result.forEach(el => {
            if (el.MeasureData) {
              el.MeasureData = JSON.parse(el.MeasureData)

              el.MeasureData.data.remark = el.OrderMarkName
            }
            arr.push(el)
          })
          state.visitTaskList[index].MeasureData = arr
          state.visitTaskList[index].measureDataInit = true
          sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
          resolve()
        }).catch(() => { resolve() })
      }
    })
  },
  refreshMeasuredData({ state }, visitTaskId) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === visitTaskId)

      getTableAnswerRowInfoList(visitTaskId).then(res => {
        var arr = []
        res.Result.forEach(el => {
          if (el.MeasureData) {
            el.MeasureData = JSON.parse(el.MeasureData)

            el.MeasureData.data.remark = el.OrderMarkName
            arr.push(el)
          }
        })
        state.visitTaskList[index].MeasureData = arr
        state.visitTaskList[index].measureDataInit = true
        sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
        resolve()
      }).catch(() => { resolve() })
    })
  },
  getNoneDicomMeasuredData({ state }, visitTaskId) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === visitTaskId)
      var measureData = state.visitTaskList[index].MeasureData
      var noneDicomMeasureData = measureData.filter(item => !item.IsDicomReading)
      resolve(noneDicomMeasureData)
    })
  },
  addMeasuredData({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      var measureData = state.visitTaskList[index].MeasureData
      // var idx = measureData.findIndex(item => item.MeasureData.uuid === obj.data.MeasureData.data.uuid)
      var idx = measureData.findIndex(item => item.QuestionId === obj.data.QuestionId && item.RowIndex === obj.data.RowIndex)
      if (idx > -1) {
        for (const k in state.visitTaskList[index].MeasureData[idx]) {
          if (k !== 'Id' && obj.data[k]) {
            state.visitTaskList[index].MeasureData[idx][k] = obj.data[k]
          }
        }

        // state.visitTaskList[index].MeasureData[idx].MeasureData = obj.data.MeasureData
        console.log('更新标记成功', idx)
      } else {
        state.visitTaskList[index].MeasureData.push(obj.data)
        console.log('新增标记成功')
      }
      sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      resolve()
    })
  },
  removeMeasuredData({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      var measureData = state.visitTaskList[index].MeasureData

      // var uuid = obj.measureData.data.uuid
      // var idx = measureData.findIndex(item => item.MeasureData && item.MeasureData.data && item.MeasureData.data.uuid === uuid)
      var idx = measureData.findIndex(item => item.QuestionId === obj.questionId && item.RowIndex === obj.rowIndex)
      if (idx > -1) {
        measureData.splice(idx, 1)

        state.visitTaskList[index].MeasureData = measureData
        console.log('移除标记成功', idx)
      } else if (obj.orderMarkName) {
        const i = measureData.findIndex(item => item.QuestionId === obj.questionId && item.OrderMarkName === obj.orderMarkName)
        measureData.splice(i, 1)

        state.visitTaskList[index].MeasureData = measureData
      }
      sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      resolve()
    })
  },
  updateMeasureDataStatus({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      var measureData = state.visitTaskList[index].MeasureData
      var idx = measureData.findIndex(item => item.QuestionId === obj.questionId && item.RowIndex === obj.rowIndex)
      if (idx > -1 && measureData[idx].MeasureData) {
        measureData[idx].MeasureData.data.status = obj.status
        state.visitTaskList[index].MeasureData = measureData
      }
      sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      resolve()
    })
  },
  getStudyInfo({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      if (state.visitTaskList[index].studyListInit) {
        resolve()
      } else {
        var studyList = []
        // getVisitStudyList
        // getReadingVisitStudyList
        getReadingVisitStudyList(obj.trialId, obj.subjectVisitId, obj.visitTaskId).then(res => {
          res.Result.forEach((study, studyIndex) => {
            const data = {}
            data.StudyId = study.StudyId
            data.StudyCode = study.StudyCode
            data.Modalities = study.Modalities
            data.SeriesCount = study.SeriesCount
            data.InstanceCount = study.InstanceCount
            data.InstanceCount = study.InstanceCount
            data.IsDicom = study.IsDicom
            data.PreviewImageCount = 0
            data.IsCriticalSequence = study.IsCriticalSequence
            var seriesList = []
            study.SeriesList.forEach((series, seriesIndex) => {
              const imageIds = []
              try {
                // if (~window.location.href.indexOf('3c210000-3e2c-0016-4247-08dabf28e96b')) {
                series.InstancePathList.forEach((path) => {
                  // var path = id.split('/')[id.split('/').length - 1]
                  imageIds.push(`wadouri:${localStorage.getItem('location') !== 'USA' ? process.env.VUE_APP_DICOM_PATH : process.env.VUE_APP_DICOM_USA_PATH}${path}`)
                })
                // } else {
                //   series.InstanceList.forEach((id) => {
                //     imageIds.push(`wadouri:${process.env.VUE_APP_DICOM_PATH}/instance/content/${id}`)
                //   })
                // }
              } catch (e) {
                console.log(e)
              }
              seriesList.push({
                isDicom: study.IsDicom,
                imageIds: imageIds,
                instanceList: series.InstanceList,
                seriesId: series.Id,
                imageIdIndex: 0,
                seriesUid: series.SeriesInstanceUid,
                seriesNumber: series.SeriesNumber,
                sliceThickness: series.SliceThickness,
                modality: series.Modality,
                description: series.Description,
                previewImageUrl: study.IsDicom ? `/api/series/preview/${series.Id}` : `/api/Common/LocalFilePreview?relativePath=${series.NoneDicomFileFirstFile}`,
                instanceCount: series.InstanceCount,
                prefetchInstanceCount: 0,
                loadStatus: false,
                imageloadedArr: [],
                studyId: study.StudyId,
                studyIndex: studyIndex,
                seriesIndex: seriesIndex,
                taskBlindName: state.visitTaskList[index].TaskBlindName,
                visitTaskId: obj.visitTaskId,
                readingTaskState: state.visitTaskList[index].ReadingTaskState,
                isBaseLineTask: state.visitTaskList[index].IsBaseLineTask,
                isCurrentTask: state.visitTaskList[index].IsCurrentTask,
                isLoading: false,
                isBeMark: series.IsBeMark,
                ww: series.WindowWidth,
                wc: series.WindowCenter
              })
            })
            data.SeriesList = seriesList
            studyList.push(data)
          })
          state.visitTaskList[index].StudyList = studyList
          state.visitTaskList[index].studyListInit = true
          sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
          resolve()
        }).catch(() => { resolve() })
      }
    })
  },

  updateStudyList({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      var studyList = state.visitTaskList[index].StudyList || []
      if (studyList) {
        for (var i = 0; i < studyList.length; i++) {
          for (var j = 0; j < studyList[i].SeriesList.length; j++) {
            if (studyList[i].SeriesList[j].seriesUid === obj.seriesUid || !studyList[i].SeriesList[j].seriesUid) {
              var idx = studyList[i].SeriesList[j].imageIds.findIndex(image => image === obj.imageId)
              if (idx > -1 && studyList[i].SeriesList[j].imageloadedArr.indexOf(obj.imageId) < 0) {
                ++studyList[i].SeriesList[j].prefetchInstanceCount
                studyList[i].SeriesList[j].imageloadedArr.push(obj.imageId)
                // studyList[i].SeriesList[j].isLoading = true
                if (studyList[i].SeriesList[j].prefetchInstanceCount >= studyList[i].SeriesList[j].instanceCount) {
                  studyList[i].SeriesList[j].prefetchInstanceCount = studyList[i].SeriesList[j].instanceCount
                  // 设置当前序列状态为已下载完成
                  studyList[i].SeriesList[j].loadStatus = true
                }
              }
            }
          }
        }
      }
      state.visitTaskList[index].StudyList = studyList
      sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      resolve()
    })
  },

  setStatus({ state }, obj) {
    var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
    state.visitTaskList[index].IsInit = true
    sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
  },
  setActiveSeries({ state }, series) {
    return new Promise(resolve => {
      state.activeSeries = series
      resolve()
    })
  },
  setLastCanvasTaskId({ state }, taskId) {
    return new Promise(resolve => {
      state.lastCanvasTaskId = taskId
      resolve()
    })
  },
  setCurrentReadingTaskState({ state }, readingTaskState) {
    return new Promise(resolve => {
      state.currentReadingTaskState = readingTaskState
      resolve()
    })
  },
  setSeriesStack({ state }, seriesStack) {
    state.seriesStack = seriesStack
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

