<template>
  <div v-loading="loading" class="oncologyReview_wrapper">
    <el-card shadow="never" :body-style="{ padding: '10px' }" style="margin-bottom:10px">
      <h4 v-if="isReadingShowSubjectInfo">
        受试者：
        <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" class="clearfix">
        <span style="font-weight: bold;">肿瘤学阅片</span>
      </div>
      <div style="text-align:right;margin:5px 0;">
        <el-button
          type="primary"
          size="small"
          @click="previewCD"
        >
          临床数据
        </el-button>
        <el-button
          v-if="oncologyInfo.ReadingTaskState < 2"
          size="small"
          type="primary"
          @click="handleSave(true)"
        >
          保存
        </el-button>
        <el-button
          v-if="oncologyInfo.ReadingTaskState < 2"
          size="small"
          type="primary"
          @click="handleConfirm"
        >
          确认
        </el-button>
      </div>
      <el-table
        :data="oncologyInfo.OncologyVisits"
        style="width: 100%"
      >
        <el-table-column
          prop="VisitName"
          label="访视名称"
          show-overflow-tooltip
          width="150"
        />

        <el-table-column
          label="影像学阅片结果"
          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">
                {{ scope.row.QuestionList.length>index?scope.row.QuestionList[index].Answer:'' }}
              </template>
            </el-table-column>
            <el-table-column
              v-if="oncologyInfo.IsShowDetail"
              prop="IsHaveChange"
              label="全局是否有更新"
              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)"
                >
                  查看详情
                </el-button>
              </template>
            </el-table-column>
            <el-table-column
              v-if="oncologyInfo.IsShowDetail"
              prop="VisitRemark"
              label="访视点注释"
              show-overflow-tooltip
              width="150"
            />
          </template>
        </el-table-column>

        <el-table-column
          label="肿瘤学阅片结果"
          align="center"
          prop=""
        >
          <template>
            <el-table-column
              prop="EvaluationResult"
              label="结论"
              show-overflow-tooltip
              width="150"
            >
              <template slot-scope="scope">
                <el-select
                  v-if="oncologyInfo.ReadingTaskState < 2"
                  v-model="scope.row.EvaluationResult"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in trialEvaluations"
                    :key="item"
                    :label="item"
                    :value="item"
                  />
                </el-select>
                <span v-else>{{ 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>原因</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="查看详情"
              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;">既往肿瘤学阅片结果</span>
      </div>

      <el-table
        v-loading="priorLoading"
        :data="priorList"
        style="width: 100%"
      >
        <el-table-column
          prop="TaskBlindName"
          label="肿瘤学阅片"
          show-overflow-tooltip
          width="200"
        />
        <el-table-column
          :label="$t('common:action:action')"
          width="200"
        >
          <template slot-scope="scope">
            <el-button
              circle
              title="查看详情"
              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 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
    }
  },
  data() {
    return {
      currentUser: zzSessionStorage.getItem('userName'),
      signVisible: false,
      signCode: null,
      loading: false,
      priorLoading: false,
      priorList: [],
      questionCols: [],
      oncologyInfo: {},
      trialEvaluations: []
    }
  },
  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.trialEvaluations = res.Result.TrialEvaluationResult ? res.Result.TrialEvaluationResult.split('|') : []
        this.oncologyInfo = res.Result
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    handleSave(isPrompt) {
      this.loading = true
      var index = this.oncologyInfo.OncologyVisits.findIndex(item => !item.EvaluationResult)
      if (index > -1) {
        this.loading = false
        this.$confirm('肿瘤学阅片结论不能为空！', {
          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.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`
      })
      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>
