import {
  getRelatedVisitTask,
  getTableAnswerRowInfoList,
  getDicomReadingQuestionAnswer,
  getReadingQuestionAndAnswer,
  getReadingOrganList,
  deleteCustomTag
}
  from '@/api/trials'
import Vue from 'vue'
import { getCustomTag } from '@/api/reading'

import requestPoolManager from '@/utils/request-pool'
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: '',
    imageQuality: null,
    imageQualityIssues: null,
    currentLoadIns: []
  }
}
function getQuestions(questions) {
  const criterionType = parseInt(localStorage.getItem('CriterionType'))
  questions.forEach(item => {
    if ((item.Type === 'table' || item.Type === 'basicTable') && item.TableQuestions && item.TableQuestions.Answers.length > 0) {
      item.TableQuestions.Answers.forEach(answerObj => {
        answerObj.isDicomReading = answerObj.IsDicomReading === 'True'

        if (answerObj.RowId) {
          if (criterionType === 10) {
            // pcwg
            var lesionNum = getQuestionAnswer(item.TableQuestions.Questions, 11, answerObj)
            answerObj.lesionNum = lesionNum
            answerObj.saveTypeEnum = isNaN(parseInt(answerObj.lesionNum)) ? 1 : 2
          } else if (criterionType === 19) {
            // ivus
            answerObj.area1 = getQuestionAnswer(item.TableQuestions.Questions, 1001, answerObj)
            answerObj.area2 = getQuestionAnswer(item.TableQuestions.Questions, 1002, answerObj)
            const v = getQuestionAnswer(item.TableQuestions.Questions, 1003, answerObj)
            answerObj.diff = v
            answerObj.saveTypeEnum = isNaN(parseFloat(v)) ? 1 : 2
          } else if (criterionType === 20) {
            // oct
            if (item.LesionType === 101) {
              answerObj.l1 = getQuestionAnswer(item.TableQuestions.Questions, 1011, answerObj)
              answerObj.l2 = getQuestionAnswer(item.TableQuestions.Questions, 1012, answerObj)
              answerObj.l3 = getQuestionAnswer(item.TableQuestions.Questions, 1013, answerObj)
              const min = getQuestionAnswer(item.TableQuestions.Questions, 1014, answerObj)
              answerObj.min = min
              const mean = getQuestionAnswer(item.TableQuestions.Questions, 1015, answerObj)
              answerObj.mean = mean
              answerObj.saveTypeEnum = (isNaN(parseFloat(min)) || isNaN(parseFloat(mean))) ? 1 : 2
            } else if (item.LesionType === 103) {
              const angle = getQuestionAnswer(item.TableQuestions.Questions, 1016, answerObj)
              answerObj.angle = angle
              answerObj.saveTypeEnum = isNaN(parseFloat(angle)) ? 1 : 2
            }
          } else {
            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)
            let isLymphLesion = getQuestionAnswer(item.TableQuestions.Questions, 2, answerObj)
            isLymphLesion = isLymphLesion ? parseInt(isLymphLesion) : null
            answerObj.isLymphLesion = isLymphLesion
            answerObj.lesionState = getQuestionAnswer(item.TableQuestions.Questions, 7, answerObj)
            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].Type === 'basicTable') && 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.Type === 'basicTable') && 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].Type === 'basicTable') && questions[i].TableQuestions && (questions[i].LesionType === obj.lesionType)) {
      var sourceObj = {}
      questions[i].TableQuestions.Questions.forEach(item => {
        sourceObj[item.Id] = null
      })
      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 ''
  }
}
// function getKeySeriesInfo(keyInstance, series) {
//   const obj = {}
//   const set = new Set()
//   var instances = series.instanceList.concat(keyInstance).filter((item) => {
//     if (set.has(item)) {
//       return true
//     } else {
//       set.add(item)
//       return false
//     }
//   })
//   instances.map(item => {
//     obj[item] = { seriesId: series.seriesId, studyIndex: series.studyIndex, seriesIndex: series.seriesIndex }
//   })
//   return obj
// }

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) {
    console.log('getVisitTasks')
    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 = ''
      state.imageQuality = null
      state.imageQualityIssues = null
      resolve()
    })
  },
  getMasterSeries({ state }, obj) {
    return new Promise(resolve => {
      console.log('getMasterSeries')
      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 = []
            const instanceList = []
            // series.InstancePathList.forEach((path) => {
            //   imageIds.push(`wadouri:${localStorage.getItem('location') !== 'USA' ? Vue.prototype.OSSclientConfig.basePath : Vue.prototype.OSSclientConfig.basePath}${path}`)
            // })
            series.InstanceInfoList.forEach(instance => {
              if (instance.NumberOfFrames && instance.NumberOfFrames > 1) {
                for (let i = 0; i < instance.NumberOfFrames; i++) {
                  const imageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? Vue.prototype.OSSclientConfig.basePath : Vue.prototype.OSSclientConfig.basePath}${instance.Path}?frame=${i}&instanceId=${instance.Id}&visitTaskId=${obj.visitTaskId}&idx=0|0`
                  imageIds.push(imageId)
                }
              } else {
                const imageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? Vue.prototype.OSSclientConfig.basePath : Vue.prototype.OSSclientConfig.basePath}${instance.Path}?instanceId=${instance.Id}&visitTaskId=${obj.visitTaskId}&idx=0|0`
                imageIds.push(imageId)
              }
              instance.ImageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? Vue.prototype.OSSclientConfig.basePath : Vue.prototype.OSSclientConfig.basePath}${instance.Path}?instanceId=${instance.Id}&visitTaskId=${obj.visitTaskId}&idx=0|0`
              instanceList.push(instance.Id)
            })
            seriesList.push({
              isDicom: study.IsDicom,
              imageIds: imageIds,
              instanceInfoList: series.InstanceInfoList,
              instanceList: instanceList,
              seriesId: series.Id,
              imageIdIndex: 0,
              seriesUid: series.SeriesInstanceUid,
              seriesNumber: series.SeriesNumber,
              sliceThickness: series.SliceThickness,
              modality: series.Modality,
              description: series.Description,
              previewImageUrl: study.IsDicom ? series.ImageResizePath ? Vue.prototype.OSSclientConfig.basePath + series.ImageResizePath : `/api/series/preview/${series.Id}` : Vue.prototype.OSSclientConfig.basePath + `${series.NoneDicomFileFirstFile}`,
              instanceHtmlPathList: series.InstanceHtmlPathList,
              instanceCount: series.InstanceCount,
              prefetchInstanceCount: series.InstanceCount,
              loadStatus: true,
              imageloadedArr: series.InstanceList,
              studyId: study.StudyId,
              studyIndex: 0,
              seriesIndex: index,
              studyCode: study.StudyCode,
              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.splice(i, 1, obj)
            requestPoolManager.resetCachedTask()
          } else {
            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
          state.visitTaskList[index].QuestionMarkInfoList = res.OtherInfo.QuestionMarkInfoList
          // 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
        state.visitTaskList[index].QuestionMarkInfoList = res.OtherInfo.QuestionMarkInfoList
        // 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()
    })
  },
  getCustomizeMeasuredData({ state }, visitTaskId) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === visitTaskId)
      if (state.visitTaskList[index].measureDataInit) {
        resolve()
      } else {
        getCustomTag({ visitTaskId: visitTaskId }).then(res => {
          var arr = []
          console.log(res.Result)
          res.Result.forEach(el => {
            if (el.MeasureData) {
              el.MeasureData = JSON.parse(el.MeasureData)
            }
            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() })
      }
    })
  },
  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
            }
            if (el.OtherMeasureData) {
              el.OtherMeasureData = JSON.parse(el.OtherMeasureData)
              el.OtherMeasureData.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() })
      }
    })
  },
  removeCustomizeMeasuredData({ state }, obj) {
    return new Promise(async resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      var measureData = state.visitTaskList[index].MeasureData
      console.log('removeCustomizeMeasuredData', obj, 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)
      // console.log(obj, measureData)
      if (obj.questionInfo.Id) {
        var idx = measureData.findIndex(item => item.Id === obj.questionInfo.Id)
        console.log('idx', idx)
        if (idx > -1) {
          if (measureData[idx].FristAddTaskId) {
            measureData[idx].MeasureData = ''
            console.log('清除标记成功', idx)
          } else {
            measureData.splice(idx, 1)
            console.log('移除标记成功', idx)
          }
          if (obj.questionInfo.Id && state.currentReadingTaskState < 2) {
            await deleteCustomTag(obj.questionInfo.Id)
          }
          state.visitTaskList[index].MeasureData = measureData
        }
      } else if (obj.orderMarkName) {
        const i = measureData.findIndex(item => item.MeasureData.data.remark === obj.orderMarkName)
        if (i > -1) {
          if (measureData[i].FristAddTaskId) {
            measureData[i].MeasureData = ''
            console.log('清除标记成功', i)
          } else {
            measureData.splice(i, 1)
            console.log('移除标记成功', i)
          }
        }
        if (obj.questionInfo.Id && state.currentReadingTaskState < 2) {
          await deleteCustomTag(obj.questionInfo.Id)
        }
        state.visitTaskList[index].MeasureData = measureData
      }
      // sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      resolve()
    })
  },
  refreshCustomizeMeasuredData({ state }, visitTaskId) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === visitTaskId)
      getCustomTag({ visitTaskId: visitTaskId }).then(res => {
        var arr = []
        console.log(res.Result)
        res.Result.forEach(el => {
          if (el.MeasureData) {
            el.MeasureData = JSON.parse(el.MeasureData)
          }
          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) : '')
      console.log(state.visitTaskList)
      resolve()
    })
  },
  addOrUpdateNonTargetMeasuredData({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      var measureData = state.visitTaskList[index].MeasureData
      console.log('addOrUpdateNonTargetMeasuredData')
      // item.MeasureData.data.remark === obj.orderMarkName
      var idx = measureData.findIndex(item => item.QuestionId === obj.data.QuestionId && item.OrderMarkName === obj.data.OrderMarkName)
      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]
          }
        }
        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()
    })
  },
  removeNonTargetMeasuredData({ state }, obj) {
    return new Promise(resolve => {
      console.log('removeNonTargetMeasuredData')
      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)
      if (idx > -1) {
        if (measureData[idx].FristAddTaskId) {
          measureData[idx].MeasureData = ''
          console.log('清除标记成功', idx)
        } else {
          measureData.splice(idx, 1)
          console.log('移除标记成功', idx)
        }
        state.visitTaskList[index].MeasureData = measureData
      }
      // sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      resolve()
    })
  },
  addCustomizeMeasuredData({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      var measureData = state.visitTaskList[index].MeasureData
      console.log(measureData, obj)
      // var idx = measureData.findIndex(item => item.MeasureData.uuid === obj.data.MeasureData.data.uuid)
      // if (!obj.questionInfo) {
      //   state.visitTaskList[index].MeasureData.push({
      //     MeasureData: obj,
      //     SeriesId: obj.seriesId,
      //     StudyId: obj.studyId,
      //     InstanceId: obj.instanceId,
      //     Id: obj.Id
      //   })
      //   console.log('新增标记成功')
      //   resolve()
      // }
      var idx = measureData.findIndex(item => item.MeasureData.data.remark === obj.measureData.data.remark)
      if (idx > -1) {
        // state.visitTaskList[index].MeasureData[idx].InstanceId = obj.instanceId
        state.visitTaskList[index].MeasureData[idx].MeasureData = obj.measureData
        // state.visitTaskList[index].MeasureData[idx].SeriesId = obj.seriesId
        // state.visitTaskList[index].MeasureData[idx].StudyId = obj.studyId
        // for (const k in state.visitTaskList[index].MeasureData[idx]) {
        //   if (k !== 'Id' && obj.MeasureData.data[k]) {
        //     state.visitTaskList[index].MeasureData[idx][k] = obj.MeasureData.data[k]
        //   }
        // }
        // state.visitTaskList[index].MeasureData[idx].MeasureData = obj.data.MeasureData
        console.log('更新标记成功', idx)
      } else {
        // state.visitTaskList[index].MeasureData.push(obj.MeasureData.data)
        state.visitTaskList[index].MeasureData.push({
          MeasureData: obj.measureData,
          SeriesId: obj.measureData.seriesId,
          StudyId: obj.measureData.studyId,
          InstanceId: obj.measureData.instanceId,
          Id: obj.id
        })
        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) {
        if (measureData[idx].FristAddTaskId) {
          measureData[idx].MeasureData = ''
          console.log('清除标记成功', idx)
        } else {
          measureData.splice(idx, 1)
          console.log('移除标记成功', idx)
        }
        state.visitTaskList[index].MeasureData = measureData
      } else if (obj.orderMarkName) {
        const i = measureData.findIndex(item => item.QuestionId === obj.questionId && item.OrderMarkName === obj.orderMarkName)
        if (i > -1) {
          if (measureData[i].FristAddTaskId) {
            measureData[i].MeasureData = ''
            console.log('清除标记成功', i)
          } else {
            measureData.splice(i, 1)
            console.log('移除标记成功', i)
          }
        }
        state.visitTaskList[index].MeasureData = measureData
      }
      // 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) {
    console.log('getStudyInfo')
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      if (state.visitTaskList[index].studyListInit) {
        resolve()
      } else {
        var studyList = []
        var keyImages = []
        getReadingVisitStudyList(obj.trialId, obj.subjectVisitId, obj.visitTaskId).then(res => {
          const i = res.Result.findIndex(i => i.IsCriticalSequence)
          if (i > -1) {
            const seriesList = res.Result[i].SeriesList && res.Result[i].SeriesList
            seriesList.map(i => {
              i.InstanceInfoList.map(k => {
                keyImages.push({ instanceId: k.Id })
              })
            })
          }
          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 = []
              const instanceList = []
              // try {
              //   series.InstancePathList.forEach((path) => {
              //     imageIds.push(`wadouri:${localStorage.getItem('location') !== 'USA' ? Vue.prototype.OSSclientConfig.basePath : Vue.prototype.OSSclientConfig.basePath}${path}`)
              //   })
              // } catch (e) {
              //   console.log(e)
              // }
              series.InstanceInfoList.forEach(instance => {
                if (instance.NumberOfFrames && instance.NumberOfFrames > 1) {
                  if (study.IsCriticalSequence && instance.KeyFramesList.length > 0) {
                    instance.KeyFramesList.map(i => {
                      const imageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? Vue.prototype.OSSclientConfig.basePath : Vue.prototype.OSSclientConfig.basePath}${instance.Path}?frame=${i}&instanceId=${instance.Id}&visitTaskId=${obj.visitTaskId}&idx=${studyIndex}|${seriesIndex}|${index}`
                      imageIds.push(imageId)
                    })
                  } else {
                    for (let i = 0; i < instance.NumberOfFrames; i++) {
                      const imageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? Vue.prototype.OSSclientConfig.basePath : Vue.prototype.OSSclientConfig.basePath}${instance.Path}?frame=${i}&instanceId=${instance.Id}&visitTaskId=${obj.visitTaskId}&idx=${studyIndex}|${seriesIndex}|${index}`
                      imageIds.push(imageId)
                    }
                  }
                  instance.ImageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? Vue.prototype.OSSclientConfig.basePath : Vue.prototype.OSSclientConfig.basePath}${instance.Path}?frame=${0}&instanceId=${instance.Id}&visitTaskId=${obj.visitTaskId}&idx=${studyIndex}|${seriesIndex}|${index}`
                } else {
                  const imageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? Vue.prototype.OSSclientConfig.basePath : Vue.prototype.OSSclientConfig.basePath}${instance.Path}?instanceId=${instance.Id}&visitTaskId=${obj.visitTaskId}&idx=${studyIndex}|${seriesIndex}|${index}`
                  imageIds.push(imageId)
                  instance.ImageId = imageId
                }
                if (!study.IsCriticalSequence && series.IsBeMark) {
                  const i = keyImages.findIndex(i => i.instanceId === instance.Id)
                  if (i > -1) {
                    keyImages[i].studyIndex = studyIndex
                    keyImages[i].seriesIndex = seriesIndex
                  }
                }
                instanceList.push(instance.Id)
              })
              seriesList.push({
                isDicom: study.IsDicom,
                imageIds: imageIds,
                instanceInfoList: series.InstanceInfoList,
                instanceList: instanceList,
                seriesId: series.Id,
                imageIdIndex: 0,
                seriesUid: series.SeriesInstanceUid,
                seriesNumber: series.SeriesNumber,
                sliceThickness: series.SliceThickness,
                modality: series.Modality,
                description: series.Description,
                previewImageUrl: study.IsDicom ? series.ImageResizePath ? Vue.prototype.OSSclientConfig.basePath + series.ImageResizePath : `/api/series/preview/${series.Id}` : Vue.prototype.OSSclientConfig.basePath + `${series.NoneDicomFileFirstFile}`,
                instanceCount: series.InstanceCount,
                instanceHtmlPathList: series.InstanceHtmlPathList,
                prefetchInstanceCount: 0,
                loadStatus: false,
                imageloadedArr: [],
                studyId: study.StudyId,
                studyIndex: studyIndex,
                seriesIndex: seriesIndex,
                studyCode: study.StudyCode,
                taskBlindName: state.visitTaskList[index].TaskBlindName,
                visitTaskId: obj.visitTaskId,
                readingTaskState: state.visitTaskList[index].ReadingTaskState,
                isBaseLineTask: state.visitTaskList[index].IsBaseLineTask,
                isCurrentTask: state.visitTaskList[index].IsCurrentTask,
                isExistsClinicalData: state.visitTaskList[index].IsExistsClinicalData,
                isLoading: false,
                isBeMark: series.IsBeMark,
                ww: series.WindowWidth,
                wc: series.WindowCenter,
                isExistMutiFrames: series.IsExistMutiFrames
              })
            })
            data.SeriesList = seriesList
            studyList.push(data)
          })
          state.visitTaskList[index].StudyList = studyList
          state.visitTaskList[index].studyListInit = true
          state.visitTaskList[index].KeyImages = keyImages
          // sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
          resolve()
        }).catch(() => { resolve() })
      }
    })
  },
  getKeySeries({ state }, obj) {
    return new Promise(resolve => {
      console.log('getKeySeries')
      let { study, idx, visitTaskId } = obj
      let data = null
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === visitTaskId)
      var keyImages = []
      if (study) {
        data = {}
        const series = study.SeriesList && study.SeriesList
        series.map(i => {
          i.InstanceInfoList.map(k => {
            keyImages.push({ instanceId: k.Id })
          })
        })
        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 = []
          const instanceList = []
          series.InstanceInfoList.forEach(instance => {
            if (instance.NumberOfFrames && instance.NumberOfFrames > 1) {
              if (study.IsCriticalSequence && instance.KeyFramesList.length > 0) {
                instance.KeyFramesList.map(i => {
                  const imageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? Vue.prototype.OSSclientConfig.basePath : Vue.prototype.OSSclientConfig.basePath}${instance.Path}?frame=${i}&instanceId=${instance.Id}&visitTaskId=${obj.visitTaskId}&idx=${idx}|${seriesIndex}|${index}`
                  imageIds.push(imageId)
                })
              } else {
                for (let i = 0; i < instance.NumberOfFrames; i++) {
                  const imageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? Vue.prototype.OSSclientConfig.basePath : Vue.prototype.OSSclientConfig.basePath}${instance.Path}?frame=${i}&instanceId=${instance.Id}&visitTaskId=${obj.visitTaskId}&idx=${idx}|${seriesIndex}|${index}`
                  imageIds.push(imageId)
                }
              }
              instance.ImageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? Vue.prototype.OSSclientConfig.basePath : Vue.prototype.OSSclientConfig.basePath}${instance.Path}?frame=${0}&instanceId=${instance.Id}&visitTaskId=${obj.visitTaskId}&idx=${idx}|${seriesIndex}|${index}`
            } else {
              const imageId = `wadouri:${localStorage.getItem('location') !== 'USA' ? Vue.prototype.OSSclientConfig.basePath : Vue.prototype.OSSclientConfig.basePath}${instance.Path}?instanceId=${instance.Id}&visitTaskId=${obj.visitTaskId}&idx=${idx}|${seriesIndex}|${index}`
              imageIds.push(imageId)
              instance.ImageId = imageId
            }
            if (!study.IsCriticalSequence && series.IsBeMark) {
              const i = keyImages.findIndex(i => i.instanceId === instance.Id)
              if (i > -1) {
                keyImages[i].idx = idx
                keyImages[i].seriesIndex = seriesIndex
              }
            }
            instanceList.push(instance.Id)
          })
          seriesList.push({
            isDicom: study.IsDicom,
            imageIds: imageIds,
            instanceInfoList: series.InstanceInfoList,
            instanceList: instanceList,
            seriesId: series.Id,
            imageIdIndex: 0,
            seriesUid: series.SeriesInstanceUid,
            seriesNumber: series.SeriesNumber,
            sliceThickness: series.SliceThickness,
            modality: series.Modality,
            description: series.Description,
            previewImageUrl: study.IsDicom ? series.ImageResizePath ? Vue.prototype.OSSclientConfig.basePath + series.ImageResizePath : `/api/series/preview/${series.Id}` : Vue.prototype.OSSclientConfig.basePath + `${series.NoneDicomFileFirstFile}`,
            instanceCount: series.InstanceCount,
            instanceHtmlPathList: series.InstanceHtmlPathList,
            prefetchInstanceCount: 0,
            loadStatus: false,
            imageloadedArr: series.InstanceInfoList,
            studyId: study.StudyId,
            studyIndex: idx,
            seriesIndex: seriesIndex,
            studyCode: study.StudyCode,
            taskBlindName: state.visitTaskList[index].TaskBlindName,
            visitTaskId: obj.visitTaskId,
            readingTaskState: state.visitTaskList[index].ReadingTaskState,
            isBaseLineTask: state.visitTaskList[index].IsBaseLineTask,
            isCurrentTask: state.visitTaskList[index].IsCurrentTask,
            isExistsClinicalData: state.visitTaskList[index].IsExistsClinicalData,
            isLoading: false,
            isBeMark: series.IsBeMark,
            ww: series.WindowWidth,
            wc: series.WindowCenter,
            isExistMutiFrames: series.IsExistMutiFrames
          })
        })
        data.SeriesList = seriesList
      }
      let stateIndex = state.visitTaskList[index].StudyList.findIndex(item => item.IsCriticalSequence)
      console.log(stateIndex, 'stateIndex')
      if (data) {
        if (!!~stateIndex) {
          state.visitTaskList[index].StudyList.splice(stateIndex, 1, data)
        } else {
          state.visitTaskList[index].StudyList.unshift(data)
        }
      } else {
        if (!!~stateIndex) {
          state.visitTaskList[index].StudyList.splice(stateIndex, 1)
        }
      }
      state.visitTaskList[index].studyListInit = true
      state.visitTaskList[index].KeyImages = keyImages
      // sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      resolve(data)
    })
  },
  updateStudyList({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      if (index > -1) {
        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
                  }
                  break
                }
              }
            }
          }
        }
        state.visitTaskList[index].StudyList = studyList
        // sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      } else {
        // console.log(obj)
      }
      resolve()
    })
  },
  updateSeriesList({ state }, obj) {
    return new Promise(resolve => {
      if (obj.visitTaskindex > -1 && obj.studyIndex > -1 && obj.seriesIndex > -1) {
        var studyList = state.visitTaskList[obj.visitTaskindex].StudyList || []
        if (studyList[obj.studyIndex].SeriesList[obj.seriesIndex].imageloadedArr.indexOf(obj.imageId) < 0) {
          studyList[obj.studyIndex].SeriesList[obj.seriesIndex].imageloadedArr.push(obj.imageId)
          ++studyList[obj.studyIndex].SeriesList[obj.seriesIndex].prefetchInstanceCount
        } else {
          studyList[obj.studyIndex].SeriesList[obj.seriesIndex].prefetchInstanceCount = studyList[obj.studyIndex].SeriesList[obj.seriesIndex].instanceCount
          // 设置当前序列状态为已下载完成
          studyList[obj.studyIndex].SeriesList[obj.seriesIndex].loadStatus = true
        }
        state.visitTaskList[obj.visitTaskindex].StudyList = studyList
        // sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      }
      resolve()
    })
  },
  setImageLoadedProgress({ state }, obj) {
    const studyIndex = parseInt(obj.idx.split('|')[0])
    const seriesIndex = parseInt(obj.idx.split('|')[1])
    const visitTaskIndex = parseInt(obj.idx.split('|')[2])
    let pStudyIndex = null
    let pSeriesIndex = null
    let pSeries = null
    try {
      const study = state.visitTaskList[visitTaskIndex].StudyList[studyIndex]
      const series = state.visitTaskList[visitTaskIndex].StudyList[studyIndex].SeriesList[seriesIndex]
      const keyImages = state.visitTaskList[visitTaskIndex].KeyImages
      if (study.IsCriticalSequence) {
        const i = keyImages.findIndex(i => i.instanceId === obj.instanceId)
        if (i > -1) {
          pStudyIndex = keyImages[i].studyIndex
          pSeriesIndex = keyImages[i].seriesIndex
        }
      } else if (series.isBeMark) {
        if (keyImages.length > 0) {
          pStudyIndex = 0
          pSeriesIndex = 0
        }
      }
      if (pStudyIndex !== null && pSeriesIndex !== null) {
        pSeries = state.visitTaskList[visitTaskIndex].StudyList[pStudyIndex].SeriesList[pSeriesIndex]
      }

      var prefetchInstanceCount = series.prefetchInstanceCount
      var instanceCount = series.instanceCount
      var prefetchInstanceCount2 = pSeries ? pSeries.prefetchInstanceCount : null
      var instanceCount2 = pSeries ? pSeries.instanceCount : null
      if (series.imageloadedArr.indexOf(obj.instanceId) < 0) {
        const i = state.currentLoadIns.findIndex(i => i.instanceId === obj.instanceId)
        if (i > -1) {
          prefetchInstanceCount = prefetchInstanceCount + obj.percentComplete - state.currentLoadIns[i].percentComplete
          prefetchInstanceCount2 = prefetchInstanceCount2 !== null ? prefetchInstanceCount2 + obj.percentComplete - state.currentLoadIns[i].percentComplete : null
          state.currentLoadIns[i].percentComplete = obj.percentComplete
          if (obj.percentComplete >= 100) {
            state.currentLoadIns.splice(i, 1)
          }
        } else {
          if (obj.percentComplete !== 100) {
            state.currentLoadIns.push({ instanceId: obj.instanceId, percentComplete: obj.percentComplete })
          }
          prefetchInstanceCount = prefetchInstanceCount + obj.percentComplete
          prefetchInstanceCount2 = prefetchInstanceCount2 !== null ? prefetchInstanceCount2 + obj.percentComplete : null
        }
        series.prefetchInstanceCount = prefetchInstanceCount
        if (pSeries) {
          pSeries.prefetchInstanceCount = prefetchInstanceCount2
        }
        if (obj.percentComplete >= 100) {
          series.imageloadedArr.push(obj.instanceId)
          if (pSeries) {
            pSeries.imageloadedArr.push(obj.instanceId)
          }
        }
      }

      if (prefetchInstanceCount >= instanceCount * 100) {
        series.prefetchInstanceCount = instanceCount * 100
        // 设置当前序列状态为已下载完成
        series.loadStatus = true
      }
      if (prefetchInstanceCount2 !== null && instanceCount2 !== null && prefetchInstanceCount2 >= instanceCount2 * 100) {
        pSeries.prefetchInstanceCount = instanceCount2 * 100
        // 设置当前序列状态为已下载完成
        pSeries.loadStatus = true
      }
    } catch (e) {
      console.log('error')
    }
  },
  setImageloadedInfo({ state }, obj) {
    console.log('setImageloadedInfo', obj)
    // if(obj.instance === '20dd8fc9-51b0-ec63-942b-cb3006c72650')
    // var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
    // // const prefetchInstanceCount = state.visitTaskList[index].StudyList[obj.studyIndex].SeriesList[obj.seriesIndex].prefetchInstanceCount
    // const instanceList = state.visitTaskList[index].StudyList[obj.studyIndex].SeriesList[obj.seriesIndex].instanceList
    // const idx = state.visitTaskList[index].StudyList.findIndex(i => i.IsCriticalSequence)

    // if (!state.visitTaskList[index].StudyList[obj.studyIndex].IsCriticalSequence) {
    //   // 当前下载的非关键序列
    //   console.log('当前下载的非关键序列')
    //   if (idx > -1) {
    //     const keyInstance = state.visitTaskList[index].StudyList[idx].SeriesList[0].instanceList
    //     obj.markedImages = getKeySeriesInfo(keyInstance, state.visitTaskList[index].StudyList[obj.studyIndex].SeriesList[obj.seriesIndex])
    //     instanceList.map(i => {
    //       if (obj.markedImages.hasOwnProperty(i) && state.visitTaskList[index].StudyList[idx].SeriesList[0].imageloadedArr.indexOf(i) < 0) {
    //         state.visitTaskList[index].StudyList[idx].SeriesList[0].imageloadedArr.push(i)
    //         state.visitTaskList[index].StudyList[idx].SeriesList[0].prefetchInstanceCount = state.visitTaskList[index].StudyList[idx].SeriesList[0].prefetchInstanceCount + 100
    //       }
    //     })
    //     if (state.visitTaskList[index].StudyList[idx].SeriesList[0].imageloadedArr >= state.visitTaskList[index].StudyList[idx].SeriesList[0].instanceCount) {
    //       state.visitTaskList[index].StudyList[idx].SeriesList[0].loadStatus = true
    //     }
    //   }
    // }
    // state.visitTaskList[index].StudyList[obj.studyIndex].SeriesList[obj.seriesIndex].prefetchInstanceCount = state.visitTaskList[index].StudyList[obj.studyIndex].SeriesList[obj.seriesIndex].instanceCount * 100
    // state.visitTaskList[index].StudyList[obj.studyIndex].SeriesList[obj.seriesIndex].imageloadedArr = instanceList
    // state.visitTaskList[index].StudyList[obj.studyIndex].SeriesList[obj.seriesIndex].loadStatus = true
    // const imageloadedArr = state.visitTaskList[index].StudyList[obj.studyIndex].SeriesList[obj.seriesIndex].imageloadedArr
    // if (imageloadedArr.indexOf())

    // if (state.visitTaskList[index].StudyList[0].IsCriticalSequence){
    //   state.visitTaskList[index].StudyList[0].SeriesList[0].prefetchInstanceCount = prefetchInstanceCount + 100
    //   state.visitTaskList[index].StudyList[obj.studyIndex].SeriesList[obj.seriesIndex].imageloadedArr.push(obj.imageId)
    // }
  },
  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 => {
      var isReadingTaskViewInOrder = localStorage.getItem('isReadingTaskViewInOrder')
      if (parseInt(isReadingTaskViewInOrder) === 2) {
        if (!state.lastCanvasTaskId) {
          console.log('setLastCanvasTaskId')
          state.lastCanvasTaskId = taskId
        }
      } else {
        state.lastCanvasTaskId = taskId
      }
      resolve()
    })
  },
  setCurrentReadingTaskState({ state }, readingTaskState) {
    return new Promise(resolve => {
      state.currentReadingTaskState = readingTaskState
      resolve()
    })
  },
  setSeriesStack({ state }, seriesStack) {
    state.seriesStack = seriesStack
  },
  setImageQuality({ state }, imageQuality) {
    state.imageQuality = isNaN(parseInt(imageQuality)) ? null : parseInt(imageQuality)
  },
  setImageQualityIssues({ state }, imageQualityIssues) {
    state.imageQualityIssues = isNaN(parseInt(imageQualityIssues)) ? null : parseInt(imageQualityIssues)
  },
  addQuestionMeasuredData({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      var measureData = state.visitTaskList[index].QuestionMarkInfoList
      var idx = measureData.findIndex(item => item.QuestionId === obj.data.QuestionId)
      if (idx > -1) {
        for (const k in state.visitTaskList[index].QuestionMarkInfoList[idx]) {
          if (k !== 'Id' && obj.data[k]) {
            state.visitTaskList[index].QuestionMarkInfoList[idx][k] = obj.data[k]
          }
        }
        console.log('更新标记成功', idx)
      } else {
        state.visitTaskList[index].QuestionMarkInfoList.push(obj.data)
        console.log('新增标记成功')
      }
      // sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      resolve()
    })
  },
  removeQuestionMeasuredData({ state }, obj) {
    return new Promise(resolve => {
      var index = state.visitTaskList.findIndex(i => i.VisitTaskId === obj.visitTaskId)
      var measureData = state.visitTaskList[index].QuestionMarkInfoList
      if (obj.orderMarkName) {
        const i = measureData.findIndex(item => item.QuestionId === obj.questionId && item.OrderMarkName === obj.orderMarkName)
        if (i > -1) {
          measureData[i].MeasureData = ''
          console.log('清除标记成功', i)
        }
        state.visitTaskList[index].QuestionMarkInfoList = measureData
      }
      // sessionStorage.setItem('visitTaskList', state.visitTaskList.length > 0 ? JSON.stringify(state.visitTaskList) : '')
      resolve()
    })
  }
}

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

