<template>
  <div v-loading="loading" style="display: flex;flex-direction: column;height: 100%">
    <div class="preview-wrapper" style="flex:1">
      <div class="left-wrapper">
        <div class="basic-info">
          <span v-if="otherInfo.SubjectCode">{{ `${otherInfo.SubjectCode}` }}</span>
          <span v-if="otherInfo.ReadingNameOrTaskBlindName">({{ `${otherInfo.ReadingNameOrTaskBlindName}` }})</span>
        </div>
        <div v-if="cdList.length>0" class="basic-content">
          <div v-for="item in cdList" :key="item.Id" class="cd-wrapper">
            <div class="cd-name-wrapper">{{ item.ClinicalDataSetName }}</div>
            <template v-if="item.ClinicalUploadType * 1 === 1">
              <div
                v-for="file in item.FileList"
                :key="file.Id"
                class="cd-item"
                :class="{activeBtn:file.Id === selected.id}"
                @click.prevent="preview(file,1)"
              >
                {{ file.FileName }}
              </div>
            </template>
            <template v-else-if="item.ClinicalUploadType * 1 === 2">
              <div
                v-for="(from, index) in item.ClinicalFromList"
                :key="from.Id"
                class="cd-item"
                :class="{activeBtn:from.ClinicalFormId === selected.id}"
                @click.prevent="preview(from,2, item)"
              >
                {{ from.CheckDate ? from.CheckDate.split(' ')[0] : item.ClinicalDataSetName + (index + 1) }}
              </div>
            </template>
            <div v-else class="cd-item" :class="{activeBtn:item.Id === selected.id}" @click.prevent="preview(item,0)">
              <!-- 表格 -->
              {{ $t('trials:uploadClinicalData:title:table') }}
            </div>
          </div>
        </div>
        <div v-else class="basic-content-empty">
          <span>{{ $t('trials:clinicaldara:title:nodata') }}</span>
        </div>
      </div>
      <div class="right-wrapper">
        <div v-if="selected.type===1" class="right-content">
          <iframe :src="`/static/pdfjs/web/viewer.html?file=${OSSclientConfig.basePath}${selected.filePath}`" width="100%" height="100%" frameborder="0" />
        </div>
        <div v-else-if="selected.type===2" class="right-content" style="padding: 10px">
          <clinicalDataQuestions
            v-if="isShow"
            :data="selected"
            :trial-clinical-id="selected.ClinicalDataTrialSetId"
            :is-viewer="false"
            :visit-id="selected.VisitId"
            :subject-id="selected.SubjectId"
            :trial-id="selected.TrialId"
            :reading-id="selected.ReadingId"
            :clinical-form-id="selected.ClinicalFormId"
            :open-type="'look'"
            @close="false"
          />
        </div>
        <div
          v-else-if="selected.type===0"
          style="padding:10px;overflow-y: auto;"
          class="right-content"
        >
          <!-- 既往放疗史 -->
          <h4>{{ $t('trials:uploadClinicalData:title:pastTreatment') }}</h4>
          <el-table
            :data="selected.clinicalTableData.PreviousHistoryList"
            style="width: 100%"
          >
            <el-table-column
              type="index"
              width="50"
            />
            <!-- 放疗部位 -->
            <el-table-column
              prop="Position"
              :label="$t('trials:uploadClinicalData:table:bodyPart')"
              width="180"
            />
            <!-- 开始日期 -->
            <el-table-column
              prop="StartTime"
              :label="$t('trials:uploadClinicalData:table:beginDate')"
              width="180"
            >
              <template slot-scope="scope">
                {{ scope.row.StartTime?moment(scope.row.StartTime).format('YYYY-MM-DD'):'' }}
              </template>
            </el-table-column>
            <!-- 结束日期 -->
            <el-table-column
              prop="EndTime"
              :label="$t('trials:uploadClinicalData:table:endDate')"
              width="180"
            >
              <template slot-scope="scope">
                {{ scope.row.EndTime?moment(scope.row.EndTime).format('YYYY-MM-DD'):'' }}
              </template>
            </el-table-column>
            <!-- 病灶是否PD -->
            <el-table-column
              prop="IsPD"
              :label="$t('trials:uploadClinicalData:table:isPD')"
              width="180"
            >
              <template slot-scope="scope">
                {{ $fd('IsPdEnum', scope.row.IsPD) }}
              </template>
            </el-table-column>
          </el-table>
          <!-- 既往手术史 -->
          <h4>{{ $t('trials:uploadClinicalData:title:pastSurgery') }}</h4>
          <el-table
            :data="selected.clinicalTableData.PreviousSurgeryList"
            style="width: 100%"
          >
            <el-table-column
              type="index"
              width="50"
            />
            <!-- 手术名称 -->
            <el-table-column
              prop="OperationName"
              :label="$t('trials:uploadClinicalData:table:surgeryName')"
              width="180"
            />
            <!-- 手术日期 -->
            <el-table-column
              prop="OperationTime"
              :label="$t('trials:uploadClinicalData:table:surgeryDate')"
              width="180"
            >
              <template slot-scope="scope">
                {{ scope.row.OperationTime?moment(scope.row.OperationTime).format('YYYY-MM-DD'):'' }}
              </template>
            </el-table-column>
          </el-table>
          <!-- 既往其他治疗史 -->
          <h4>{{ $t('trials:uploadClinicalData:title:others') }}</h4>
          <el-table
            :data="selected.clinicalTableData.PreviousOtherList"
            style="width: 100%"
          >
            <el-table-column
              type="index"
              width="50"
            />
            <!-- 治疗类型 -->
            <el-table-column
              prop="TreatmentType"
              :label="$t('trials:uploadClinicalData:table:treatmentType')"
              width="180"
            />
            <!-- 开始日期 -->
            <el-table-column
              prop="StartTime"
              :label="$t('trials:uploadClinicalData:table:treatmentbeginDate')"
              width="180"
            >
              <template slot-scope="scope">
                {{ scope.row.StartTime?moment(scope.row.StartTime).format('YYYY-MM-DD'):'' }}
              </template>
            </el-table-column>
            <!-- 结束日期 -->
            <el-table-column
              prop="EndTime"
              :label="$t('trials:uploadClinicalData:table:treatmentendDate')"
              width="180"
            >
              <template slot-scope="scope">
                {{ scope.row.EndTime?moment(scope.row.EndTime).format('YYYY-MM-DD'):'' }}
              </template>
            </el-table-column>
          </el-table>
        </div>
        <!-- 保存 -->
        <div v-if="isConfirm === '1'" style="text-align: right;position: fixed;left: 0;bottom: 20px;width: 100%;padding-right: 20px">
          <el-button size="small" type="primary" @click="submitClinicalForm">
            {{ type === 'unconfirm' ? $t('trials:workbench:button:Approve') : $t('common:button:confirm') }}
          </el-button>
        </div>
      </div>
      <el-dialog
        v-if="signVisible"
        :visible.sync="signVisible"
        :close-on-click-modal="false"
        width="600px"
        append-to-body
        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>
    <div  v-if="isConfirm === '1' && type !== 'unconfirm'" style="width: 100%;height: 200px">
      <el-divider content-position="left">{{ $t('trials:readingPeriod:verify:title:result') }}</el-divider>
      <el-form
        ref="verificationForm"
        v-loading="loading"
        :model="verificationForm"
        size="small"
        :rules="rules"
        label-width="150px"
        :inline="true"
      >
        <div>
          <!-- 临床信息是否完整 -->
          <el-form-item :label="$t('trials:readingPeriod:verify:title:isComplete')" prop="IsComplete">
            <el-radio-group v-model="verificationForm.IsComplete">
              <el-radio :label="true">{{ $fd('YesOrNo', true) }}</el-radio>
              <el-radio :label="false">N/A</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <div>
          <!-- 临床信息是否盲化 -->
          <el-form-item :label="$t('trials:readingPeriod:verify:title:isBlind')" prop="IsBlind">
            <el-radio-group v-model="verificationForm.IsBlind">
              <el-radio :label="true">{{ $fd('YesOrNo', true) }}</el-radio>
              <el-radio :label="false">N/A</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
      </el-form>
    </div>
  </div>
</template>
<script>
import { getReadingOrTaskClinicalDataList, PMConfirmClinical } from '@/api/trials'
import store from '@/store'
import { changeURLStatic } from '@/utils/history.js'
import clinicalDataQuestions from '@/components/clinicalDataQuestions'


import SignForm from '@/views/trials/components/newSignForm'
import const_ from '@/const/sign-code'

import moment from 'moment'
export default {
  name: 'MultipleNoneDicom',
  components: { clinicalDataQuestions, SignForm },
  data() {
    return {
      verificationForm: {},
      rules: {
        IsBlind: [{ required: true, message: this.$t('common:ruleMessage:select') }],
        IsComplete: [{ required: true, message: this.$t('common:ruleMessage:select') }]
      },
      type: null,
      signCode: null,
      signVisible: false,
      currentUser: zzSessionStorage.getItem('userName'),
      selected: {
        id: '',
        type: null, // 0:格式化录入；1：pdf; 2:其他
        fileName: '',
        filePath: '',
        clinicalTableData: []
      },
      isShow: false,
      cdList: [],
      otherInfo: {},
      isConfirm: '0',
      moment,
      loading: false
    }
  },
  mounted() {
    if (this.$router.currentRoute.query.TokenKey) {
      store.dispatch('user/setToken', this.$router.currentRoute.query.TokenKey)
      changeURLStatic('TokenKey', '')
    }
    this.isConfirm = this.$router.currentRoute.query.isConfirm
    this.type = this.$router.currentRoute.query.type
    this.getList()
  },
  methods: {
    closeSignDialog(isSign, signInfo) {
      if (isSign) {
        this.confirmClinicalData(signInfo)
      } else {
        this.signVisible = false
      }
    },
    submitClinicalForm() {
      if (this.type !== 'unconfirm') {
        this.$refs.verificationForm.validate(valid => {
          if (!valid) return
          const { CDQualityConfirmation } = const_.processSignature
          this.signCode = CDQualityConfirmation
          this.signVisible = true
        })
      } else {
        const { CDQualityConfirmation } = const_.processSignature
        this.signCode = CDQualityConfirmation
        this.signVisible = true
      }
    },
    confirmClinicalData(signInfo) {
      var params = {
        data: {
          TrialId: this.$router.currentRoute.query.trialId,
          SubjectId: this.$router.currentRoute.query.subjectId,
          ReadModuleId: this.$router.currentRoute.query.readingId,
          IsConfirm: this.type === 'unconfirm' ? false : true,
          IsClinicalDataComplete: this.verificationForm.IsComplete,
          IsClinicalDataBlind: this.verificationForm.IsBlind,
        }
      }
      if (signInfo) {
        params.signInfo = signInfo
      }
      PMConfirmClinical(params).then(res => {
        this.$message.success( this.type === 'confirm' ? this.$t('trials:workbench:message:msg1') : this.$t('trials:workbench:message:msg2'))
        this.signVisible = false
        this.confirmVisible = false
        window.opener.postMessage({ type: 'pmConfirmClinical', data: '' }, window.location)
        this.isConfirm = '0'
      }).catch(() => {
        this.$refs['signForm'].btnLoading = false
      })
    },
    // 获取非Dicom检查信息
    getList() {
      this.loading = true
      var param = {
        subjectId: this.$router.currentRoute.query.subjectId,
        trialId: this.$router.currentRoute.query.trialId,
        getClinicalType: this.$router.currentRoute.query.getClinicalType && this.$router.currentRoute.query.getClinicalType !== 'null' ? this.$router.currentRoute.query.getClinicalType : '',
        ClinicalDataTrialSetId: this.$router.currentRoute.query.ClinicalDataTrialSetId ? this.$router.currentRoute.query.ClinicalDataTrialSetId : '',
        readingId: this.$router.currentRoute.query.readingId ? this.$router.currentRoute.query.readingId : '',
        visitTaskId: this.$router.currentRoute.query.visitTaskId ? this.$router.currentRoute.query.visitTaskId : '',
        readingClinicalDataId: this.$router.currentRoute.query.readingClinicalDataId ? this.$router.currentRoute.query.readingClinicalDataId : '',
        IsGetAllConsistencyAnalysis:this.$router.currentRoute.query.isGetAllConsistencyAnalysis == 0 ? false : true,
      }
      if (this.$router.currentRoute.query.IsOnlyGetCRCReadModule) {
        param.IsOnlyGetCRCReadModule = true
      }
      console.log('getList')
      getReadingOrTaskClinicalDataList(param).then(res => {
        console.log(res.Result)
        this.cdList = res.Result
        this.otherInfo = res.OtherInfo
        this.loading = false
        console.log('cdList', this.cdList)
        if (this.cdList.length > 0) {
          var type = this.cdList[0].ClinicalUploadType === 1 ? 1 : this.cdList[0].ClinicalUploadType === 2 ? 2 : 0
          var obj = type === 1 ? this.cdList[0].FileList[0] : this.cdList[0]
          if (type === 2) {
            obj = this.cdList[0].ClinicalFromList[0]
          }
          this.preview(obj, type, this.cdList[0])
        }
      }).catch(() => { this.loading = false })
    },
    preview(obj, type, item) {
      this.$set(this.selected, 'id', obj.Id)
      this.$set(this.selected, 'type', type)
      if (type === 1) {
        // PDF
        this.$set(this.selected, 'fileName', obj.FileName)
        this.$set(this.selected, 'filePath', obj.Path)
      } else if (type === 2) {
        // 自定义表单
        this.isShow = false
        console.log(item, obj)
        this.$set(this.selected, 'id', obj.ClinicalFormId)
        this.$set(this.selected, 'ClinicalDataTrialSetId', item.ClinicalDataTrialSetId)
        this.$set(this.selected, 'ClinicalFormId', obj.ClinicalFormId)
        this.$set(this.selected, 'VisitId', item.VisitId)
        this.$set(this.selected, 'SubjectId', item.SubjectId)
        this.$set(this.selected, 'TrialId', item.TrialId)
        this.$set(this.selected, 'ReadingId', item.ReadingId)
        this.$nextTick(() => {
          this.isShow = true
        })
      } else {
        // 格式化录入
        console.log('ClinicalTableData', obj.ClinicalTableData)
        this.$set(this.selected, 'clinicalTableData', obj.ClinicalTableData)
      }
    }
  }
}
</script>
<style lang="scss">
.preview-wrapper{
  display: flex;
  flex-direction: row !important;
  width: 100%;
  height: 100%;
  padding: 5px;
  overflow: hidden;
  ::-webkit-scrollbar {
    width: 7px;
    height: 7px;
  }
  ::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: #d0d0d0;
  }
  .left-wrapper{
    box-sizing: border-box;
    margin-right: 10px;
    height: 100%;
    width: 300px;
    border: 1px solid #ddd;

    .basic-info{
      height: 50px;
      line-height: 40px;
      padding: 5px 10px;
      font-size: 20px;
      font-weight: bold;
      background-color: #4e4e4e;
      color: #fbfbfb;
    }
    .activeBtn{
      color: #428bca;
      border-color: #428bca;
    }
    .basic-content{
      height: 100%;
      overflow: auto;
    }
    .basic-content-empty{
      padding: 5px;
      font-size: 16px;
    }
    .cd-wrapper{
      padding: 5px;

    }
    .cd-name-wrapper{
      height: 40px;
      line-height: 40px;
      padding-left: 5px;
      font-size: 15px;
      font-weight: bold;
      background-color: #eee;
    }
    .cd-item{
      box-sizing: border-box;
      border-bottom: 2px solid #f3f3f3;
      height: 50px;
      line-height: 50px;
      cursor: pointer;
      padding-left: 5px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }
  .right-wrapper{
    flex: 1;
    height: 100%;
    border: 1px solid #ddd;
  }
  .right-content{
    height:100%;
  }

}
</style>
