<template>
  <div class="report-wrapper">
    <el-card v-loading="loading" shadow="never">
      <div slot="header" class="clearfix report-header">
        <!-- 电子影像病例报告表（eICRF） -->
        <h3 style="margin:0;padding:0;">{{ $t('trials:readingReport:title:eicrf') }}</h3>
        <div style="margin-left:auto">
          <el-switch
            v-model="isShowDetail"
            :active-text="$t('trials:readingReport:title:expandDetails')"
            :inactive-text="$t('trials:readingReport:title:collapseDetails')"
            style="margin-right:5px;"
            @change="handleShowDetail"
          />
          <el-button
            v-if="readingTaskState<2"
            type="primary"
            size="small"
            @click="getReportInfo(false)"
          >
            <!-- 刷新 -->
            {{ $t('trials:readingReport:button:refresh') }}
          </el-button>
          <el-button
            v-if="readingTaskState<2 && CriterionType !== 10"
            type="primary"
            size="small"
            @click="handleSave(true)"
          >
            <!-- 保存 -->
            {{ $t('common:button:save') }}
          </el-button>
          <el-button
            v-if="readingTaskState<2"
            type="primary"
            size="small"
            @click="beforeLeave"
          >
            <!-- 提交 -->
            {{ $t('common:button:submit') }}
          </el-button>
        </div>
      </div>
      <div ref="tableWrapper" style="height:100%;overflow-y: auto;">
        <el-table
          v-if="height"
          ref="reportList"
          :data="taskQuestions"
          row-key="Id"
          border
          default-expand-all
          :height="height"
          :tree-props="{children: 'Childrens', hasChildren: 'hasChildren'}"
          size="mini"
        >
          <el-table-column
            prop=""
            label=""
            show-overflow-tooltip
            width="350px"
          >
            <template slot-scope="scope">
              <span v-if="scope.row.QuestionName" :style="{color: ((scope.row.isLymphNodes === 1 && scope.row.QuestionMark === 1) || (scope.row.isLymphNodes === 0 && scope.row.QuestionMark === 0)) && (scope.row.LesionType === 0 || scope.row.LesionType === 5) ? '#f66' : '#fff'}">{{ scope.row.QuestionName }}</span>
              <span
                v-else
                style="font-weight: bold;font-size: 16px;color: #f44336;"
              >
                {{ language==='en'?scope.row.GroupEnName:scope.row.GroupName }}
              </span>
            </template>
          </el-table-column>
          <el-table-column
            v-for="task in visitTaskList"
            :key="task.VisitTaskId"
            prop="date"

            show-overflow-tooltip
            width="150px"
          >
            <template slot="header">
              <div v-if="task.IsCurrentTask">
                <div>
                  {{ task.BlindName }}
                </div>
              </div>
              <div v-else>
                <div>
                  {{ task.BlindName }}
                  <el-button type="text" size="small" @click="previewDicoms(task)">
                    <span class="el-icon-view" />
                  </el-button>
                </div>
              </div>
            </template>
            <template slot-scope="scope">
              <span :style="{color: ((scope.row.isLymphNodes === 1 && scope.row.QuestionMark === 1) || (scope.row.isLymphNodes === 0 && scope.row.QuestionMark === 0)) && (scope.row.LesionType === 0 || scope.row.LesionType === 5) ? '#f66' : '#fff'}">
                <template v-if="task.VisitTaskId === visitTaskId && readingTaskState < 2 && [13,14,15,42].includes(scope.row.QuestionType)">
                  <!-- 是否存在疾病（基线时可修改） -->
                  <template v-if="task.IsBaseLine && scope.row.QuestionType=== 15">
                    <el-select
                      v-if="scope.row.Type==='select' && scope.row.DictionaryCode"
                      v-model="currentExistDisease"
                      size="mini"
                      @change="handleExistDiseaseChange"
                    >
                      <el-option
                        v-for="item of $d[ scope.row.DictionaryCode]"
                        :key="item.id"
                        :value="item.value"
                        :label="item.label"
                      />
                    </el-select>
                  </template>
                  <!-- 整体肿瘤评估（非基线可修改） -->
                  <template v-else-if="!task.IsBaseLine && (scope.row.QuestionType=== 13 || scope.row.QuestionType=== 42)">
                    <el-select
                      v-if="scope.row.Type==='select' && scope.row.DictionaryCode"
                      v-model="currentEvaluateResult"
                      size="mini"
                      @change="handleEvaluateResultChange"
                    >
                      <template v-if="CriterionType === 1 && tLesionCount">
                        <el-option
                          v-for="item of $d[ scope.row.DictionaryCode]"
                          v-show="(!task.IsBaseLine && item.value > -1) && (task.CrterionDictionaryGroup.indexOf(item.raw.CrterionDictionaryGroup) > -1) && (item.value !== 1 && item.value !== 3)"
                          :key="item.id"
                          :value="item.value"
                          :label="item.label"
                        />
                      </template>
                      <template v-else-if="CriterionType === 1 && ntLesionCount">
                        <el-option
                          v-for="item of $d[ scope.row.DictionaryCode]"
                          v-show="(!task.IsBaseLine && item.value > -1) && (task.CrterionDictionaryGroup.indexOf(item.raw.CrterionDictionaryGroup) > -1) && (item.value !== 1)"
                          :key="item.id"
                          :value="item.value"
                          :label="item.label"
                        />
                      </template>
                      <template v-else>
                        <el-option
                          v-for="item of $d[ scope.row.DictionaryCode]"
                          v-show="(!task.IsBaseLine && item.value > -1) && (task.CrterionDictionaryGroup.indexOf(item.raw.CrterionDictionaryGroup) > -1)"
                          :key="item.id"
                          :value="item.value"
                          :label="item.label"
                        />
                      </template>
                    </el-select>
                  </template>
                  <!-- <template v-else-if="task.IsBaseLine && scope.row.QuestionType=== 13">
                    {{ $fd(scope.row.DictionaryCode, currentEvaluateResult) }}
                  </template> -->
                  <!-- 访视点备注（是否存在疾病与系统不一致或者整体肿瘤评估与系统不一致时，必填） -->
                  <!-- tumorEvaluate && task.VisitTaskId === visitTaskId && scope.row.QuestionType=== 14 && (currentEvaluateResult !== tumorEvaluate || currentExistDisease !== isExistDisease) -->
                  <template v-else-if="task.VisitTaskId === visitTaskId && scope.row.QuestionType=== 14 ">
                    <!-- v-if="tumorEvaluate && (currentEvaluateResult !== tumorEvaluate || currentExistDisease !== isExistDisease)" -->
                    <template>
                      <!-- 输入框 -->
                      <el-input
                        v-if="scope.row.Type==='input'"
                        v-model="currentTaskReason"
                        size="mini"
                        @change="evaluateReasonChange"
                      />
                      <el-input
                        v-else-if="scope.row.Type==='textarea'"
                        v-model="currentTaskReason"
                        :autosize="{ minRows: 2, maxRows: 4}"
                        size="mini"
                        maxlength="500"
                        @change="evaluateReasonChange"
                      />
                      <!-- 系统评估结果为：xxx,与当前调整的结果不一致，请填写调整原因 -->
                      <p v-if="currentEvaluateResult !== tumorEvaluate" style="width: 140px;padding:0 2px;white-space: normal;word-break: break-all;word-wrap: break-word;">{{ $t('trials:readingReport:message:msg6') }}<span style="color:red">{{ $fd('OverallAssessment',tumorEvaluate) }}</span>{{ $t('trials:readingReport:message:msg7') }}<span style="color:red">{{ $fd('OverallAssessment',currentEvaluateResult) }}</span>{{ $t('trials:readingReport:message:msg8') }}</p>
                      <p v-else-if="currentExistDisease !== isExistDisease" style="width: 140px;padding:0 2px;white-space: normal;word-break: break-all;word-wrap: break-word;">{{ $t('trials:readingReport:title:sysEvaluationRes') }}<span style="color:red">{{ $fd('ExistDisease',isExistDisease) }}</span>{{ $t('trials:readingReport:message:msg1') }}</p>
                    </template>
                    <!-- <template v-else>
                      <span>{{ currentTaskReason }}</span>
                    </template> -->

                  </template>
                  <template v-else-if="scope.row.DictionaryCode">
                    {{ $fd(scope.row.DictionaryCode, scope.row.Answers[task.VisitTaskId]) }}
                  </template>
                  <template v-else>
                    {{ scope.row.Answers[task.VisitTaskId] }}
                  </template>
                </template>

                <template v-else-if="scope.row.QuestionType=== 15">
                  <el-tooltip v-if="getAnswerInfo(scope.row.Answer,task.VisitTaskId,'IsGlobalChange')" :content="`${$t('trials:reading:warnning:msg55')}${$fd(scope.row.DictionaryCode, getAnswerInfo(scope.row.Answer,task.VisitTaskId,'GlobalChangeAnswer'))}`" placement="top" effect="light">
                    <span style="color:red;"> {{ $fd(scope.row.DictionaryCode, scope.row.Answers[task.VisitTaskId]) }}</span>
                  </el-tooltip>
                  <span v-else>{{ $fd(scope.row.DictionaryCode, scope.row.Answers[task.VisitTaskId]) }}</span>
                </template>

                <template v-else-if="scope.row.QuestionType=== 13 || scope.row.QuestionType=== 42">
                  <el-tooltip v-if="getAnswerInfo(scope.row.Answer,task.VisitTaskId,'IsGlobalChange')" :content="`${$t('trials:reading:warnning:msg55')}${$fd(scope.row.DictionaryCode, getAnswerInfo(scope.row.Answer,task.VisitTaskId,'GlobalChangeAnswer'))}`" placement="top" effect="light">
                    <span style="color:red;"> {{ $fd(scope.row.DictionaryCode, scope.row.Answers[task.VisitTaskId]) }}</span>
                  </el-tooltip>
                  <span v-else>{{ $fd(scope.row.DictionaryCode, scope.row.Answers[task.VisitTaskId]) }}</span>
                </template>
                <template v-else-if="scope.row.QuestionType=== 22">
                  {{ scope.row.Answers[task.VisitTaskId] === '-1' ? $t('trials:readingReport:title:unknow') : scope.row.Answers[task.VisitTaskId] }}
                </template>

                <template v-else-if="scope.row.DictionaryCode">
                  {{ $fd(scope.row.DictionaryCode, scope.row.Answers[task.VisitTaskId]) }}
                </template>
                <template v-else-if="CriterionType === 10">
                  {{ isNaN(parseInt(scope.row.Answers[task.VisitTaskId]))?scope.row.Answers[task.VisitTaskId]:`${scope.row.Answers[task.VisitTaskId]}` }}
                </template>
                <template v-else-if="(scope.row.ValueType === 0 || scope.row.ValueType === 1) && scope.row.Unit">
                  {{ isNaN(parseInt(scope.row.Answers[task.VisitTaskId]))?scope.row.Answers[task.VisitTaskId]:`${scope.row.Answers[task.VisitTaskId]} ${$fd('ValueUnit',scope.row.Unit)}` }}
                </template>
                <template v-else-if="scope.row.ValueType === 2">
                  {{ isNaN(parseInt(scope.row.Answers[task.VisitTaskId]))?scope.row.Answers[task.VisitTaskId]:`${scope.row.Answers[task.VisitTaskId]}%` }}
                </template>
                <template v-else-if="scope.row.Answers && scope.row.Answers.hasOwnProperty(task.VisitTaskId)">
                  {{ scope.row.Answers[task.VisitTaskId] }}
                </template>
              </span>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <!-- 附加评估 -->
    <el-dialog
      v-if="additionalAssessmentsDig.visible"
      :visible.sync="additionalAssessmentsDig.visible"
      :close-on-click-modal="false"
      :title="additionalAssessmentsDig.title"
      width="600px"
    >
      <AdditionalAssessment
        :questions="assessmentQuestions"
        :visit-task-id="visitTaskId"
        @close="additionalAssessmentsDig.visible = false"
        @sign="sign"
      />
    </el-dialog>
    <!-- 签名框 -->
    <el-dialog
      v-if="signVisible"
      :visible.sync="signVisible"
      :close-on-click-modal="false"
      width="600px"
      custom-class="base-dialog-wrapper"
    >
      <div slot="title">
        <span style="font-size:18px;">{{ $t('common:dialogTitle:sign') }}</span>
        <span style="font-size:12px;margin-left:5px">{{ `(${$t('common:label:sign')}${ currentUser })` }}</span>
      </div>
      <SignForm ref="signForm" :sign-code-enum="signCode" @closeDialog="closeSignDialog" />
    </el-dialog>
  </div>
</template>
<script>
import { getReadingReportEvaluation, changeDicomReadingQuestionAnswer, submitDicomVisitTask, verifyVisitTaskQuestions, getTaskAdditionalQuestion } from '@/api/trials'
import { getAutoCutNextTask } from '@/api/user'
import DicomEvent from './DicomEvent'
import const_ from '@/const/sign-code'
import SignForm from '@/views/trials/components/newSignForm'
import { getToken } from '@/utils/auth'
import store from '@/store'
import { mapGetters } from 'vuex'
import { changeURLStatic } from '@/utils/history.js'
import AdditionalAssessment from './AdditionalAssessment'
export default {
  name: 'ReportPage',
  components: { SignForm, AdditionalAssessment },
  props: {
    visitTaskId: {
      type: String,
      required: true
    },
    questionFormChangeState: {
      type: Boolean,
      default() {
        return false
      }
    }
  },
  data() {
    return {
      currentUser: zzSessionStorage.getItem('userName'),
      signVisible: false,
      signCode: null,
      visitTaskList: [],
      taskQuestions: [],
      loading: false,
      answers: [],
      readingTaskState: 2,
      tumorEvaluate: null,
      currentEvaluateResult: null,
      isExistDisease: null,
      currentExistDisease: null,
      currentTaskReason: '',
      answerArr: [],
      questions: [],
      isShowDetail: false,
      CriterionType: 0,
      height: 0,
      additionalAssessmentsDig: { visible: false, title: this.$t('trials:trials-panel:setting:reading-unit:TrialCriterionAdditionalAssessmentTypeList') },
      assessmentQuestions: [],
      tLesionCount: null,
      ntLesionCount: null,
      openWindow: null
    }
  },
  computed: {
    ...mapGetters(['language'])
  },
  watch: {
    taskQuestions() {
      this.$nextTick(() => {
        this.getTableHeight()
        this.$refs.reportList && this.$refs.reportList.doLayout()
        this.setScrollTop()
      })
    }
  },
  created() { this.getTableHeight() },
  mounted() {
    this.CriterionType = parseInt(localStorage.getItem('CriterionType'))

    window.addEventListener('resize', () => {
      this.handleResize()
      this.setScrollTop()
    })
    DicomEvent.$on('getReportInfo', isRefresh => {
      if (!isRefresh) return
      this.getReportInfo()
    })
    DicomEvent.$on('resetOpenWindow', () => {
      if (this.openWindow) {
        this.openWindow.close()
      }
    })
    this.getReportInfo()
  },
  beforeDestroy() {
    DicomEvent.$off('getReportInfo')
    DicomEvent.$off('resetOpenWindow')
    if (this.openWindow) {
      this.openWindow.close()
    }
  },
  methods: {
    myConfirm(msg) {
      return new Promise(resolve => {
        this.$confirm(msg, {
          type: 'warning',
          showCancelButton: true
        }).then(() => {
          resolve(true)
        }).catch(() => {
          resolve(false)
        })
      })
    },
    async beforeLeave() {
      if (this.questionFormChangeState) {
        var msg = this.$t('trials:readingReport:message:msg5')
        var isgo = await this.myConfirm(msg)
        if (!isgo) {
          return Promise.resolve(true)
        }
      }
      var list = null
      DicomEvent.$emit('getAllUnSaveLesions', val => {
        list = val
      })
      if (list.length > 0) {
        var arr = []
        list.map(i => {
          arr.push(i.lessionName)
        })
        // 请先保存${arr.join('、')}病灶信息！
        let msg = this.$t('trials:reading:warnning:msg200')
        msg = msg.replace('xxx', arr.join(this.language === 'en' ? ', ' : '、'))
        this.$confirm(msg, {
          type: 'warning',
          showCancelButton: false
        }).then(() => {
        }).catch(() => {
        })
      } else {
        this.handleConfirm()
      }
    },
    getAnswerInfo(answerArr, visitTaskId, prop) {
      var i = answerArr.findIndex(i => i.VisitTaskId === visitTaskId)
      if (i === -1) return ''
      var val = answerArr[i][prop]
      return isNaN(parseInt(val)) ? val : parseInt(val)
    },
    getTableHeight() {
      this.height = window.innerHeight - 170
    },
    getReportInfo(IsCalculate) {
      this.loading = true
      var params = {
        visitTaskId: this.visitTaskId,
        trialId: this.$router.currentRoute.query.trialId,
        IsCalculate: IsCalculate !== false
      }
      getReadingReportEvaluation(params).then(res => {
        this.readingTaskState = res.Result.ReadingTaskState
        this.tumorEvaluate = res.Result.CalculateResult.TumorEvaluate ? parseInt(res.Result.CalculateResult.TumorEvaluate) : null
        this.isExistDisease = res.Result.CalculateResult.IsExistDisease ? parseInt(res.Result.CalculateResult.IsExistDisease) : null
        this.answerArr = []
        this.questions = res.Result.TaskQuestions.concat()
        this.visitTaskList = res.Result.VisitTaskList
        var taskQuestions = this.getQuestions(res.Result.TaskQuestions, !this.isShowDetail, null, null)
        this.taskQuestions = []
        taskQuestions.forEach(item => {
          this.$set(this.taskQuestions, this.taskQuestions.length, item)
        })
        const tLesion = res.Result.LesionCountList.find(i => i.LesionType === 0)
        this.tLesionCount = tLesion ? tLesion.Count : 0
        const ntLesion = res.Result.LesionCountList.find(i => i.LesionType === 1)
        this.ntLesionCount = ntLesion ? ntLesion.Count : 0
        this.setScrollTop()
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    setScrollTop(a) {
      setTimeout(() => {
        this.$nextTick(() => {
          if (this.$refs.reportList) {
            this.getTableHeight()
            this.$refs.reportList.bodyWrapper.scrollTop = this.$refs.reportList.bodyWrapper.scrollHeight
            this.$refs.reportList.bodyWrapper.scrollTop = this.$refs.reportList.bodyWrapper.scrollHeight
          }
        })
      }, 50)
    },
    getQuestions(questions, isNTFilterLength, lesionType, isLymphNodes) {
      const arr = []
      if (questions.length !== 0) {
        questions.forEach((item) => {
          // 过滤病灶标识  病灶名称  部位  器官  位置  是否淋巴结
          // 非靶病灶和新病灶 过滤长径和短径信息
          // 非淋巴结靶病灶 过滤短径

          lesionType = item.LesionType
          var filterArr = [7]
          if ((item.LesionType === 1 || item.LesionType === 2 || item.LesionType === 6 || item.LesionType === 7 || item.LesionType === 8) && isNTFilterLength) {
            filterArr = [0, 1, 3, 4, 5, 6, 2, 8, 10, 7]
          } else {
            filterArr = [3, 4, 5, 6, 2, 8, 10, 7]
          }
          if ((lesionType === 0 || lesionType === 5) && isLymphNodes === 0 && !this.isShowDetail && (this.CriterionType === 1 || this.CriterionType === 3 || this.CriterionType === 17)) {
            filterArr.push(1)
          }

          if (isLymphNodes === 0) {
            filterArr.push(1)
          }
          if (!(filterArr.includes(item.QuestionMark))) {
            const obj = item
            obj.Answers = {}
            if (item.RowIndex > 0) {
              try {
                var idx = item.Childrens.findIndex(i => i.QuestionMark === 8)
                var idxLoc = item.Childrens.findIndex(i => i.QuestionMark === 10)
                var state = item.Childrens.findIndex(i => i.QuestionMark === 7)
                if (idx > -1) {
                  if (item.Childrens[idx].Answer.length > 0) {
                    var k = item.Childrens[idx].Answer.findIndex(v => v.Answer !== '')
                    var part = ''
                    if (obj.IsCanEditPosition) {
                      part = `${item.Childrens[idx].Answer[k].Answer}--${item.Childrens[idxLoc].Answer[k].Answer}`
                    } else {
                      part = `${item.Childrens[idx].Answer[k].Answer}`
                    }
                    if (item.SplitOrMergeLesionName && k > -1) {
                      // obj.QuestionName = `${obj.QuestionName} --${part} (Split from ${item.SplitOrMergeLesionName})`
                      obj.QuestionName = `${obj.QuestionName} --${part}`
                      var Answers = {}
                      if (state >= 0) {
                        this.visitTaskList.forEach(v => {
                          const o = item.Childrens[state].Answer.find(v1 => {
                            return v1.VisitTaskId === v.VisitTaskId
                          })
                          if (o) {
                            Answers[o.VisitTaskId] = this.$fd(item.Childrens[state].DictionaryCode, parseInt(o.Answer))
                          }
                        })
                      }
                      this.$set(obj, 'Answers', Answers)
                      // obj.QuestionName = `${obj.QuestionName} `
                    } else if (!item.SplitOrMergeLesionName && k > -1) {
                      obj.QuestionName = `${obj.QuestionName}--${part}`
                      const Answers = {}
                      if (state >= 0) {
                        this.visitTaskList.forEach(v => {
                          const o = item.Childrens[state].Answer.find(v1 => {
                            return v1.VisitTaskId === v.VisitTaskId
                          })
                          if (o) {
                            Answers[o.VisitTaskId] = this.$fd(item.Childrens[state].DictionaryCode, parseInt(o.Answer))
                          }
                        })
                      }
                      this.$set(obj, 'Answers', Answers)
                      // obj.QuestionName = `${obj.QuestionName} `
                    } else {
                      obj.QuestionName = `${obj.QuestionName} `
                    }
                    if (item.ReportMark) {
                      obj.QuestionName = `${obj.QuestionName} (${item.ReportMark})`
                    }

                    if (this.CriterionType === 1 || this.CriterionType === 3 || this.CriterionType === 17) {
                      var idxLymphNode = item.Childrens.findIndex(i => i.QuestionMark === 2)
                      if (idxLymphNode > -1) {
                        isLymphNodes = item.Childrens[idxLymphNode].Answer[k].Answer ? parseInt(item.Childrens[idxLymphNode].Answer[k].Answer) : null
                        item.Childrens.forEach(v => {
                          this.$set(v, 'isLymphNodes', isLymphNodes)
                        })
                      }
                    }
                  }
                }
              } catch (e) {
                console.log(e)
              }
            }
            item.Answer.forEach(i => {
              if (item.DictionaryCode) {
                obj.Answers[i.VisitTaskId] = i.Answer ? parseInt(i.Answer) : null
              } else {
                obj.Answers[i.VisitTaskId] = i.Answer
              }
            })
            if (item.QuestionType === 15) {
              this.currentExistDisease = obj.Answers[this.visitTaskId]
              this.answerArr.push({ id: item.QuestionId, answer: obj.Answers[this.visitTaskId], questionType: 15 })
            }
            if (item.QuestionType === 13 || item.QuestionType === 42) {
              this.currentEvaluateResult = obj.Answers[this.visitTaskId]
              this.answerArr.push({ id: item.QuestionId, answer: obj.Answers[this.visitTaskId], questionType: item.QuestionType })
            }
            if (item.QuestionType === 14) {
              this.currentTaskReason = obj.Answers[this.visitTaskId]
              this.answerArr.push({ id: item.QuestionId, answer: obj.Answers[this.visitTaskId], questionType: 14 })
            }
            if (item.Childrens.length >= 1) {
              obj.Childrens = this.getQuestions(item.Childrens, isNTFilterLength, lesionType, isLymphNodes)
            }
            arr.push(obj)
          }
        })
      }
      return arr
    },
    handleShowDetail(val) {
      this.getReportInfo()
      // this.taskQuestions = this.getQuestions(res.Result.TaskQuestions, !this.isShowDetail, null)
    },
    handleExistDiseaseChange(val) {
      // this.currentExistDisease = parseInt(val)
      if (val === this.isExistDisease && this.tumorEvaluate === this.currentEvaluateResult) {
        this.currentTaskReason = ''
        this.evaluateReasonChange('')
      }
      this.currentTaskReason = ''
      this.evaluateReasonChange('')
      var idx = this.answerArr.findIndex(i => i.questionType === 15)
      if (idx > -1) {
        this.answerArr[idx].answer = val
      }
    },
    handleEvaluateResultChange(val) {
      // this.currentEvaluateResult = parseInt(val)
      if (val === this.tumorEvaluate && this.isExistDisease === this.currentExistDisease) {
        this.currentTaskReason = ''
        this.evaluateReasonChange('')
      }
      this.currentTaskReason = ''
      this.evaluateReasonChange('')
      var idx = this.answerArr.findIndex(i => i.questionType === 13 || i.questionType === 42)
      if (idx > -1) {
        this.answerArr[idx].answer = val
      }
      this.setScrollTop()
    },

    evaluateReasonChange(val) {
      var idx = this.answerArr.findIndex(i => i.questionType === 14)
      if (idx > -1) {
        this.answerArr[idx].answer = val
      }
    },
    async handleConfirm() {
      await this.handleSave(false)
      await this.verifyVisitTaskQuestions()
      var i = this.visitTaskList.findIndex(i => i.VisitTaskId === this.visitTaskId)
      var isBaseline = this.visitTaskList[i].IsBaseLine
      if (isBaseline) {
        this.assessmentQuestions = await this.getAdditionalAssessments()
        if (this.assessmentQuestions.length > 0) {
          // 打开附加评估框
          this.additionalAssessmentsDig.visible = true
        } else {
          const { ImageAssessmentReportConfirmation } = const_.processSignature
          this.signCode = ImageAssessmentReportConfirmation
          this.signVisible = true
        }
      } else {
        const { ImageAssessmentReportConfirmation } = const_.processSignature
        this.signCode = ImageAssessmentReportConfirmation
        this.signVisible = true
      }
    },
    sign() {
      this.additionalAssessmentsDig.visible = false
      this.$nextTick(() => {
        const { ImageAssessmentReportConfirmation } = const_.processSignature
        this.signCode = ImageAssessmentReportConfirmation
        this.signVisible = true
      })
    },
    // 附加评估
    getAdditionalAssessments() {
      return new Promise((resolve) => {
        this.loading = true
        getTaskAdditionalQuestion({ visitTaskId: this.visitTaskId }).then(res => {
          this.loading = false
          resolve(res.Result)
        }).catch(() => {
          this.loading = false
          resolve()
        })
      })
    },
    verifyVisitTaskQuestions() {
      return new Promise((resolve, reject) => {
        this.loading = true
        verifyVisitTaskQuestions({ visitTaskId: this.visitTaskId }).then(res => {
          this.loading = false
          resolve()
        }).catch(() => {
          this.loading = false
          reject()
        })
      })
    },
    handleResize() {
      this.$nextTick(() => {
        this.$refs.reportList && this.$refs.reportList.doLayout()
      })
    },
    // 关闭签名框
    closeSignDialog(isSign, signInfo) {
      if (isSign) {
        this.signConfirm(signInfo)
      } else {
        this.signVisible = false
      }
    },
    // 签名并确认
    signConfirm(signInfo) {
      this.loading = true
      var params = {
        data: {
          visitTaskId: this.visitTaskId
        },
        signInfo: signInfo
      }
      submitDicomVisitTask(params).then(async res => {
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          if (this.$refs['signForm']) {
            this.$refs['signForm'].btnLoading = false
          }

          this.signVisible = false
          // window.location.reload()
          // window.opener.postMessage('refreshTaskList', window.location)

          // 设置当前任务阅片状态为已读
          this.readingTaskState = 2
          await store.dispatch('reading/setVisitTaskReadingTaskState', { visitTaskId: this.visitTaskId, readingTaskState: 2 })
          // DicomEvent.$emit('setReadingState', 2)
          await store.dispatch('reading/setCurrentReadingTaskState', 2)
          var isAutoTask = await this.getAutoTaskVal()
          if (isAutoTask) {
            DicomEvent.$emit('getNextTask')
          } else {
            // '当前阅片任务已完成，是否进入下一个阅片任务？'
            this.$confirm(this.$t('trials:readingReport:message:msg4'), {
              type: 'warning',
              distinguishCancelAndClose: true
            })
              .then(() => {
                DicomEvent.$emit('getNextTask')
              })
              .catch(action => {
                changeURLStatic('visitTaskId', this.visitTaskId)
              })
          }

          window.opener.postMessage('refreshTaskList', window.location)
          DicomEvent.$emit('readingPageUpdate', { readingTaskState: 2 })
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
        if (this.$refs['signForm'] && this.$refs['signForm'].btnLoading) {
          this.$refs['signForm'].btnLoading = false
        }
      })
    },
    getAutoTaskVal() {
      return new Promise((resolve, reject) => {
        getAutoCutNextTask().then(res => {
          resolve(res.Result.AutoCutNextTask)
        }).catch(() => { reject() })
      })
    },
    previewDicoms(task) {
      if (this.openWindow) {
        this.openWindow.close()
      }
      var token = getToken()
      var subjectCode = this.$router.currentRoute.query.subjectCode
      var subjectId = this.$router.currentRoute.query.subjectId
      var trialId = this.$router.currentRoute.query.trialId
      var isReadingTaskViewInOrder = this.$router.currentRoute.query.isReadingTaskViewInOrder
      var criterionType = this.$router.currentRoute.query.criterionType
      var readingTool = this.$router.currentRoute.query.readingTool
      var path = `/readingDicoms?trialId=${trialId}&subjectCode=${subjectCode}&subjectId=${subjectId}&visitTaskId=${task.VisitTaskId}&isReadingTaskViewInOrder=${isReadingTaskViewInOrder}&criterionType=${criterionType}&readingTool=${readingTool}&TokenKey=${token}`
      const routeData = this.$router.resolve({ path })
      this.openWindow = window.open(routeData.href, '_blank')
    },
    handleSave(isPrompt) {
      return new Promise((resolve, reject) => {
        var isBeill
        var evaluateResult = ''
        var evaluateAjustReason = ''
        this.answers = []
        var isExistEvaluateResult = false
        this.answerArr.map(item => {
          if (item.questionType === 13 || item.questionType === 42) {
            evaluateResult = item.answer
            isExistEvaluateResult = true
          }
          if (item.questionType === 14) {
            evaluateAjustReason = item.answer
          }
          if (item.questionType === 15) {
            isBeill = item.answer
          }
          this.answers.push({ id: item.id, answer: item.answer })
        })
        console.log(this.currentExistDisease, this.isExistDisease, evaluateAjustReason, isBeill)
        if (this.currentExistDisease !== this.isExistDisease && !evaluateAjustReason) {
          this.$confirm(this.$t('trials:readingReport:message:msg2'), {
            type: 'warning',
            showCancelButton: false,
            callback: action => {}
          })
          reject()
          return
        }
        if (isExistEvaluateResult && evaluateResult === null) {
          // 请将疗效评估信息填写完整
          this.$confirm(this.$t('trials:readingReport:message:msg2'), {
            type: 'warning',
            showCancelButton: false,
            callback: action => {}
          })
          reject()
          return
        }
        if (isExistEvaluateResult && (evaluateResult !== this.tumorEvaluate) && !evaluateAjustReason) {
          // 请填写整体评估调整原因
          this.$confirm(this.$t('trials:readingReport:message:msg3'), {
            type: 'warning',
            showCancelButton: false,
            callback: action => {}
          })
          reject()
          return
        }
        this.loading = true
        var params = {
          visitTaskId: this.visitTaskId,
          answers: this.answers
        }
        changeDicomReadingQuestionAnswer(params).then(res => {
          if (isPrompt) {
            this.$message.success(this.$t('common:message:savedSuccessfully'))
          }
          this.loading = false
          resolve()
        }).catch(() => {
          this.loading = false
          reject()
        })
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.report-wrapper{

  height: 100%;
  padding: 10px 0px;
  // background-color: #fff;
  background-color: #000;
  ::-webkit-scrollbar {
    width: 7px;
    height: 7px;
  }
  ::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: #d0d0d0;
  }
  .report-header{
    display: flex;
  }
  .el-card{
    display:flex;flex-direction: column;height: 100%;
    background-color: #000;
    color: #ffffff;
    border:none;
    /deep/ .el-card__body{
      flex: 1;
    }
  }

  // /deep/ .el-table__cell{
  //   background-color: #000;
  //   color: #ffffff;
  // }
  // /deep/ .el-table{
  //   background-color: #000;
  //   color: #ffffff;
  // }
  // /deep/ .el-table__cell{
  //   background-color: #000;
  //   color: #ffffff;
  // }

  /deep/ .el-table, .el-table__expanded-cell {
    background-color: #000;
    color: #fff;
    border-color:#444444;
  }

  /deep/ .el-table th, .el-table tr {
    background-color: #000;
    color: #fff;
    border-color:#444444;
  }
  /deep/ .el-table__body tr > td{
    background-color:#000 !important;
    color: #fff;
    border-color:#444444;
  }
  /deep/ .el-table__body tr:hover > td{
    background-color:#858282 !important;
    color: #fff;
    border-color:#444444;
  }
  /deep/ .el-table--border th.gutter:last-of-type{
    border: none;
  }
  /deep/ .el-card__header{
    border: none;
    padding: 10px;
  }
}
/deep/ .el-switch__label{
  color:#fff;
}
/deep/ .el-switch__label.is-active{
  color: #428bca;
}
</style>
