<template>
  <div class="measurement-wrapper">

    <div class="container">
      <div class="basic-info">
        <h3 v-if="isReadingShowSubjectInfo">
          <span v-if="subjectCode">{{ subjectCode }} </span>
          <span style="margin-left:5px;">{{ taskBlindName }}</span>
        </h3>
        <div v-if="readingTaskState < 2">
          <el-tooltip class="item" effect="dark" :content="$t('trials:dicomReading:message:confirmReset')"
            placement="bottom">
            <i class="el-icon-refresh-left" @click="resetMeasuredData" />
          </el-tooltip>
        </div>
      </div>

      <!-- 非测量问题 -->
      <div class="lesions">
        <Questions ref="ecrf" :groupClassify="1" :question-form-change-state="questionFormChangeState"
          :question-form-change-num="questionFormChangeNum" @handleReadingChart="handleReadingChart" />
      </div>
      <!-- 测量问题 -->
      <template>
        <div v-for="(qs, index) in questions" :key="index" v-loading="loading" class="lesions lesions_wrapper">
          <h4 v-if="qs.Type === 'group'" style="color: #ddd;padding: 5px 0px;margin: 0;">
            {{ language === 'en' ? qs.GroupEnName : qs.GroupName }}
          </h4>
          <div class="lesion_list">
            <div v-for="item in qs.Childrens" v-show="!(isBaseLineTask && item.LesionType === 2)" :key="item.Id">
              <div v-if="item.Type === 'table'" class="flex-row" style="margin:3px 0;">
                <div class="title">{{ item.QuestionName }}</div>
              </div>
              <div
                style="color: #ddd;text-align: left;padding: 5px 10px;border-bottom: 1px solid #5a5a5a;    font-size: 15px;">
                <el-row>
                  <!-- 分段 -->
                  <el-col :span="14">{{ $t('trials:MRIPDFF:label:col1') }}</el-col>
                  <!-- 是否可测量 -->
                  <!-- <el-col :span="7">{{$t('trials:MRIPDFF:label:col2')}}</el-col> -->
                  <!-- 平均值 -->
                  <el-col :span="7">{{ $t('trials:MRIPDFF:label:col3') }}</el-col>
                </el-row>
              </div>

              <el-collapse v-if="item.Type === 'table' && item.TableQuestions" v-model="activeName" accordion
                @change="handleCollapseChange">
                <el-collapse-item v-for="(q, i) in item.TableQuestions.Answers" :key="`${item.Id}_${q.RowIndex}`"
                  :name="`${item.Id}_${q.RowIndex}`"
                  @contextmenu.prevent.native="collapseRightClick($event, q, item.Id, q.RowIndex)">
                  <template slot="title">
                    <div style="width:300px;position: relative;"
                      :style="{ color: (activeName === item.Id + q.RowIndex ? '#ffeb3b' : '#fff') }">

                      {{ getLesionName(item.TableQuestions.Questions, q) }}
                      <!-- 未保存 -->
                      <el-tooltip
                        v-if="readingTaskState < 2 && parseInt(item.TableQuestions.Answers[i].saveTypeEnum) === 0"
                        class="item" effect="dark" :content="$t('trials:reading:button:unsaved')" placement="bottom">
                        <i class="el-icon-warning" style="color:red" />
                      </el-tooltip>
                      <!-- 信息不完整 -->
                      <el-tooltip
                        v-if="readingTaskState < 2 && parseInt(item.TableQuestions.Answers[i].saveTypeEnum) === 1"
                        class="item" effect="dark" :content="$t('trials:reading:button:incompleteInfor')"
                        placement="bottom">
                        <i class="el-icon-warning" style="color:#ff9800" />
                      </el-tooltip>
                      <div style="position: absolute;right: 0px;top: 2px;">
                        <!-- white-space: nowrap;overflow: hidden;text-overflow: ellipsis; -->
                        <div style="font-size: 13px;width:110px;height: 30px;">
                          <!-- <div style="display: inline-block;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;width:95px">
                            {{ $fd('ReadingYesOrNo', parseInt(item.TableQuestions.Answers[i].isMeasurable)) }}
                          </div> -->
                          <div
                            style="display: inline-block;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;width:50px">
                            {{ isNaN(parseFloat(item.TableQuestions.Answers[i].mean)) ?
                              item.TableQuestions.Answers[i].mean : `${item.TableQuestions.Answers[i].mean}%` }}
                          </div>
                        </div>
                      </div>
                    </div>

                  </template>
                  <QuestionForm :ref="`${item.Id}_${q.RowIndex}`" :questions="item.TableQuestions.Questions"
                    :answers="item.TableQuestions.Answers[i]" :lesion-type="item.LesionType"
                    :order-mark="item.OrderMark" :table-questions="tableQuestions" :row-index="String(q.RowIndex)"
                    :question-name="item.QuestionName" :parent-qs-id="item.Id" :visit-task-id="visitTaskId"
                    :is-current-task="isCurrentTask" :reading-task-state="readingTaskState"
                    :is-base-line-task="isBaseLineTask" @getReadingQuestionAndAnswer="getReadingQuestionAndAnswer"
                    @resetQuestions="resetQuestions" @close="close" @handleReadingChart="handleReadingChart" />
                </el-collapse-item>

              </el-collapse>
            </div>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>
<script>
import { resetReadingTask } from '@/api/reading'
import DicomEvent from './../DicomEvent'
import store from '@/store'
import { mapGetters } from 'vuex'
import Questions from './../Questions'
import QuestionForm from './QuestionForm'
export default {
  name: 'MeasurementList',
  components: {
    Questions,
    QuestionForm
  },
  props: {
    isShow: {
      type: Boolean,
      required: true
    },
    isReadingShowSubjectInfo: {
      type: Boolean,
      required: true
    },
    questionFormChangeState: {
      type: Boolean,
      default() {
        return false
      }
    },
    questionFormChangeNum: {
      type: Number,
      default() {
        return 0
      }
    }
  },
  data() {
    return {
      questions: [],
      activeName: '',
      activeItem: {
        activeRowIndex: null,
        activeCollapseId: null
      },
      visitTaskId: '',
      isCurrentTask: false,
      loading: false,
      unSaveTargets: [],
      temporaryLesions: [],
      readingTaskState: 2,
      isBaseLineTask: false,
      taskBlindName: '',
      tableQuestions: [],
      isFirstRender: false,
      CriterionType: null,
      subjectCode: '',
      liverSegmentId: '',
      liverSegmentDicCode: ''
    }
  },
  computed: {
    ...mapGetters(['visitTaskList', 'language', 'lastCanvasTaskId', 'currentReadingTaskState'])
  },
  watch: {
    lastCanvasTaskId: {
      immediate: true,
      handler(val) {
        if (val) {
          this.initList()
        }
        console.log('lastCanvasTaskId', val)
      }
    },
    currentReadingTaskState: {
      immediate: true,
      handler(val) {
        if (val) {
          this.readingTaskState = val
        }
      }
    }
  },
  mounted() {
    // this.subjectCode = this.$router.currentRoute.query.subjectCode
    this.subjectCode = localStorage.getItem('subjectCode')
    this.CriterionType = parseInt(localStorage.getItem('CriterionType'))
    DicomEvent.$on('setCollapseActive', measureData => {
      this.setCollapseActive(measureData)
      console.log('setCollapseActive')
    })
    DicomEvent.$on('getAllUnSaveLesions', (callback) => {
      var list = this.getAllUnSaveLesions()
      callback(list)
      console.log('getAllUnSaveLesions')
    })
  },
  beforeDestroy() {
    DicomEvent.$off('setCollapseActive')
    DicomEvent.$off('getUnSaveTarget')
    DicomEvent.$off('getAllUnSaveLesions')
  },
  methods: {
    handleReadingChart(e) {
      this.$emit('handleReadingChart', e)
    },
    async initList() {
      var i = this.visitTaskList.findIndex(i => i.VisitTaskId === this.lastCanvasTaskId)
      if (i > -1) {
        this.visitTaskId = this.visitTaskList[i].VisitTaskId
        this.taskBlindName = this.visitTaskList[i].TaskBlindName
        this.readingTaskState = this.visitTaskList[i].ReadingTaskState
        this.isBaseLineTask = this.visitTaskList[i].IsBaseLineTask
        this.isCurrentTask = this.visitTaskList[i].IsCurrentTask
        this.activeName = ''
        this.activeItem.activeRowIndex = null
        this.activeItem.activeCollapseId = null
        if (!this.visitTaskList[i].IsInit) {
          var loading = this.$loading({ fullscreen: true })
          var triald = this.trialId = this.$router.currentRoute.query.trialId
          if (!this.visitTaskList[i].measureDataInit) {
            await store.dispatch('reading/getMeasuredData', this.visitTaskList[i].VisitTaskId)
          }
          if (!this.visitTaskList[i].studyListInit) {
            await store.dispatch('reading/getStudyInfo', { trialId: triald, subjectVisitId: this.visitTaskList[i].VisitId, visitTaskId: this.visitTaskList[i].VisitTaskId, taskBlindName: this.visitTaskList[i].TaskBlindName })
          }
          if (!this.visitTaskList[i].readingQuestionsInit) {
            await store.dispatch('reading/getReadingQuestionAndAnswer', { trialId: triald, visitTaskId: this.visitTaskList[i].VisitTaskId })
          }
          if (!this.visitTaskList[i].questionsInit) {
            await store.dispatch('reading/getDicomReadingQuestionAnswer', { trialId: triald, visitTaskId: this.visitTaskList[i].VisitTaskId })
          }

          await store.dispatch('reading/setStatus', { visitTaskId: this.visitTaskList[i].VisitTaskId })
          loading.close()
        }
        this.questions = this.visitTaskList[i].ReadingQuestions
        this.$nextTick(() => {
          this.$refs['ecrf'].getQuestions(this.visitTaskId)
          this.getTableQuestions()
          this.tableQuestions.forEach(item => {
            item.TableQuestions.Answers.forEach(i => {
              var refName = `${item.Id}_${i.RowIndex}`
              this.$refs[refName] && this.$refs[refName][0].initForm()
            })
          })
        })
      }
    },
    async resetQuestions(obj) {
      this.setQuestions(this.questions, obj)
      await store.dispatch('reading/setReadingQuestionAndAnswer', { questions: this.questions, visitTaskId: this.visitTaskId })

      this.getTableQuestions()
    },
    setQuestions(questions, obj) {
      questions.forEach(item => {
        if (item.Type === 'table' && item.Id === obj.questionId) {
          var idx = item.TableQuestions.Answers.findIndex(i => i.RowIndex === obj.rowIndex)
          item.TableQuestions.Answers[idx].isMeasurable = obj.isMeasurable
          item.TableQuestions.Answers[idx].mean = obj.mean
          item.TableQuestions.Answers[idx].saveTypeEnum = obj.saveTypeEnum

          for (const i in obj.anwsers) {
            if (i === 'MeasureData' && obj.anwsers[i]) {

            } else {
              item.TableQuestions.Answers[idx][i] = String(obj.anwsers[i])
            }
          }
        }
        if (item.Childrens.length > 0) {
          this.setQuestions(item.Childrens, obj)
        }
      })
    },
    getQuestions(questions) {
      questions.forEach(item => {
        if (item.Type === 'table' && item.TableQuestions && item.TableQuestions.Answers.length > 0) {
          item.TableQuestions.Answers.forEach(answerObj => {
            let isMeasurable = this.getQuestionAnswer(item.TableQuestions.Questions, 1105, answerObj)
            this.$set(answerObj, 'isMeasurable', isMeasurable)
            this.$set(answerObj, 'mean', this.getQuestionAnswer(item.TableQuestions.Questions, 1104, answerObj))
            if (answerObj.RowId) {
              this.$set(answerObj, 'saveTypeEnum', isNaN(parseInt(isMeasurable)) ? 1 : 2)
            } else {
              this.$set(answerObj, 'saveTypeEnum', 0)
            }
          })
        }
        if (item.Childrens.length > 0) {
          this.getQuestions(item.Childrens)
        }
      })
      return questions
    },
    getTableQuestions() {
      this.tableQuestions = []
      this.questions.map(item => {
        if (item.Type === 'table') {
          this.tableQuestions.push(item)
        }
        if (item.Childrens.length > 0) {
          this.getTableQuestionsChild(item.Childrens)
        }
      })
    },
    getTableQuestionsChild(obj) {
      obj.map(item => {
        if (item.Type === 'table') {
          this.tableQuestions.push(item)
        }
        if (item.Childrens.length > 0) {
          this.getTableQuestionsChild(item.Childrens)
        }
      })
    },
    refreshReadingQuestionAndAnswer(type) {
      if (type === 0) {
        // 删除
        this.activeName = ''
        this.activeItem.activeRowIndex = null
        this.activeItem.activeCollapseId = null
      }

      this.getReadingQuestionAndAnswer(this.visitTaskId)
    },
    getReadingQuestionAndAnswer(showLoading = true) {
      return new Promise(async resolve => {
        try {
          let loading = null
          if (showLoading) {
            loading = this.$loading({ fullscreen: true })
          }
          await store.dispatch('reading/refreshReadingQuestionAndAnswer', { trialId: this.$router.currentRoute.query.trialId, visitTaskId: this.visitTaskId }).then(() => {
            var idx = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)
            if (idx > -1) {
              if (this.visitTaskList[idx].ReadingQuestions.length > 0) {
                this.questions = this.visitTaskList[idx].ReadingQuestions
              }
              this.readingTaskState = this.visitTaskList[idx].ReadingTaskState
              this.isBaseLineTask = this.visitTaskList[idx].IsBaseLineTask
              this.isCurrentTask = this.visitTaskList[idx].IsCurrentTask
            }
            this.getTableQuestions()
            this.$nextTick(() => {
              this.tableQuestions.forEach(item => {
                item.TableQuestions.Answers.forEach(i => {
                  var refName = `${item.Id}_${i.RowIndex}`
                  this.$refs[refName] && this.$refs[refName][0].initForm()
                })
              })
            })
          })
          await store.dispatch('reading/refreshMeasuredData', this.visitTaskId)
          DicomEvent.$emit('getMeasureData')

          loading ? loading.close() : ''
          resolve()
        } catch (e) {
          console.log(e)
          loading ? loading.close() : ''
        }
      })
    },
    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 ''
      }
    },
    isCanActiveTool(toolName) {
      return { isCanActiveTool: true, reason: '' }
    },

    checkToolCanActive(toolName) {
      return { isCanActiveTool: true, reason: '' }
    },

    getLesionName(questions, q) {
      let liverSegmentStr = ''
      if (!this.liverSegmentId) {
        let i = questions.findIndex(i => i.QuestionMark === 1106)
        if (i === -1) return
        this.liverSegmentId = questions[i].Id
        this.liverSegmentDicCode = questions[i].DictionaryCode
      }
      if (q && q[this.liverSegmentId]) {
        liverSegmentStr = this.$fd(this.liverSegmentDicCode, parseInt(q[this.liverSegmentId]))
      }
      return liverSegmentStr
    },
    handleCollapseChange(val) {
      if (this.activeName) {
        var arr = this.activeName.split('_')
        this.activeItem.activeRowIndex = arr[1]
        this.activeItem.activeCollapseId = arr[0]
        this.$nextTick(() => {
          const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
          if (this.$refs[refName][0].questionForm.IsDicomReading !== false) {
            var markTool = this.$refs[refName][0].currentMarkTool
            var readingTaskState = this.readingTaskState
            var isMarked = !!this.$refs[refName][0].questionForm.MeasureData
            DicomEvent.$emit('imageLocation', { questionId: this.activeItem.activeCollapseId, rowIndex: this.activeItem.activeRowIndex, visitTaskId: this.visitTaskId, lesionName: this.$refs[refName][0].lesionMark, lesionType: this.$refs[refName][0].lesionType, markTool, readingTaskState, isMarked })
          }
        })
      } else {
        this.activeItem.activeRowIndex = null
        this.activeItem.activeCollapseId = null
      }
    },
    collapseRightClick(e, obj, activeCollapseId, activeRowIndex) {
      if (obj.IsDicomReading !== false) {
        const refName = `${activeCollapseId}_${activeRowIndex}`
        DicomEvent.$emit('imageLocation', { questionId: activeCollapseId, rowIndex: activeRowIndex, visitTaskId: this.visitTaskId, lesionName: this.$refs[refName][0].lesionMark, lesionType: this.$refs[refName][0].lesionType })
      }
      e.stopImmediatePropagation()
      e.stopPropagation()
      e.preventDefault()
    },
    setCollapseActive(measureData) {
      if (measureData) {
        if (this.activeItem.activeRowIndex === measureData.RowIndex && this.activeItem.activeCollapseId === measureData.QuestionId) {
          return
        } else {
          this.activeItem.activeCollapseId = measureData.QuestionId
          this.activeItem.activeRowIndex = measureData.RowIndex
          this.activeName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
        }
      }
    },
    modifyMeasuredData(measureObj) {
      if (measureObj.questionInfo) {
        this.activeItem.activeCollapseId = measureObj.questionInfo.QuestionId
        this.activeItem.activeRowIndex = String(measureObj.questionInfo.RowIndex)
        this.activeName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
        const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
        this.$refs[refName][0].setMeasureData(measureObj.measureData)
      }
    },
    // 设置测量数据
    setMeasuredData(measureData) {
      if (this.activeItem.activeCollapseId) {
        // 判断是否存在测量数据
        this.$nextTick(() => {
          const refName = `${this.activeItem.activeCollapseId}_${this.activeItem.activeRowIndex}`
          if (!this.$refs[refName][0].questionForm.MeasureData || (this.$refs[refName][0].questionForm && this.$refs[refName][0].questionForm.MeasureData && measureData.data.uuid === this.$refs[refName][0].questionForm.MeasureData.data.uuid)) {
            this.$refs[refName][0].setMeasureData(measureData)
          }
        })
      } else {

      }
    },
    async close(questionsObj) {
      if (questionsObj) {
        this.getReadingQuestionAndAnswer(questionsObj.visitTaskId)
      }
      this.activeItem.activeRowIndex = null
      this.activeItem.activeCollapseId = null
      this.activeName = ''
    },
    getECRFQuestions(obj) {
      this.$refs['ecrf'].getQuestions(obj.visitTaskId)
    },
    async resetMeasuredData() {
      const confirm = await this.$confirm(
        this.$t('trials:dicomReading:message:confirmReset1'),
        this.$t('trials:dicomReading:message:confirmReset2'),
        {
          type: 'warning',
          distinguishCancelAndClose: true
        }
      )
      if (confirm !== 'confirm') return
      const loading = this.$loading({ fullscreen: true })
      try {
        const res = await resetReadingTask({ visitTaskId: this.visitTaskId })
        this.loading = false
        if (res.IsSuccess) {
          // 刷新标注、表单、报告页信息
          this.activeName = ''
          this.activeItem.activeRowIndex = null
          this.activeItem.activeCollapseId = null
          await this.getReadingQuestionAndAnswer(this.visitTaskId)
          const triald = this.$router.currentRoute.query.trialId
          await store.dispatch('reading/refreshDicomReadingQuestionAnswer', { trialId: triald, visitTaskId: this.visitTaskId })
          this.$refs['ecrf'].getQuestions(this.visitTaskId, true)
          DicomEvent.$emit('getMeasureData')
          DicomEvent.$emit('getReportInfo', true)
          DicomEvent.$emit('refreshStudyListMeasureData')
        }
        loading.close()
      } catch (e) {
        loading.close()
        console.log(e)
      }
    },
    getAllUnSaveLesions() {
      var arr = []
      this.tableQuestions.map(item => {
        if (item.TableQuestions && item.TableQuestions.Answers) {
          item.TableQuestions.Answers.map(t => {
            const refName = `${item.Id}_${t.RowIndex}`
            if (this.$refs[refName] && this.$refs[refName][0] && this.$refs[refName][0].questionForm.saveTypeEnum !== 2) {
              var lessionName = this.$refs[refName][0].liverSeg
              arr.push({ lessionName: lessionName, rowIndex: t.RowIndex, questionId: item.Id })
            }
          })
        }
      })
      return arr
    },

  }
}
</script>
<style lang="scss" scoped>
.measurement-wrapper {
  height: 100%;
  overflow-y: auto;
  // overflow: hidden;

  .container {
    padding: 10px;

    .basic-info {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        color: #ddd;
        padding: 5px 0px;
        margin: 0;
      }

      i {
        color: #fff;
        font-size: 22px;
        font-weight: bold;
        cursor: pointer;
      }
    }
  }

  .title {
    padding: 5px;
    font-weight: bold;
    color: #ddd;
    font-size: 15px;

  }

  .add-icon {
    padding: 5px;
    font-weight: bold;
    color: #ddd;
    font-size: 15px;
    border: 1px solid #938b8b;
    margin-bottom: 2px;
    cursor: pointer;
  }

  .add-icon:hover {
    background-color: #607d8b;
  }

  .flex-row {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    background-color: #424242;

  }

  .lesion_list {
    position: relative;
  }

  .el-collapse {
    border-bottom: none;
    border-top: none;

    ::v-deep .el-collapse-item {
      background-color: #000 !important;
      color: #ddd;

    }

    ::v-deep .el-collapse-item__header {
      background-color: #000 !important;
      color: #ddd;
      border-bottom-color: #5a5a5a;
      padding-left: 5px;
      height: 35px;
      line-height: 35px;
    }

    ::v-deep .el-collapse-item__wrap {
      background-color: #000 !important;
      color: #ddd;
    }

    ::v-deep .el-collapse-item__content {
      width: 260px;
      position: absolute;
      top: 0px;
      right: 0px;
      // border: 1px solid #ffeb3b;
      border: 1px solid #fff;
      z-index: 1;
      color: #ddd;
      padding: 5px;
      background-color: #1e1e1e;
    }

  }
}
</style>
