<template>
  <div v-loading="loading" class="oncologyReview_wrapper">
    <el-card v-if="isReadingShowSubjectInfo" shadow="never" :body-style="{ padding: '10px' }"
      style="margin-bottom:10px">
      <h4>
        <!-- 受试者： -->
        {{ $t('trials:oncologyReview:title:subject') }}
        <span style="font-weight:normal">{{ subjectCode }} </span>
        <span style="font-weight:normal">({{ taskBlindName }})</span>
      </h4>
    </el-card>
    <el-card :body-style="{ padding: '10px' }">
      <div slot="header" style="display: flex;flex-direction: row;justify-content: space-between;">
        <!-- 肿瘤学阅片 -->
        <div style="font-weight: bold;">{{ $t('trials:oncologyReview:title:oncologyReview') }}</div>
        <!-- <div v-if="isExistsClinicalData">
          <el-button type="text" @click="previewCD">临床数据</el-button>
        </div> -->
      </div>
      <div style="text-align:right;margin:5px 0;">
        <!-- 临床数据 -->
        <el-button v-if="isExistsClinicalData" type="primary" size="small" @click="previewCD">
          {{ $t('trials:oncologyReview:button:clinicalData') }}
        </el-button>
        <el-button type="primary" size="small" @click="skipTask" v-if="!isView && oncologyInfo.ReadingTaskState < 2">
          <!-- 跳过 -->
          {{ $t('trials:readingReport:button:skip') }}
        </el-button>
        <!-- 保存 -->
        <el-button v-if="oncologyInfo.ReadingTaskState < 2" size="small" type="primary" @click="handleSave(true)">
          {{ $t('common:button:save') }}
        </el-button>
        <!-- 提交 -->
        <el-button v-if="oncologyInfo.ReadingTaskState < 2" size="small" type="primary" @click="handleConfirm">
          {{ $t('common:button:submit') }}
        </el-button>
      </div>
      <el-table :data="oncologyInfo.OncologyVisits" style="width: 100%">
        <!-- 访视名称 -->
        <el-table-column prop="VisitName" :label="$t('trials:oncologyReview:title:visitName')" show-overflow-tooltip
          width="150" />
        <!-- 影像学阅片结果 -->
        <el-table-column :label="$t('trials:oncologyReview:title:readingRes')" align="center" prop="">
          <template>
            <el-table-column v-for="(qs, index) in questionCols" :key="qs" prop="" :label="qs" show-overflow-tooltip
              width="150">
              <template slot-scope="scope">
                <span v-if="scope.row.QuestionList[index].DictionaryCode">
                  {{ $fd(scope.row.QuestionList[index].DictionaryCode, parseInt(scope.row.QuestionList[index].Answer)) }}
                </span>
                <span v-else>
                  {{ scope.row.QuestionList.length > index ? scope.row.QuestionList[index].Answer : '' }}
                </span>

              </template>
            </el-table-column>
            <!-- 全局是否有更新 -->
            <el-table-column v-if="oncologyInfo.IsShowDetail" prop="IsHaveChange"
              :label="$t('trials:oncologyReview:title:isGlobalUpdate')" show-overflow-tooltip width="150">
              <template slot-scope="scope">
                <span>{{ $fd('YesOrNo', scope.row.IsHaveChange) }}</span>
                <!-- 查看详情 -->
                <el-button v-if="scope.row.IsHaveChange && oncologyInfo.GlobalTaskId" type="text"
                  style="margin-left:5px;" @click="handleViewDetail(oncologyInfo.GlobalTaskId)">
                  {{ $t('trials:oncologyReview:title:view') }}
                </el-button>
              </template>
            </el-table-column>
            <!-- 访视点注释 -->
            <el-table-column v-if="oncologyInfo.IsShowDetail" prop="VisitRemark"
              :label="$t('trials:oncologyReview:title:visitRemark')" show-overflow-tooltip width="150" />
          </template>
        </el-table-column>
        <!-- 肿瘤学阅片结果 -->
        <el-table-column :label="$t('trials:oncologyReview:title:oReviewRes')" align="center" prop="">
          <template>
            <!-- 结论 -->
            <el-table-column prop="EvaluationResult" show-overflow-tooltip width="150">
              <template slot="header">
                <div>
                  <span>{{ $t('trials:oncologyReview:title:findings') }}</span>
                  <span style="color:red">*</span>
                </div>
              </template>
              <template slot-scope="scope">
                <el-select v-if="oncologyInfo.ReadingTaskState < 2 && !scope.row.IsBaseLine"
                  v-model="scope.row.EvaluationResult" :placeholder="$t('common:ruleMessage:select')">
                  <el-option v-for="item in assessTypeList" v-show="item.Code !== '-1'" :key="item.Id"
                    :label="item.Value" :value="item.Code" />
                </el-select>
                <span v-else>{{ getAssessType(scope.row.EvaluationResult) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="EvaluationReason" show-overflow-tooltip width="250">
              <template slot="header">
                <el-tooltip placement="top">

                  <div slot="content">
                    {{ oncologyInfo.TrialEvaluationReason }}
                  </div>
                  <div>
                    <!-- 原因 -->
                    <span>{{ $t('trials:oncologyReview:title:reason') }}</span>
                    <span style="color:red">!</span>
                  </div>

                </el-tooltip>
              </template>
              <template slot-scope="scope">
                <el-input v-if="oncologyInfo.ReadingTaskState < 2 && !scope.row.IsBaseLine"
                  v-model="scope.row.EvaluationReason" />
                <span v-else>{{ scope.row.EvaluationReason }}</span>
              </template>
            </el-table-column>
          </template>
        </el-table-column>

        <el-table-column v-if="oncologyInfo.IsShowDetail" :label="$t('common:action:action')" width="100">
          <template slot-scope="scope">
            <!-- 查看详情 -->
            <el-button circle :title="$t('trials:oncologyReview:title:view')" icon="el-icon-view"
              @click="handleViewDetail(scope.row.VisitTaskId)" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-card v-if="isReadingShowPreviousResults" :body-style="{ padding: '10px' }" class="box-mr">
      <div slot="header" class="clearfix">
        <!-- 既往肿瘤学阅片结果 -->
        <span style="font-weight: bold;">{{ $t('trials:oncologyReview:title:previousRes') }}</span>
      </div>

      <el-table v-loading="priorLoading" :data="priorList" style="width: 100%">
        <!-- 肿瘤学阅片 -->
        <el-table-column prop="TaskBlindName" :label="$t('trials:oncologyReview:title:oncologyReview')"
          show-overflow-tooltip width="200" />
        <el-table-column prop="VisitName" :label="$t('trials:globalReview:table:cutOffVisitName')" show-overflow-tooltip
          width="200" />
        <el-table-column :label="$t('common:action:action')" width="200">
          <template slot-scope="scope">
            <!-- 查看详情 -->
            <el-button circle :title="$t('trials:oncologyReview:title:view')" icon="el-icon-view"
              @click="handleViewDetail(scope.row.VisitTaskId)" />
          </template>
        </el-table-column>
      </el-table>
    </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 { getOncologyReadingInfo, getReadingPastResultList, setOncologyReadingInfo, submitOncologyReadingInfo } from '@/api/trials'
import { setSkipReadingCache } from '@/api/reading'
import { getAutoCutNextTask } from '@/api/user'
import const_ from '@/const/sign-code'
import { getToken } from '@/utils/auth'
// import store from '@/store'
import { changeURLStatic } from '@/utils/history.js'
import DicomEvent from '@/views/trials/trials-panel/reading/dicoms/components/DicomEvent'
import SignForm from '@/views/trials/components/newSignForm'
export default {
  name: 'OncologyReview',
  components: { SignForm },
  props: {
    trialId: {
      type: String,
      required: true
    },
    subjectId: {
      type: String,
      required: true
    },
    visitTaskId: {
      type: String,
      required: true
    },
    readingCategory: {
      type: Number,
      required: true
    },
    subjectCode: {
      type: String,
      required: true
    },
    taskBlindName: {
      type: String,
      required: true
    },
    isReadingShowSubjectInfo: {
      type: Boolean,
      required: true
    },
    isReadingShowPreviousResults: {
      type: Boolean,
      required: true
    },
    isExistsClinicalData: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      currentUser: zzSessionStorage.getItem('userName'),
      signVisible: false,
      signCode: null,
      loading: false,
      priorLoading: false,
      priorList: [],
      questionCols: [],
      oncologyInfo: {},
      assessTypeList: [],
      openWindow: null
    }
  },
  // watch: {
  //   visitTaskId: {
  //     immediate: true,
  //     handler(val) {
  //       this.$nextTick(() => {
  //         this.getList()
  //         if (this.isReadingShowPreviousResults) {
  //           this.getPriorList()
  //         }
  //       })
  //     }
  //   }
  // },
  computed: {
    isView() {
      return !this.hasPermi(['role:ir'])
    }
  },
  mounted() {
    this.getList()
    if (this.isReadingShowPreviousResults) {
      this.getPriorList()
    }
    DicomEvent.$on('resetOpenWindow', () => {
      if (this.openWindow) {
        this.openWindow.close()
      }
    })
  },
  beforeDestroy() {
    DicomEvent.$off('resetOpenWindow')
    if (this.openWindow) {
      this.openWindow.close()
    }
  },
  methods: {
    async getList() {
      this.loading = true
      try {
        const res = await getOncologyReadingInfo({ visitTaskId: this.visitTaskId })
        var questions = []
        if (res.Result.OncologyVisits.length > 0) {
          var task = res.Result.OncologyVisits[0]
          task.QuestionList.map(qs => {
            questions.push(qs.QuestionName)
          })
        }
        this.questionCols = questions
        this.assessTypeList = res.Result.AssessTypeList
        this.oncologyInfo = res.Result
        this.loading = false
      } catch (e) {
        this.loading = false
      }
    },
    getAssessType(val) {
      var idx = this.assessTypeList.findIndex(i => i.Code === val)
      if (idx > -1) {
        return this.assessTypeList[idx].Value
      } else {
        return ''
      }
    },
    handleSave(isPrompt) {
      return new Promise(async (resolve, reject) => {
        this.loading = true
        // var index = this.oncologyInfo.OncologyVisits.findIndex(item => !item.EvaluationResult && !item.IsBaseLine)
        var isDiffer = this.checkDifferResult()
        if (isDiffer) {
          this.loading = false
          const confirm = await this.$confirm(
            this.$t('trials:oncologyReview:message:msg2'),
            {
              type: 'warning',
              distinguishCancelAndClose: true
            }
          )
          if (confirm === 'confirm') reject(false)
        } else {
          this.loading = true
          var oncologyQuestionList = []
          this.oncologyInfo.OncologyVisits.map(item => {
            if (item.EvaluationResult && !item.IsBaseLine) {
              oncologyQuestionList.push(
                {
                  visitTaskId: item.VisitTaskId,
                  evaluationResult: item.EvaluationResult,
                  evaluationReason: item.EvaluationReason
                }
              )
            }
          })
          var params = {
            oncologyTaskId: this.visitTaskId,
            oncologyQuestionList: oncologyQuestionList,
            globalTaskId: this.oncologyInfo.GlobalTaskId,
            relatedTaskId: this.oncologyInfo.RelatedTaskId
          }
          try {
            await setOncologyReadingInfo(params)
            this.loading = false
            this.getList()
            if (isPrompt) {
              this.$message.success(this.$t('common:message:savedSuccessfully'))
            }
            resolve(true)
          } catch (e) {
            this.loading = false
            reject(false)
          }
        }
      })
    },
    checkDifferResult() {
      var isDiffer = false
      var criterionType = parseInt(this.$route.query.criterionType)
      if (criterionType === 2) {
        for (let i = 0; i < this.oncologyInfo.OncologyVisits.length; i++) {
          if (this.oncologyInfo.OncologyVisits[i].IsBaseLine) continue
          var tumorAssessment = ''
          var idx = this.oncologyInfo.OncologyVisits[i].QuestionList.findIndex(v => v.DictionaryCode === 'ImagingOverallAssessment_Lugano')
          if (idx > -1) {
            tumorAssessment = this.oncologyInfo.OncologyVisits[i].QuestionList[idx].Answer
            if (!(this.oncologyInfo.OncologyVisits[i].EvaluationResult !== '' && (tumorAssessment === this.oncologyInfo.OncologyVisits[i].EvaluationResult || (tumorAssessment !== this.oncologyInfo.OncologyVisits[i].EvaluationResult && this.oncologyInfo.OncologyVisits[i].EvaluationReason)))) {
              isDiffer = true
              break
            }
          }
        }
      }
      return isDiffer
    },
    async handleSubmit() {
      const valid = await this.$refs['adForm'].validate()
      if (!valid) return
      const { ImageAssessmentReportConfirmation } = const_.processSignature
      this.signCode = ImageAssessmentReportConfirmation
      this.signVisible = true
    },
    // 关闭签名框
    closeSignDialog(isSign, signInfo) {
      if (isSign) {
        this.signConfirm(signInfo)
      } else {
        this.signVisible = false
      }
    },
    async handleConfirm() {
      const res = await this.handleSave(false)
      if (res) {
        const { ImageAssessmentReportConfirmation } = const_.processSignature
        this.signCode = ImageAssessmentReportConfirmation
        this.signVisible = true
      }
    },
    // 签名并确认
    async signConfirm(signInfo) {
      this.loading = true
      var params = {
        data: {
          oncologyTaskId: this.visitTaskId
        },
        signInfo: signInfo
      }
      try {
        const res = await submitOncologyReadingInfo(params)
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          this.isEdit = false
          this.$refs['signForm'].btnLoading = false
          this.signVisible = false
          // window.location.reload()
          // window.opener.postMessage('refreshTaskList', window.location)
          // 设置当前任务阅片状态为已读
          this.oncologyInfo.ReadingTaskState = 2

          const res = await getAutoCutNextTask()
          var isAutoTask = res.Result.AutoCutNextTask
          if (isAutoTask) {
            // store.dispatch('reading/resetVisitTasks')
            // DicomEvent.$emit('getNextTask')
            window.location.reload()
          } else {
            // '当前阅片任务已完成，是否进入下一个阅片任务？'
            const confirm = await this.$confirm(
              this.$t('trials:oncologyReview:title:msg2'),
              {
                type: 'warning',
                distinguishCancelAndClose: true
              }
            )
            if (confirm === 'confirm') {
              // store.dispatch('reading/resetVisitTasks')
              // DicomEvent.$emit('getNextTask')
              window.location.reload()
            } else {
              changeURLStatic('visitTaskId', this.visitTaskId)
            }
          }
          window.opener.postMessage('refreshTaskList', window.location)
        }
        this.loading = false
      } catch (e) {
        this.loading = false
        this.$refs['signForm'].btnLoading = false
      }
    },
    async getPriorList() {
      this.priorLoading = true
      try {
        const res = await getReadingPastResultList({ visitTaskId: this.visitTaskId })
        this.priorList = res.Result
        this.priorLoading = false
      } catch (e) {
        this.priorLoading = false
      }
    },
    handleViewDetail(visitTaskId) {
      if (this.openWindow) {
        this.openWindow.close()
      }
      var token = getToken()
      // const routeData = this.$router.resolve({
      //   path: `/readingPage?trialId=${this.trialId}&visitTaskId=${visitTaskId}&TokenKey=${token}&isReadingShowPreviousResults=false`
      // })
      var criterionType = this.$router.currentRoute.query.criterionType
      var readingTool = this.$router.currentRoute.query.readingTool
      readingTool = isNaN(parseInt(readingTool)) ? null : parseInt(readingTool)
      var isReadingTaskViewInOrder = this.$router.currentRoute.query.isReadingTaskViewInOrder
      var trialReadingCriterionId = this.$router.currentRoute.query.TrialReadingCriterionId
      var path = ''
      if (readingTool === 0 || readingTool === 2 || readingTool === 3) {
        path = `/readingDicoms?TrialReadingCriterionId=${trialReadingCriterionId}&trialId=${this.trialId}&subjectCode=${this.subjectCode}&subjectId=${this.subjectId}&visitTaskId=${visitTaskId}&isReadingTaskViewInOrder=${isReadingTaskViewInOrder}&criterionType=${criterionType}&readingTool=${readingTool}&TokenKey=${token}`
      } else {
        path = `/noneDicomReading?TrialReadingCriterionId=${trialReadingCriterionId}&trialId=${this.trialId}&subjectCode=${this.subjectCode}&subjectId=${this.subjectId}&visitTaskId=${visitTaskId}&isReadingTaskViewInOrder=${isReadingTaskViewInOrder}&criterionType=${criterionType}&readingTool=${readingTool}&TokenKey=${token}`
      }
      const routeData = this.$router.resolve({ path })
      this.openWindow = window.open(routeData.href, '_blank')
    },
    previewCD() {
      var token = getToken()
      const routeData = this.$router.resolve({
        path: `/clinicalData?subjectId=${this.oncologyInfo.SubjectId}&trialId=${this.trialId}&visitTaskId=${this.oncologyInfo.OncologyTaskId}&TokenKey=${token}`
      })
      window.open(routeData.href, '_blank')
    },
    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>
.oncologyReview_wrapper {
  flex: 1;
  padding: 10px;
  width: 100%;
  height: 100%;
  overflow-y: auto;

  .box-mr {
    margin: 10px 0;
  }
}
</style>
