<template>
  <div class="report-wrapper">
    <el-card v-loading="loading" shadow="never" style="display:flex;flex-direction: column;">
      <div slot="header" class="clearfix report-header">
        <h3 style="margin:0;padding:0;">{{ $t('trials:readingReport:title:eicrf') }}</h3>
        <div style="margin-left:auto">
          <el-button v-if="readingTaskState < 2" type="primary" size="small" @click="skipTask">
            <!-- 跳过 -->
            {{ $t('trials:readingReport:button:skip') }}
          </el-button>
          <el-button v-if="readingTaskState < 2" type="primary" size="small" @click="getReportInfo">{{
            $t('trials:readingReport:button:refresh') }}</el-button>
          <el-button v-if="readingTaskState < 2" type="primary" size="small" @click="handleSave(true)">{{
            $t('common:button:save') }}</el-button>
          <el-button v-if="readingTaskState < 2" type="primary" size="small" @click="handleConfirm">{{
            $t('common:button:submit') }}</el-button>
        </div>
      </div>
      <div style="flex: 1">
        <el-table v-if="taskQuestions.length > 0" ref="reportList" v-adaptive="{ bottomOffset: 0 }"
          :data="taskQuestions" row-key="Id" border default-expand-all height="100"
          :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">{{ scope.row.BlindName ? scope.row.QuestionName :
                scope.row.QuestionName }}
                <svg-icon v-if="scope.row.ShowChartTypeEnum > 0" icon-class="readingChart"
                  class="svg-icon svg-readingChart-mini" @click.stop="(e) => handleReadingChart({
                    e,
                    data: {
                      QuestionId: scope.row.RowIndex ? null : scope.row.QuestionId,
                      TableQuestionId: scope.row.RowIndex ? scope.row.TableQuestionId : null,
                      RowIndex: scope.row.RowIndex ? scope.row.RowIndex : null,
                      QuestionName: scope.row.QuestionName
                    }
                  })" />
              </span>
              <span v-else style="font-weight: bold;font-size: 16px;color: #f44336;">
                {{ 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="200px">
            <template slot="header">
              <div v-if="task.IsCurrentTask">
                {{ task.BlindName }}
              </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">
              <template
                v-if="readingTaskState < 2 && task.VisitTaskId === visitTaskId && (scope.row.Type === 'input' || scope.row.Type === 'number' || scope.row.Type === 'select' || scope.row.Type === 'textarea' || scope.row.Type === 'radio')">
                <!-- 输入框 -->
                <div>
                  <template
                    v-if="!((task.IsBaseLine && scope.row.LimitEdit === 1) || (!task.IsBaseLine && scope.row.LimitEdit === 2) || scope.row.LimitEdit === 0)">
                    <!-- {{ `${questionForm[scope.row.QuestionId] instanceof Array ?  questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId] : questionForm[scope.row.QuestionId]}` }} -->
                  </template>
                  <el-input
                    v-else-if="questionForm[scope.row.QuestionId] instanceof Array && (scope.row.Type === 'input' || scope.row.Type === 'textarea') && !scope.row.IsShowInDicom && ((task.IsBaseLine && scope.row.LimitEdit === 1) || (!task.IsBaseLine && scope.row.LimitEdit === 2) || scope.row.LimitEdit === 0)"
                    v-model="questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId]"
                    size="mini" />
                  <span
                    v-else-if="questionForm[scope.row.QuestionId] instanceof Array && (scope.row.Type === 'input' || scope.row.Type === 'textarea')">
                    {{ questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId] }}
                  </span>
                  <el-input
                    v-else-if="(scope.row.Type === 'input' || scope.row.Type === 'textarea') && !scope.row.IsShowInDicom && ((task.IsBaseLine && scope.row.LimitEdit === 1) || (!task.IsBaseLine && scope.row.LimitEdit === 2) || scope.row.LimitEdit === 0)"
                    v-model="questionForm[scope.row.QuestionId]" size="mini" />
                  <span v-else-if="scope.row.Type === 'input' || scope.row.Type === 'textarea'">
                    {{ questionForm[scope.row.QuestionId] }}
                  </span>
                  <el-select
                    v-else-if="questionForm[scope.row.QuestionId] instanceof Array && (scope.row.Type === 'select' || scope.row.Type === 'radio') && !scope.row.IsShowInDicom && ((task.IsBaseLine && scope.row.LimitEdit === 1) || (!task.IsBaseLine && scope.row.LimitEdit === 2) || scope.row.LimitEdit === 0)"
                    v-model="questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId]"
                    size="mini" clearable>
                    <template>
                      <el-option v-for="val in scope.row.TypeValue.split('|')" :key="val" :label="val" :value="val" />
                    </template>
                  </el-select>
                  <span v-else-if="questionForm[scope.row.QuestionId] instanceof Array && scope.row.Type === 'select'">
                    {{ questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId] }}
                  </span>
                  <el-select
                    v-else-if="(scope.row.Type === 'select' || scope.row.Type === 'radio' || (scope.row.Type === 'number' && scope.row.TypeValue)) && !scope.row.IsShowInDicom && ((task.IsBaseLine && scope.row.LimitEdit === 1) || (!task.IsBaseLine && scope.row.LimitEdit === 2) || scope.row.LimitEdit === 0)"
                    v-model="questionForm[scope.row.QuestionId]" size="mini" clearable
                    @focus="() => { questionId = scope.row.QuestionId }">
                    <template>
                      <el-option v-for="val in scope.row.TypeValue.split('|')" :key="val" :label="val" :value="val" />
                    </template>
                  </el-select>
                  <span v-else-if="scope.row.Type === 'select' || scope.row.Type === 'radio'">
                    {{ questionForm[scope.row.QuestionId] }}
                  </span>
                  <el-input
                    v-else-if="scope.row.DataSource !== 1 && questionForm[scope.row.QuestionId] instanceof Array && scope.row.Type === 'number' && (scope.row.xfIndex || scope.row.xfIndex === 0) && !scope.row.IsShowInDicom && ((task.IsBaseLine && scope.row.LimitEdit === 1) || (!task.IsBaseLine && scope.row.LimitEdit === 2) || scope.row.LimitEdit === 0)"
                    v-model="questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId]"
                    :disabled="scope.row.DataSource === 1" size="mini"
                    @blur="limitBlur(questionForm[scope.row.QuestionId][scope.row.xfIndex], scope.row.TableQuestionId, scope.row.ValueType)"
                    @focus="() => { questionId = scope.row.QuestionId }">
                    <template v-if="scope.row.Unit !== 0" slot="append">{{ scope.row.Unit !== 4 ? $fd('ValueUnit',
                      scope.row.Unit) : scope.row.CustomUnit }}</template>
                    <template v-else-if="scope.row.ValueType === 2" slot="append">%</template>
                  </el-input>
                  <span
                    v-else-if="questionForm[scope.row.QuestionId] instanceof Array && scope.row.Type === 'number' && (scope.row.xfIndex || scope.row.xfIndex === 0)">
                    <template v-if="(scope.row.ValueType === 0 || scope.row.ValueType === 1) && scope.row.Unit">
                      {{
                        isNaN(parseInt(questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId]))
                          ?
                          questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId] :
                          `${questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId]}
                      ${scope.row.Unit !== 4 ? $fd('ValueUnit', scope.row.Unit) : scope.row.CustomUnit}` }}
                    </template>
                    <template v-else-if="scope.row.ValueType === 2">
                      {{
                        isNaN(parseInt(questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId]))
                          ?
                          questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId] :
                          `${questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId]}
                      %` }}
                    </template>
                    <template v-else>
                      {{
                        isNaN(parseInt(questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId]))
                          ?
                          questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId] :
                          `${questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId]}`
                      }}
                    </template>
                  </span>
                  <el-input
                    v-else-if="scope.row.DataSource !== 1 && scope.row.Type === 'number' && !scope.row.IsShowInDicom && ((task.IsBaseLine && scope.row.LimitEdit === 1) || (!task.IsBaseLine && scope.row.LimitEdit === 2) || scope.row.LimitEdit === 0)"
                    v-model="questionForm[scope.row.QuestionId]" :disabled="scope.row.DataSource === 1" size="mini"
                    @blur="limitBlur(questionForm, scope.row.QuestionId, scope.row.ValueType)"
                    @focus="() => { questionId = scope.row.QuestionId }">
                    <template v-if="scope.row.Unit !== 0" slot="append">{{ scope.row.Unit !== 4 ? $fd('ValueUnit',
                      scope.row.Unit) : scope.row.CustomUnit }}</template>
                    <template v-else-if="scope.row.ValueType === 2" slot="append">%</template>
                  </el-input>
                  <span v-else-if="scope.row.Type === 'number'">
                    <template v-if="(scope.row.ValueType === 0 || scope.row.ValueType === 1) && scope.row.Unit">
                      {{ isNaN(parseInt(questionForm[scope.row.QuestionId])) ?
                        questionForm[scope.row.QuestionId] : `${questionForm[scope.row.QuestionId]} ${scope.row.Unit !== 4
                          ?
                          $fd('ValueUnit', scope.row.Unit) : scope.row.CustomUnit}` }}
                    </template>
                    <template v-else-if="scope.row.ValueType === 2">
                      {{ isNaN(parseInt(questionForm[scope.row.QuestionId])) ?
                        questionForm[scope.row.QuestionId] : `${questionForm[scope.row.QuestionId]} %` }}
                    </template>
                    <template v-else>
                      {{ isNaN(parseInt(questionForm[scope.row.QuestionId])) ? questionForm[scope.row.QuestionId] :
                        questionForm[scope.row.QuestionId] }}
                    </template>
                  </span>
                </div>
              </template>
              <template v-else-if="scope.row.Type === 'upload' && scope.row.Answers[task.VisitTaskId]">
                <span v-for="(url, index) in scope.row.Answers[task.VisitTaskId].split('|')" :key="url"
                  style="margin-left: 5px;">
                  <el-button v-if="scope.row.Answers[task.VisitTaskId]" type="text" @click="preview(url)">
                    {{ `${$t('trials:noneDicom:title:attachment')}${index + 1}` }}
                  </el-button>
                </span>
              </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="!((task.IsBaseLine && scope.row.LimitEdit === 1) || (!task.IsBaseLine && scope.row.LimitEdit === 2) || scope.row.LimitEdit === 0)" />
              <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]}
                ${scope.row.Unit !== 4 ? $fd('ValueUnit', scope.row.Unit) : scope.row.CustomUnit}` }}
              </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>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 签名框 -->
    <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>

    <!-- 预览文件 -->
    <el-dialog v-if="previewVisible" :visible.sync="previewVisible" :title="$t('common:button:preview')"
      :fullscreen="true" append-to-body custom-class="base-dialog-wrapper">
      <div class="base-modal-body" style="border: 2px solid #ccc; padding: 10px">
        <PreviewFile v-if="previewVisible" :file-path="currentPath" :file-type="currentType" />
      </div>
    </el-dialog>
    <readingChart ref="readingChart_report" />
  </div>
</template>
<script>
import { changeCalculationAnswer, getReadingReportEvaluation, submitDicomVisitTask, verifyVisitTaskQuestions, getQuestionCalculateRelation } from '@/api/trials'
import { setSkipReadingCache } from '@/api/reading'
import { getAutoCutNextTask } from '@/api/user'
import const_ from '@/const/sign-code'
import SignForm from '@/views/trials/components/newSignForm'
import PreviewFile from '@/components/PreviewFile/index'
import { getToken } from '@/utils/auth'
import store from '@/store'
import { openWindow } from "@/utils/splitScreen";
import readingChart from '@/components/readingChart'
export default {
  name: 'CustomizeReportPage',
  components: { SignForm, PreviewFile, readingChart },
  data() {
    return {
      trialId: '',
      visitTaskId: '',
      subjectId: '',
      readingTool: 1,
      criterionType: null,
      isReadingTaskViewInOrder: false,
      currentUser: zzSessionStorage.getItem('userName'),
      signVisible: false,
      signCode: null,
      visitTaskList: [],
      taskQuestions: [],
      loading: false,
      answers: [],
      readingTaskState: 2,
      answerArr: [],
      questions: [],
      CalculationList: [],
      TrialReadingCriterionId: null,
      tableAnswers: {},
      questionForm: {},
      questionId: null,
      taskInfo: null,
      previewVisible: false,
      currentPath: '',
      currentType: '',
      openWindow: null
    }
  },
  watch: {
    questionForm: {
      deep: true,
      immediate: true,
      handler(v, oldv) {
        try {
          if (!v[this.questionId] || !oldv[this.questionId]) return
        } catch (e) {
        }
        this.formItemNumberChange(this.questionId, false)
      }
    }
  },
  async mounted() {
    this.taskInfo = JSON.parse(sessionStorage.getItem('taskInfo'))
    this.trialId = this.$route.query.trialId
    this.visitTaskId = this.taskInfo.VisitTaskId
    this.subjectId = this.taskInfo.SubjectId
    this.criterionType = this.taskInfo.CriterionType
    var digitPlaces = Number(localStorage.getItem('digitPlaces'))
    this.digitPlaces = digitPlaces === -1 ? this.digitPlaces : digitPlaces
    this.TrialReadingCriterionId = this.taskInfo.TrialReadingCriterionId
    window.addEventListener('resize', () => {
      this.handleResize()
    })
    await this.getQuestionCalculateRelation()
    this.getReportInfo()
    document.addEventListener("click", this.foo);
  },
  methods: {
    handleReadingChart(row) {
      let { e, data } = row
      let obj = Object.assign({}, data)
      obj.TrialId = this.$route.query.trialId
      obj.VisitTaskId = this.taskInfo.VisitTaskId
      obj.key = 'readingChart_report'
      let zIndex = 9
      if (obj.RowIndex) {
        zIndex = 9999
      }
      this.$refs.readingChart_report.init(e, obj, zIndex)
    },
    foo() {
      if (!this.$refs.readingChart_report) return false
      this.$refs.readingChart_report.foo()
    },
    limitBlur(questionForm, id, valueType) {
      const value = questionForm[id]
      if (valueType === 0) {
        this.$set(questionForm, id, parseInt(value))
      } else if (valueType === 3) {
        this.$set(questionForm, id, parseFloat(value))
      } else {
        this.$set(questionForm, id, parseFloat(value).toFixed(this.digitPlaces))
      }
    },
    setImageUrl(qid, index, tqid, url, RowId) {
      if (index || index === 0) {
        // 表格问题
        this.$set(this.questionForm[qid][index], tqid, url)
        this.$set(this.questionForm[qid][index], tqid + '_RowId', RowId)
        // this.questionForm[qid][index][tqid] = url
      } else {
        // 非表格问题
        this.questionForm[qid] = url
      }
    },
    getTagterAnswers(list, questionId) {
      list.forEach(v => {
        if (v.QuestionId === questionId) {
          return Object.assign({}, v.Answers)
        } else if (v.Childrens.length > 0) {
          return this.getTagterAnswers(v.Childrens, questionId)
        }
      })
    },
    formItemNumberChange(questionId, isTable) {
      if (isTable) {
        this.CalculationList.forEach((v, i) => {
          var find = v.CalculateQuestionList.filter(o => {
            return o.QuestionId === questionId
          })
          // find的自动计算值number
          if (find) {
            var num = this.logic(v)
            if (num !== false) {
              this.$set(this.questionForm, v.QuestionId, num)
              // this.$emit('setFormItemData', { key: v.QuestionId, val: num })
            }
          }
        })
      } else {
        this.CalculationList.forEach(v => {
          var find = v.CalculateQuestionList.filter(o => {
            return o.TableQuestionId === questionId
          })
          // find的自动计算值number
          if (find) {
            var num = this.logic(v)
            if (num !== false) {
              this.$set(this.questionForm, v.QuestionId, num)
              // this.$emit('setFormItemData', { key: v.QuestionId, val: num })
            }
          }
        })
      }
      // this.$emit('formItemNumberChange')
    },
    getTableAnswers(QuestionId, list) {
      var arr = []
      window.xfList = list
      list.forEach((v, i) => {
        var obj = {}
        v.Childrens.forEach((o) => {
          this.$set(o, 'xfIndex', i)
          obj[o.TableQuestionId + '_RowId'] = o.RowId
          obj[o.TableQuestionId] = o.Answers[this.visitTaskId]
        })
        arr.push(obj)
      })
      return arr
    },
    InitVisitTaskQuestionForm() {
      this.taskQuestions.map((v, i) => {
        if (v.Type === 'group' && v.Childrens.length === 0 && v.Type !== 'table' && v.Type !== 'basicTable') return
        if (!v.IsPage && v.Type !== 'group' && v.Type !== 'summary' && v.Type !== 'table' && v.Type !== 'basicTable' && v.Type !== 'number') {
          this.$set(this.questionForm, v.QuestionId, v.Answers[this.visitTaskId])
        }
        if (v.Type === 'table' || v.Type === 'basicTable') {
          var tableAnswers = this.getTableAnswers(v.QuestionId, v.Childrens, i)
          this.$set(this.questionForm, v.QuestionId, tableAnswers)
          // this.$set(v, 'xfIndex', i)
        }
        if (v.Type === 'number') {
          let val = null
          if (v.ValueType === 0) {
            val = !isNaN(parseFloat(v.Answers[this.visitTaskId])) ? parseInt(v.Answers[this.visitTaskId]) : v.Answers[this.visitTaskId]
          } else if (v.ValueType === 3) {
            val = v.Answers[this.visitTaskId]
          } else {
            val = v.Answers[this.visitTaskId] === '' ? parseFloat(0).toFixed(this.digitPlaces) : v.Answers[this.visitTaskId]
          }
          this.$set(this.questionForm, v.QuestionId, val)
        }
        if (v.Childrens.length > 0) {
          this.setChild(v.Childrens)
        }
      })
      this.formItemNumberChange(this.questionId, false)
    },
    setChild(obj) {
      obj.forEach((i, index) => {
        if (i.Type !== 'group' && i.Type !== 'summary' && i.Id && i.Type !== 'table' && i.Type !== 'basicTable') {
          this.$set(this.questionForm, i.QuestionId, i.Answers[this.visitTaskId])
        }
        if (i.Type === 'table' || i.Type === 'basicTable') {
          var tableAnswers = this.getTableAnswers(i.QuestionId, i.Childrens, index)
          this.$set(this.questionForm, i.QuestionId, tableAnswers)
        }
        if (i.Type === 'number') {
          let val = null
          if (i.ValueType === 0) {
            val = !isNaN(parseFloat(i.Answers[this.visitTaskId])) ? parseInt(i.Answers[this.visitTaskId]) : i.Answers[this.visitTaskId]
          } else if (i.ValueType === 3) {
            val = i.Answers[this.visitTaskId]
          } else {
            val = i.Answers[this.visitTaskId] === '' ? parseFloat(0).toFixed(this.digitPlaces) : i.Answers[this.visitTaskId]
          }
          this.$set(this.questionForm, i.QuestionId, val)
        }
        if (i.Childrens && i.Childrens.length > 0 && i.Type !== 'table' && i.Type !== 'basicTable') {
          this.setChild(i.Childrens)
        }
      })
    },
    getQuestionCalculateRelation() {
      return new Promise(resolve => {
        getQuestionCalculateRelation({
          TrialReadingCriterionId: this.TrialReadingCriterionId
        }).then(res => {
          this.CalculationList = res.Result
          resolve()
        })
      })
    },
    logic(rules, num = 0) {
      let isNE = false
      try {
        if (rules.CalculateQuestionList.length === 0) {
          return false
        }
        let dataArr = []
        rules.CalculateQuestionList.forEach((o, i) => {
          if (this.questionForm[o.TableQuestionId] === 'NE') {
            isNE = true
          }
          if (i === 0) {
            if (rules.CustomCalculateMark > 4) {
              switch (rules.CustomCalculateMark) {
                case 5:
                  this.questionForm[o.QuestionId].forEach((q, qi) => {
                    if (!isNaN(parseFloat(q[o.TableQuestionId]))) {
                      if (qi === 0) {
                        num = parseFloat(q[o.TableQuestionId])
                      } else {
                        num *= parseFloat(q[o.TableQuestionId])
                      }
                    }

                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                  })
                  break
                case 6:
                  this.questionForm[o.QuestionId].forEach((q, qi) => {
                    if (!isNaN(parseFloat(q[o.TableQuestionId]))) {
                      if (qi === 0) {
                        num = isNaN(parseFloat(q[o.TableQuestionId])) ? null : parseFloat(q[o.TableQuestionId])
                      } else {
                        num += isNaN(parseFloat(q[o.TableQuestionId])) ? null : parseFloat(q[o.TableQuestionId])
                      }
                    }

                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                  })
                  break
                case 7:
                  this.questionForm[o.QuestionId].forEach((q, qi) => {
                    if (!isNaN(parseFloat(q[o.TableQuestionId]))) {
                      if (qi === 0) {
                        num = parseFloat(q[o.TableQuestionId])
                      } else {
                        num += parseFloat(q[o.TableQuestionId])
                      }
                    }

                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                  })
                  num = this.questionForm[o.QuestionId].length === 0 ? 0 : num / this.questionForm[o.QuestionId].length
                  break
                case 8:
                  const arr = []
                  this.questionForm[o.QuestionId].forEach(q => {
                    if (!isNaN(parseFloat(q[o.TableQuestionId]))) {
                      arr.push(q[o.TableQuestionId])
                    }

                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                  })
                  num = arr.length === 0 ? 0 : Math.max(...arr)
                  break
                case 9:
                  const arr1 = []
                  this.questionForm[o.QuestionId].forEach(q => {
                    if (!isNaN(parseFloat(q[o.TableQuestionId]))) {
                      arr1.push(q[o.TableQuestionId])
                    }
                    if (q[o.TableQuestionId] === 'NE') {
                      isNE = true
                    }
                  })
                  num = arr1.length === 0 ? 0 : Math.min(...arr1)
                  break
                case 10:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                  }
                  num = dataArr.length === 0 ? 0 : dataArr.reduce((acc, curr) => {
                    return acc + (typeof curr === "number" ? curr : 0);
                  }, 0) / dataArr.length;
                  break;
                case 11:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                  }
                  num = dataArr.length > 0 ? Math.max(...dataArr) : 0;
                  break;
                case 12:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                  }
                  num = dataArr.length > 0 ? Math.min(...dataArr) : 0;
                  break;
                case 13:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                  }
                  num = dataArr.length === 0 ? 0 : dataArr.reduce((acc, curr) => acc && curr) ? 1 : 0
                  break;
                case 14:
                  if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                    dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                  }
                  num = dataArr.length === 0 ? 0 : dataArr.reduce((acc, curr) => acc || curr, 0) ? 1 : 0;
                  break;
              }
            } else {
              if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                num = parseFloat(this.questionForm[o.TableQuestionId])
              }

            }
          } else {
            if (this.questionForm[o.TableQuestionId] === 'NE') {
              isNE = true
            }
            switch (rules.CustomCalculateMark) {
              case 1:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  num += parseFloat(this.questionForm[o.TableQuestionId])
                }

                break
              case 2:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  num -= parseFloat(this.questionForm[o.TableQuestionId])
                }

                break
              case 3:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  num *= parseFloat(this.questionForm[o.TableQuestionId])
                }

                break
              case 4:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  num /= parseFloat(this.questionForm[o.TableQuestionId])
                }

                // num /= parseFloat(this.questionForm[o.TableQuestionId])
                break
              case 10:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                }
                num = dataArr.length === 0 ? 0 : dataArr.reduce((acc, curr) => {
                  return acc + (typeof curr === "number" ? curr : 0);
                }, 0) / dataArr.length;
                break;
              case 11:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                }
                num = dataArr.length > 0 ? Math.max(...dataArr) : 0;
                break;
              case 12:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                }
                num = dataArr.length > 0 ? Math.min(...dataArr) : 0;
                break;
              case 13:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                }
                num = dataArr.length === 0 ? 0 : dataArr.reduce((acc, curr) => acc && curr) ? 1 : 0
                break;
              case 14:
                if (!isNaN(parseFloat(this.questionForm[o.TableQuestionId]))) {
                  dataArr.push(parseFloat(this.questionForm[o.TableQuestionId]))
                }
                num = dataArr.length === 0 ? 0 : dataArr.reduce((acc, curr) => acc || curr, 0) ? 1 : 0;
                break;
            }
          }
        })
      } catch (e) {
        console.log(e)
      }
      if (isNE) {
        return 'NE'
      }
      if (rules.ValueType === 2) {
        num = num * 100
      }
      return isNaN(num) ? '' : isFinite(num) ? num.toFixed(this.digitPlaces) : '∞'
    },
    getReportInfo() {
      this.loading = true
      var params = {
        visitTaskId: this.visitTaskId,
        trialId: this.trialId
      }
      this.taskQuestions = []
      getReadingReportEvaluation(params).then(res => {
        this.readingTaskState = res.Result.ReadingTaskState
        this.answerArr = []
        this.questions = res.Result.TaskQuestions.concat()
        var taskQuestions = this.getQuestions(res.Result.TaskQuestions)
        taskQuestions.forEach(item => {
          this.$set(this.taskQuestions, this.taskQuestions.length, item)
        })
        this.visitTaskList = res.Result.VisitTaskList
        this.InitVisitTaskQuestionForm()
        this.handleResize()
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    getQuestions(questions) {
      const arr = []
      if (questions.length !== 0) {
        questions.forEach((item) => {
          const obj = item
          this.$set(obj, 'Answers', {})
          item.Answer.forEach(i => {
            if (item.DictionaryCode) {
              this.$set(obj.Answers, i.VisitTaskId, i.Answer ? parseInt(i.Answer) : null)
              // obj.Answers[i.VisitTaskId] = i.Answer ? parseInt(i.Answer) : null
            } else {
              if (item.Type === 'number') {
                let val = null
                if (item.ValueType === 0) {
                  val = !isNaN(parseFloat(i.Answer)) ? parseInt(i.Answer) : i.Answer
                } else if (item.ValueType === 3) {
                  val = i.Answer
                } else {
                  val = isNaN(parseFloat(i.Answer)) ? i.Answer : parseFloat(i.Answer).toFixed(this.digitPlaces)
                }
                this.$set(obj.Answers, i.VisitTaskId, val)
              } else {
                this.$set(obj.Answers, i.VisitTaskId, i.Answer)
              }
              // obj.Answers[i.VisitTaskId] = i.Answer
            }
          })
          if (item.Childrens.length >= 1) {
            obj.Childrens = this.getQuestions(item.Childrens)
          }
          arr.push(obj)
        })
      }
      return arr
    },
    handleShowDetail(val) {
      this.getReportInfo()
      // this.taskQuestions = this.getQuestions(res.Result.TaskQuestions, !this.isShowDetail, null)
    },
    async handleConfirm() {
      await this.handleSave(false)
      await this.verifyVisitTaskQuestions()
      const { ImageAssessmentReportConfirmation } = const_.processSignature
      this.signCode = ImageAssessmentReportConfirmation
      this.signVisible = true
    },
    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
      }
    },
    // 签名并确认
    async signConfirm(signInfo) {
      this.loading = true
      try {
        var params = {
          data: {
            visitTaskId: this.visitTaskId
          },
          signInfo: signInfo
        }
        const res = await submitDicomVisitTask(params)
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          if (this.$refs['signForm']) {
            this.$refs['signForm'].btnLoading = false
          }

          this.signVisible = false

          // 设置当前任务阅片状态为已读
          this.readingTaskState = 2
          this.taskInfo.ReadingTaskState = 2
          localStorage.setItem('taskInfo', JSON.stringify(this.taskInfo))
          store.dispatch('noneDicomReview/setCurrentTaskState', 2)
          window.opener.postMessage('refreshTaskList', window.location)
          const res = await getAutoCutNextTask({ imageToolType: 2 })
          const isAutoTask = res.Result.AutoCutNextTask
          if (isAutoTask) {
            window.location.reload()
          } else {
            // '当前阅片任务已完成，是否进入下一个阅片任务？'
            this.$confirm(this.$t('trials:readingReport:message:msg4'), {
              type: 'warning',
              distinguishCancelAndClose: true
            })
              .then(() => {
                window.location.reload()
              })
              .catch(action => {
                // changeURLStatic('visitTaskId', this.visitTaskId)
              })
          }
        }
        this.loading = false
      } catch (e) {
        console.log(e)
        this.loading = false
        if (this.$refs['signForm'] && this.$refs['signForm'].btnLoading) {
          this.$refs['signForm'].btnLoading = false
        }
      }
    },
    async previewDicoms(task) {
      var token = getToken()
      // var subjectCode = this.$router.currentRoute.query.subjectCode
      var subjectCode = localStorage.getItem('subjectCode')
      var subjectId = this.subjectId
      var trialId = this.trialId
      var isReadingTaskViewInOrder = this.isReadingTaskViewInOrder
      var criterionType = this.criterionType
      var readingTool = this.readingTool
      var trialReadingCriterionId = this.$router.currentRoute.query.TrialReadingCriterionId
      var path = `/noneDicomReading?TrialReadingCriterionId=${trialReadingCriterionId}&trialId=${trialId}&subjectCode=${subjectCode}&subjectId=${subjectId}&visitTaskId=${task.VisitTaskId}&isReadingTaskViewInOrder=${isReadingTaskViewInOrder}&criterionType=${criterionType}&readingTool=${readingTool}&TokenKey=${token}`
      const routeData = this.$router.resolve({ path })
      const res = await getAutoCutNextTask({ imageToolType: 2 })
      let IsDoubleScreen = false
      if (res.IsSuccess) {
        IsDoubleScreen = res.Result.IsDoubleScreen
      }
      if (IsDoubleScreen) {
        this.openWindow = await openWindow(routeData.href)
        if (!this.openWindow) {
          let html = `<div><span>${this.$t("trials:reading:tip:MultiScreen2")}</span><a style="color:#409EFF"
              href="/screen.pdf"
              target="blank">${this.$t("trials:reading:tip:openFile")}</a></div>`
          let confirm = await this.$confirm(html, '', { dangerouslyUseHTMLString: true })
          if (!confirm) return false
          this.openWindow = await openWindow(routeData.href, '', true)
        }
      } else {
        this.openWindow = window.open(routeData.href, "_blank");
      }
      // window.open(routeData.href, '_blank')
    },
    handleSave(isPrompt) {
      return new Promise((resolve, reject) => {
        this.loading = true
        var answers = []
        var tableQuestionAnswer = []
        for (const k in this.questionForm) {
          if (this.questionForm[k] instanceof Array) {
            this.questionForm[k].forEach((v, i) => {
              Object.keys(v).forEach(o => {
                if (o.indexOf('_RowId') === -1) {
                  tableQuestionAnswer.push({
                    questionId: k,
                    answer: v[o],
                    tableQuestionId: o,
                    rowId: v[o + '_RowId']
                  })
                }
              })
            })
            // tableQuestionAnswer.push({})
          } else {
            answers.push({ questionId: k, answer: this.questionForm[k].toString() })
          }
        }
        var params = {
          visitTaskId: this.visitTaskId,
          questionAnswer: answers,
          tableQuestionAnswer: tableQuestionAnswer
        }
        changeCalculationAnswer(params).then(res => {
          if (isPrompt) {
            this.$message.success(this.$t('common:message:savedSuccessfully'))
          }
          // DicomEvent.$emit('refreshQuestionAnswer')
          this.loading = false
          resolve()
        }).catch(() => {
          this.loading = false
          reject()
        })
      })
    },
    async skipTask() {
      try {
        // 是否确认跳过？
        const confirm = await this.$confirm(
          this.$t('trials:readingReport:message:skipConfirm'),
          {
            type: 'warning',
            distinguishCancelAndClose: true
          }
        )
        if (confirm !== 'confirm') return
        this.loading = true
        const res = await setSkipReadingCache({ visitTaskId: this.visitTaskId })
        this.loading = false
        if (res.IsSuccess) {
          window.location.reload()
        }
      } catch (e) {
        this.loading = false
        console.log(e)
      }
    },
    // 预览
    preview(path) {
      this.currentPath = path
      const arr = path.split('.')
      this.currentType = arr[arr.length - 1]
      this.previewVisible = true
    }
  }
}
</script>
<style lang="scss" scoped>
.report-wrapper {

  height: 100%;
  // 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 {
    background-color: #000;
    color: #ffffff;
    border: none;
  }

  ::v-deep .el-table--border th.gutter:last-of-type {
    border: none;
  }

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

  ::v-deep .el-table th,
  .el-table tr {
    background-color: #000;
    color: #fff;
    border-color: #444444;
  }

  ::v-deep .el-table__body tr>td {
    background-color: #000 !important;
    color: #fff;
    border-color: #444444;
  }

  ::v-deep .el-table__body tr:hover>td {
    background-color: #858282 !important;
    color: #fff;
    border-color: #444444;
  }

  ::v-deep .el-table--border th.gutter:last-of-type {
    border: none;
  }

  ::v-deep .el-card__header {
    border: none;
    padding: 10px;
  }

  ::v-deep .el-upload-list--picture-card .el-upload-list__item {
    width: 30px;
    height: 30px;
  }

  ::v-deep .el-upload--picture-card {
    width: 30px;
    height: 30px;
    line-height: 40px;
  }

  ::v-deep .el-dialog {
    background: #1e1e1e;
    border: 1px solid #ddd;
    color: #ddd;

    .el-dialog__title {
      color: #fff;
    }

    .el-input .el-input__inner {
      background-color: transparent;
      color: #ddd;
      border: 1px solid #5e5e5e;
    }

    .el-input.is-disabled .el-input__inner {
      background-color: #646464a1;
    }

    .el-form-item__label {
      color: #dfdfdf
    }
  }
}

::v-deep .el-switch__label {
  color: #fff;
}

::v-deep .el-switch__label.is-active {
  color: #428bca;
}

.uploadWrapper {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
</style>
