<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-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="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 }}</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 v-if="task.LatestScanDate">-->
                <!--                  {{ task.LatestScanDate.split(' ')[0] }}-->
                <!--                </div>-->
                <!-- {{ `（影像点击跳转）` }} -->
                <!--                {{ $t('trials:readingReport:button:jump') }}-->
              </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')">
                <template>
                  <!-- 输入框 -->
                  <div>
                    <template v-if="!((task.IsBaseLine && scope.row.LimitEdit === 1) || (!task.IsBaseLine && scope.row.LimitEdit === 2) || scope.row.LimitEdit === 0)" />
                    <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.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
                    >
                      <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>
              <template v-else-if="task.VisitTaskId === visitTaskId && scope.row.Type === 'upload'">
                <UploadFile
                  v-if="scope.row.Type==='upload' && (scope.row.xfIndex || scope.row.xfIndex === 0)"
                  :visit-task-id="visitTaskId"
                  :question="scope.row"
                  :task="task"
                  :reading-task-state="readingTaskState"
                  :init-url="questionForm[scope.row.QuestionId][scope.row.xfIndex][scope.row.TableQuestionId]"
                  @setImageUrl="(url) => {setImageUrl(scope.row.QuestionId, scope.row.xfIndex, scope.row.TableQuestionId, url, scope.row.RowId)}"
                />
                <UploadFile
                  v-else-if="scope.row.Type==='upload'"
                  :visit-task-id="visitTaskId"
                  :question="scope.row"
                  :task="task"
                  :reading-task-state="readingTaskState"
                  :init-url="questionForm[scope.row.QuestionId]"
                  @setImageUrl="(url) => {setImageUrl(scope.row.QuestionId, scope.row.xfIndex, scope.row.TableQuestionId, url)}"
                />
              </template>
              <template v-else-if="scope.row.Type === 'upload'">
                <UploadFile
                  v-if="scope.row.Type==='upload' && (scope.row.xfIndex || scope.row.xfIndex === 0)"
                  :visit-task-id="visitTaskId"
                  :question="scope.row"
                  :task="task"
                  :reading-task-state="readingTaskState"
                  :init-url="scope.row.Answers[task.VisitTaskId]"
                />
                <UploadFile
                  v-else-if="scope.row.Type==='upload'"
                  :visit-task-id="visitTaskId"
                  :question="scope.row"
                  :task="task"
                  :reading-task-state="readingTaskState"
                  :init-url="scope.row.Answers[task.VisitTaskId]"
                />
              </template>
              <template v-else-if="scope.row.QuestionType=== 22">
                {{ scope.row.Answers[task.VisitTaskId] === '-1' ? '未知' : 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="!((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>
  </div>
</template>
<script>
import { changeCalculationAnswer, getReadingReportEvaluation, submitDicomVisitTask, verifyVisitTaskQuestions, getQuestionCalculateRelation } from '@/api/trials'
import { setSkipReadingCache } from '@/api/reading'
import DicomEvent from '@/views/trials/trials-panel/reading/dicoms/components/DicomEvent'
import UploadFile from './UploadFile'
import const_ from '@/const/sign-code'
import SignForm from '@/views/trials/components/newSignForm'
import { getToken } from '@/utils/auth'
import store from '@/store'
export default {
  name: 'Report',
  components: { SignForm, UploadFile },
  props: {
    trialId: {
      type: String,
      required: true
    },
    visitTaskId: {
      type: String,
      required: true
    },
    subjectId: {
      type: String,
      required: true
    },
    readingTool: {
      type: String,
      required: true
    },
    criterionType: {
      type: String,
      required: true
    },
    isReadingTaskViewInOrder: {
      type: Number,
      required: true
    }
  },
  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,
      CalculationList: [],
      TrialReadingCriterionId: null,
      tableAnswers: {},
      questionForm: {},
      questionId: 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)
      }
    },
    taskQuestions() {
      this.$nextTick(() => {
        this.setScrollTop()
      })
    }
  },
  async mounted() {
    this.CriterionType = parseInt(localStorage.getItem('CriterionType'))
    this.digitPlaces = parseInt(localStorage.getItem('digitPlaces'))
    this.TrialReadingCriterionId = this.$route.query.TrialReadingCriterionId
    window.addEventListener('resize', () => {
      this.handleResize()
      this.setScrollTop()
    })
    DicomEvent.$on('getReportInfo', isRefresh => {
      if (!isRefresh) return
      this.getReportInfo()
    })
    await this.getQuestionCalculateRelation()
    this.getReportInfo()
  },
  beforeDestroy() {
    DicomEvent.$off('getReportInfo')
  },
  methods: {
    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') return
        if (!v.IsPage && v.Type !== 'group' && v.Type !== 'summary' && v.Type !== 'table' && v.Type !== 'number') {
          this.$set(this.questionForm, v.QuestionId, v.Answers[this.visitTaskId])
        }
        if (v.Type === 'table') {
          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 = parseInt(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') {
          this.$set(this.questionForm, i.QuestionId, i.Answers[this.visitTaskId])
        }
        if (i.Type === 'table') {
          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 = parseInt(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') {
          this.setChild(i.Childrens)
        }
      })
    },
    getQuestionCalculateRelation() {
      return new Promise(resolve => {
        getQuestionCalculateRelation({
          TrialReadingCriterionId: this.TrialReadingCriterionId
        }).then(res => {
          this.CalculationList = res.Result
          resolve()
        })
      })
    },
    logic(rules, num = 0) {
      try {
        if (rules.CalculateQuestionList.length === 0) {
          return false
        }
        rules.CalculateQuestionList.forEach((o, i) => {
          if (i === 0) {
            if (rules.CustomCalculateMark > 4) {
              switch (rules.CustomCalculateMark) {
                case 5:
                  this.questionForm[o.QuestionId].forEach((q, qi) => {
                    if (qi === 0) {
                      num = parseFloat(q[o.TableQuestionId])
                    } else {
                      num *= parseFloat(q[o.TableQuestionId])
                    }
                  })
                  break
                case 6:
                  this.questionForm[o.QuestionId].forEach((q, qi) => {
                    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])
                    }
                  })
                  break
                case 7:
                  this.questionForm[o.QuestionId].forEach((q, qi) => {
                    if (qi === 0) {
                      num = parseFloat(q[o.TableQuestionId])
                    } else {
                      num += parseFloat(q[o.TableQuestionId])
                    }
                  })
                  num = this.questionForm[o.QuestionId].length === 0 ? 0 : num / this.questionForm[o.QuestionId].length
                  break
                case 8:
                  var arr = []
                  this.questionForm[o.QuestionId].forEach(q => {
                    arr.push(q[o.TableQuestionId])
                  })
                  num = arr.length === 0 ? 0 : Math.max(...arr)
                  break
                case 9:
                  // eslint-disable-next-line no-redeclare
                  var arr = []
                  this.questionForm[o.QuestionId].forEach(q => {
                    arr.push(q[o.TableQuestionId])
                  })
                  num = arr.length === 0 ? 0 : Math.min(...arr)
                  break
              }
            } else {
              num = parseFloat(this.questionForm[o.TableQuestionId])
            }
          } else {
            switch (rules.CustomCalculateMark) {
              case 1:
                num += parseFloat(this.questionForm[o.TableQuestionId])
                break
              case 2:
                num -= parseFloat(this.questionForm[o.TableQuestionId])
                break
              case 3:
                num *= parseFloat(this.questionForm[o.TableQuestionId])
                break
              case 4:
                num /= parseFloat(this.questionForm[o.TableQuestionId])
                // num /= parseFloat(this.questionForm[o.TableQuestionId])
                break
            }
          }
        })
      } catch (e) {
        console.log(e)
      }
      var digitPlaces = parseInt(localStorage.getItem('digitPlaces'))
      if (rules.ValueType === 2) {
        num = num * 100
      }
      return isNaN(num) ? '' : isFinite(num) ? num.toFixed(digitPlaces) : '∞'
    },
    getReportInfo() {
      this.loading = true
      var params = {
        visitTaskId: this.visitTaskId,
        trialId: this.$router.currentRoute.query.trialId
      }
      this.taskQuestions = []
      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()
        var taskQuestions = this.getQuestions(res.Result.TaskQuestions, !this.isShowDetail, null, null)
        taskQuestions.forEach(item => {
          this.$set(this.taskQuestions, this.taskQuestions.length, item)
        })
        this.visitTaskList = res.Result.VisitTaskList
        this.InitVisitTaskQuestionForm()
        this.handleResize()
        this.setScrollTop()
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    setScrollTop(a) {
      setTimeout(() => {
        this.$nextTick(() => {
          if (this.$refs.reportList) {
            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 = []
          if ((item.LesionType === 1 || item.LesionType === 2) && isNTFilterLength) {
            filterArr = [0, 1, 3, 4, 5, 6, 2, 8, 10]
          } else {
            filterArr = [3, 4, 5, 6, 2, 8, 10]
          }
          if (lesionType === 0 && isLymphNodes === 0 && !this.isShowDetail && this.CriterionType === 1) {
            filterArr.push(1)
          }
          if (!(filterArr.includes(item.QuestionMark))) {
            const obj = item
            this.$set(obj, 'Answers', {})
            // obj.Answers = {}
            if (item.RowIndex > 0) {
              var idx = item.Childrens.findIndex(i => i.QuestionMark === 8)
              var idxLoc = item.Childrens.findIndex(i => i.QuestionMark === 10)

              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} `
                  } else if (!item.SplitOrMergeLesionName && k > -1) {
                    obj.QuestionName = `${obj.QuestionName} --${part}`
                    // obj.QuestionName = `${obj.QuestionName} `
                  } else {
                    obj.QuestionName = `${obj.QuestionName} `
                  }

                  if (this.CriterionType === 1) {
                    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
                    }
                  }
                }
              }
            }
            var digitPlaces = parseInt(localStorage.getItem('digitPlaces')) || 0
            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 = parseInt(i.Answer)
                  } else if (item.ValueType === 3) {
                    val = i.Answer
                  } else {
                    val = isNaN(parseFloat(i.Answer)) ? i.Answer : parseFloat(i.Answer).toFixed(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, 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('')
      }
      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('')
      }
      var idx = this.answerArr.findIndex(i => i.questionType === 13)
      if (idx > -1) {
        this.answerArr[idx].answer = val
      }
    },

    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()
      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
      }
    },
    // 签名并确认
    signConfirm(signInfo) {
      this.loading = true
      var params = {
        data: {
          visitTaskId: this.visitTaskId
        },
        signInfo: signInfo
      }
      submitDicomVisitTask(params).then(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
          store.dispatch('reading/setVisitTaskReadingTaskState', { visitTaskId: this.visitTaskId, readingTaskState: 2 })
          DicomEvent.$emit('setReadingState', 2)
          window.opener.postMessage('refreshTaskList', window.location)
          this.$confirm(this.$t('trials:oncologyReview:title:msg2'), {
            type: 'warning',
            distinguishCancelAndClose: true
          })
            .then(() => {
              // var token = getToken()
              // var subjectCode = this.$router.currentRoute.query.subjectCode
              // var subjectId = this.$router.currentRoute.query.subjectId
              // var trialId = this.$router.currentRoute.query.trialId

              // this.$router.push({
              //   path: `/readingPage?subjectCode=${subjectCode}&subjectId=${subjectId}&trialId=${trialId}&TokenKey=${token}`
              // })
              // DicomEvent.$emit('getNextTask')
              window.location.reload()
            })
            .catch(action => {

            })
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
        if (this.$refs['signForm'] && this.$refs['signForm'].btnLoading) {
          this.$refs['signForm'].btnLoading = false
        }
      })
    },
    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 })
      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)
      }
    }
  }
}
</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-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-switch__label.is-active{
  color: #428bca;
}
.uploadWrapper{
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}
</style>
