<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
          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"
              :label="$t('trials:oncologyReview:title:findings')"
              show-overflow-tooltip
              width="150"
            >
              <template slot-scope="scope">
                <el-select
                  v-if="oncologyInfo.ReadingTaskState < 2"
                  v-model="scope.row.EvaluationResult"
                  :placeholder="$t('common:ruleMessage:select')"
                >
                  <el-option
                    v-for="item in assessTypeList"
                    :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 :maxLength="$inputMax"
                  v-if="oncologyInfo.ReadingTaskState < 2"
                  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
          :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 const_ from '@/const/sign-code'
import { getToken } from '@/utils/auth'
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: []

    }
  },
  mounted() {
    this.getList()
    if (this.isReadingShowPreviousResults) {
      this.getPriorList()
    }
  },
  methods: {
    getList() {
      this.loading = true
      getOncologyReadingInfo({ visitTaskId: this.visitTaskId }).then(res => {
        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(() => { 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) {
      this.loading = true
      var index = this.oncologyInfo.OncologyVisits.findIndex(item => !item.EvaluationResult)
      if (index > -1) {
        this.loading = false
        // '肿瘤学阅片结论不能为空！'
        this.$confirm(this.$t('trials:oncologyReview:message:msg1'), {
          type: 'warning',
          distinguishCancelAndClose: true
        })
          .then(() => {
            return Promise.reject(false)
          })
          .catch(action => {
            return Promise.reject(false)
          })
      } else {
        this.loading = true
        var oncologyQuestionList = []
        this.oncologyInfo.OncologyVisits.map(item => {
          if (item.EvaluationResult) {
            oncologyQuestionList.push(
              {
                visitTaskId: item.VisitTaskId,
                evaluationResult: item.EvaluationResult,
                evaluationReason: item.EvaluationReason
              }
            )
          }
        })
        var params = {
          oncologyTaskId: this.visitTaskId,
          oncologyQuestionList: oncologyQuestionList
        }
        return new Promise((resolve, reject) => {
          setOncologyReadingInfo(params).then(res => {
            this.loading = false
            this.getList()
            if (isPrompt) {
              this.$message.success(this.$t('common:message:savedSuccessfully'))
            }
            resolve(true)
          }).catch(_ => {
            this.loading = false
            reject(false)
          })
        })
      }
    },
    handleSubmit() {
      this.$refs['adForm'].validate((valid) => {
        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
      }
    },
    handleConfirm() {
      this.handleSave(false).then(res => {
        if (res) {
          const { ImageAssessmentReportConfirmation } = const_.processSignature
          this.signCode = ImageAssessmentReportConfirmation
          this.signVisible = true
        }
      })
    },
    // 签名并确认
    signConfirm(signInfo) {
      this.loading = true
      var params = {
        data: {
          oncologyTaskId: this.visitTaskId
        },
        signInfo: signInfo
      }
      submitOncologyReadingInfo(params).then(res => {
        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
          window.opener.postMessage('refreshTaskList', window.location)
          // '当前阅片任务已完成，是否进入下一个阅片任务？'
          this.$confirm(this.$t('trials:oncologyReview:title:msg2'), {
            type: 'warning',
            distinguishCancelAndClose: true
          })
            .then(() => {
              // var token = getToken()
              // var criterionType = this.$router.currentRoute.query.criterionType
              // var readingTool = this.$router.currentRoute.query.readingTool
              // var isReadingTaskViewInOrder = this.$router.currentRoute.query.isReadingTaskViewInOrder
              // var trialReadingCriterionId = this.$router.currentRoute.query.TrialReadingCriterionId
              // var path = ''
              // if (readingTool && parseInt(readingTool) === 0) {
              //   path = `/readingDicoms?TrialReadingCriterionId=${trialReadingCriterionId}&trialId=${this.trialId}&subjectCode=${this.subjectCode}&subjectId=${this.subjectId}&isReadingTaskViewInOrder=${isReadingTaskViewInOrder}&criterionType=${criterionType}&readingTool=${readingTool}&TokenKey=${token}&key=${new Date().getTime()}`
              // } else {
              //   path = `/noneDicomReading?TrialReadingCriterionId=${trialReadingCriterionId}&trialId=${this.trialId}&subjectCode=${this.subjectCode}&subjectId=${this.subjectId}&isReadingTaskViewInOrder=${isReadingTaskViewInOrder}&criterionType=${criterionType}&readingTool=${readingTool}&TokenKey=${token}&key=${new Date().getTime()}`
              // }
              // this.$router.push({ path })
              DicomEvent.$emit('getNextTask')
            })
            .catch(action => {

            })
        }
        this.loading = false
      }).catch(_ => {
        this.loading = false
        this.$refs['signForm'].btnLoading = false
      })
    },
    getPriorList() {
      this.priorLoading = true
      getReadingPastResultList({ visitTaskId: this.visitTaskId }).then(res => {
        this.priorList = res.Result
        this.priorLoading = false
      }).catch(() => { this.priorLoading = false })
    },
    handleViewDetail(visitTaskId) {
      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) {
        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 })
      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')
    }
  }
}
</script>
<style lang="scss" scoped>
.oncologyReview_wrapper{
  flex: 1;
  padding: 10px;
  width: 100%;
  height: 100%;
  overflow-y: auto;
  .box-mr{
    margin:10px 0;
  }
}
</style>
