<template>
  <div class="clinical-data_content">
    <el-tabs type="card" v-model="clinicalType" v-if="!(data.IsVisit || data.IsBaseLine)">
      <el-tab-pane v-for="item in $d.GetClinicalType" :key="item.Id" :label="item.label" :name="item.value.toString()">
        <div v-if="item.value === 1">
          <h4 style="margin:0">
            <!-- 提示： -->
            {{ $t('trials:readingPeriod:cd:title:tips') }}
          </h4>
          <h5>
            <!-- 当前访视/阅片期需要采集“临床数据名称”。请采集临床数据后，按照模板上传，并签名确认。 -->
            {{ $t('trials:readingPeriod:cd:title:tips1') }}
          </h5>
          <h5>
            {{ $t('trials:readingPeriod:cd:title:tips2') }}
          </h5>
        </div>
        <div class="top">
          <!-- 预览 -->
          <el-button
            type="primary"
            icon="el-icon-view"
            size="small"
            :disabled="list.length===0"
            @click="handlePreview()"
          >
            {{ $t('trials:readingPeriod:cd:title:preview') }}
          </el-button>
          <!-- 添加 -->
          <el-button
            v-if="otherInfo.IsCanAddClinicalData && hasPermi(['trials:trials-panel:subject:readingPeriod:edit']) && clinicalType === '1'"
            type="primary"
            icon="el-icon-plus"
            size="small"
            @click="handleAdd"
          >
            {{ $t('common:button:add') }}
          </el-button>
          <el-button
            v-if="hasPermi(['trials:trials-panel:subject:readingPeriod:edit']) && clinicalType === '2' && list.length > 0 && list[0].ReadingClinicalDataState !== 3 && !list[0].IsCRCApplicationRevoke"
            type="primary"
            icon="el-icon-plus"
            size="small"
            :disabled="list.length === 0"
            @click="handleVerification(list[0], 'confirm')"
          >
            核查
          </el-button>
          <el-button
            v-if="hasPermi(['trials:trials-panel:subject:readingPeriod:edit']) && clinicalType === '2' && list.length > 0 && list[0].ReadingClinicalDataState !== 3 && list[0].IsCRCApplicationRevoke"
            type="primary"
            icon="el-icon-plus"
            size="small"
            :disabled="list.length === 0"
            @click="handleVerification(list[0], 'unconfirm')"
          >
            撤回审批
          </el-button>
        </div>
        <div class="main">
          <el-table
            v-loading="loading"
            :data="list"
            stripe
            style="width: 100%"
            height="500"
          >
            <el-table-column type="index" width="40" />
            <!-- 临床数据名称 -->
            <el-table-column
              prop="ClinicalDataSetName"
              :label="$t('trials:readingPeriod:cd:table:clinicalDataName')"
            />
            <el-table-column
              prop="UploadRole"
              label="上传人"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                {{ $fd('ClinicalDataUploadRole',scope.row.UploadRole) }}
              </template>
            </el-table-column>
            <!-- 数据级别 -->
            <el-table-column
              prop="ClinicalDataLevel"
              :label="$t('trials:readingPeriod:cd:table:dataLevel')"
            >
              <template slot-scope="scope">
                {{ $fd('ClinicalLevel',scope.row.ClinicalDataLevel) }}
              </template>
            </el-table-column>
            <!-- 传输方式 -->
            <el-table-column
              prop="ClinicalUploadType"
              :label="$t('trials:readingPeriod:cd:table:transferType')"
            >
              <template slot-scope="scope">
                {{ $fd('ClinicalUploadType',scope.row.ClinicalUploadType) }}
              </template>
            </el-table-column>
            <!-- 文件数量 -->
            <el-table-column
              prop="FileCount"
              :label="$t('trials:readingPeriod:cd:table:fileCount')"
            >
              <template slot-scope="scope">
                {{ scope.row.ClinicalUploadType === 0?'NA':scope.row.FileCount }}
              </template>
            </el-table-column>
            <!-- 阅片临床数据状态 -->
            <el-table-column
              prop="ReadingClinicalDataState"
              :label="$t('trials:readingPeriod:cd:title:cdStatus')"
              width="150"
            >
              <template slot-scope="scope">
                <el-tag v-if="scope.row.ReadingClinicalDataState === 0" type="info">{{ $fd('ReadingClinicalDataState', scope.row.ReadingClinicalDataState) }}</el-tag>
                <el-tag v-if="scope.row.ReadingClinicalDataState === 1" type="danger">{{ $fd('ReadingClinicalDataState', scope.row.ReadingClinicalDataState) }}</el-tag>
                <el-tag v-if="scope.row.ReadingClinicalDataState === 2" type="primary">{{ $fd('ReadingClinicalDataState', scope.row.ReadingClinicalDataState) }}</el-tag>
                <el-tag v-if="scope.row.ReadingClinicalDataState === 3" type="warning">{{ $fd('ReadingClinicalDataState', scope.row.ReadingClinicalDataState) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column
              :label="$t('common:action:action')"
              width="260"
            >
              <template slot-scope="scope">
                <!-- 查看 -->
                <el-button
                  circle
                  :disabled="scope.row.ClinicalUploadType===1 && scope.row.FileCount === 0"
                  :title="$t('trials:readingPeriod:cd:action:view')"
                  icon="el-icon-view"
                  @click="handlePreview(scope.row.Id, scope.row)"
                />
                <!-- 编辑 -->
                <el-button
                  v-if="clinicalType === '1'"
                  v-hasPermi="['trials:trials-panel:subject:readingPeriod:edit']"
                  circle
                  :title="$t('trials:readingPeriod:cd:action:edit')"
                  icon="el-icon-edit-outline"
                  :disabled="scope.row.IsCRCUpload || scope.row.IsSign || scope.row.UploadRole === 0"
                  @click="handleEdit(scope.row)"
                />
                <!-- 编辑 -->
                <el-button
                  v-hasPermi="['trials:trials-panel:subject:readingPeriod:edit']"
                  v-if="clinicalType === '1'"
                  circle
                  :title="$t('trials:readingPeriod:cd:title:cdCheck')"
                  icon="el-icon-s-claim"
                  :disabled="(scope.row.IsCRCUpload || scope.row.IsSign || scope.row.UploadRole === 0)  && scope.row.ReadingClinicalDataState !== 2"
                  @click="handleVerification(scope.row, 'confirm')"
                />
                <!-- 删除 -->
                <el-button
                  v-if="clinicalType === '1'"
                  v-hasPermi="['trials:trials-panel:subject:readingPeriod:edit']"
                  circle
                  :title="$t('trials:readingPeriod:cd:action:delete')"
                  icon="el-icon-delete"
                  :disabled="scope.row.IsCRCUpload || scope.row.IsSign || scope.row.UploadRole === 0"
                  @click="handleDelete(scope.row)"
                />
              </template>
            </el-table-column>
          </el-table>

          <!-- 添加或编辑 -->
          <el-dialog
            v-if="addOrUpdateCD.visible"
            :visible.sync="addOrUpdateCD.visible"
            :close-on-click-modal="false"
            :title="addOrUpdateCD.title"
            width="500px"
            append-to-body
            custom-class="base-dialog-wrapper"
          >
            <AddOrEditCD :trial-reading-criterion-id="trialReadingCriterionId" :data="currentData" @close="addOrUpdateCD.visible = false" @getList="getList" />
          </el-dialog>

          <!-- 核查 -->
          <el-dialog
            v-if="verification.visible"
            :visible.sync="verification.visible"
            :close-on-click-modal="false"
            :title="verification.title"
            width="600px"
            append-to-body
            custom-class="base-dialog-wrapper"
          >
            <Verification :data="currentData" @close="verification.visible = false" @getList="getList" @handlePreview="handlePreview" @sign="handleSign" />
          </el-dialog>

          <!-- 签名 -->
          <el-dialog
            v-if="signVisible"
            :visible.sync="signVisible"
            :close-on-click-modal="false"
            width="600px"
            custom-class="base-dialog-wrapper"
            append-to-body
          >
            <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>
      </el-tab-pane>
    </el-tabs>
    <div v-else>
      <div class="top">
        <!-- 预览 -->
        <el-button
          type="primary"
          icon="el-icon-view"
          size="small"
          :disabled="list.length===0"
          @click="handlePreview()"
        >
          {{ $t('trials:readingPeriod:cd:title:preview') }}
        </el-button>
        <!-- 添加 -->
        <el-button
          v-if="otherInfo.IsCanAddClinicalData && hasPermi(['trials:trials-panel:subject:readingPeriod:edit'])"
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
        >
          {{ $t('common:button:add') }}
        </el-button>
      </div>
      <div class="main">
        <el-table
          v-loading="loading"
          :data="list"
          stripe
          style="width: 100%"
          height="500"
        >
          <el-table-column type="index" width="40" />
          <!-- 临床数据名称 -->
          <el-table-column
            prop="ClinicalDataSetName"
            :label="$t('trials:readingPeriod:cd:table:clinicalDataName')"
          />
          <el-table-column
            prop="UploadRole"
            label="上传人"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              {{ $fd('ClinicalDataUploadRole',scope.row.UploadRole) }}
            </template>
          </el-table-column>
          <!-- 数据级别 -->
          <el-table-column
            prop="ClinicalDataLevel"
            :label="$t('trials:readingPeriod:cd:table:dataLevel')"
          >
            <template slot-scope="scope">
              {{ $fd('ClinicalLevel',scope.row.ClinicalDataLevel) }}
            </template>
          </el-table-column>
          <!-- 传输方式 -->
          <el-table-column
            prop="ClinicalUploadType"
            :label="$t('trials:readingPeriod:cd:table:transferType')"
          >
            <template slot-scope="scope">
              {{ $fd('ClinicalUploadType',scope.row.ClinicalUploadType) }}
            </template>
          </el-table-column>
          <!-- 文件数量 -->
          <el-table-column
            prop="FileCount"
            :label="$t('trials:readingPeriod:cd:table:fileCount')"
          >
            <template slot-scope="scope">
              {{ scope.row.ClinicalUploadType === 0?'NA':scope.row.FileCount }}
            </template>
          </el-table-column>
          <!-- 阅片临床数据状态 -->
          <el-table-column
            prop="ReadingClinicalDataState"
            :label="$t('trials:readingPeriod:cd:title:cdStatus')"
            width="150"
          >
            <template slot-scope="scope">
              <el-tag v-if="scope.row.ReadingClinicalDataState === 0" type="info">{{ $fd('ReadingClinicalDataState', scope.row.ReadingClinicalDataState) }}</el-tag>
              <el-tag v-if="scope.row.ReadingClinicalDataState === 1" type="danger">{{ $fd('ReadingClinicalDataState', scope.row.ReadingClinicalDataState) }}</el-tag>
              <el-tag v-if="scope.row.ReadingClinicalDataState === 2" type="primary">{{ $fd('ReadingClinicalDataState', scope.row.ReadingClinicalDataState) }}</el-tag>
              <el-tag v-if="scope.row.ReadingClinicalDataState === 3" type="warning">{{ $fd('ReadingClinicalDataState', scope.row.ReadingClinicalDataState) }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('common:action:action')"
            width="260"
          >
            <template slot-scope="scope">
              <!-- 查看 -->
              <el-button
                circle
                :disabled="scope.row.ClinicalUploadType===1 && scope.row.FileCount === 0"
                :title="$t('trials:readingPeriod:cd:action:view')"
                icon="el-icon-view"
                @click="handlePreview(scope.row.Id, scope.row)"
              />
              <!-- 编辑 -->
              <el-button
                v-hasPermi="['trials:trials-panel:subject:readingPeriod:edit']"
                circle
                :title="$t('trials:readingPeriod:cd:action:edit')"
                icon="el-icon-edit-outline"
                :disabled="scope.row.IsCRCUpload || scope.row.IsSign || scope.row.UploadRole === 0"
                @click="handleEdit(scope.row)"
              />
              <!-- 编辑 -->
              <el-button
                v-hasPermi="['trials:trials-panel:subject:readingPeriod:edit']"
                circle
                :title="$t('trials:readingPeriod:cd:title:cdCheck')"
                icon="el-icon-s-claim"
                :disabled="(scope.row.IsCRCUpload || scope.row.IsSign || scope.row.UploadRole === 0)  && scope.row.ReadingClinicalDataState !== 2"
                @click="handleVerification(scope.row, 'confirm')"
              />
              <!-- 删除 -->
              <el-button
                v-hasPermi="['trials:trials-panel:subject:readingPeriod:edit']"
                circle
                :title="$t('trials:readingPeriod:cd:action:delete')"
                icon="el-icon-delete"
                :disabled="scope.row.IsCRCUpload || scope.row.IsSign || scope.row.UploadRole === 0"
                @click="handleDelete(scope.row)"
              />
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加或编辑 -->
        <el-dialog
          v-if="addOrUpdateCD.visible"
          :visible.sync="addOrUpdateCD.visible"
          :close-on-click-modal="false"
          :title="addOrUpdateCD.title"
          width="500px"
          append-to-body
          custom-class="base-dialog-wrapper"
        >
          <AddOrEditCD :trial-reading-criterion-id="trialReadingCriterionId" :data="currentData" @close="addOrUpdateCD.visible = false" @getList="getList" />
        </el-dialog>

        <!-- 核查 -->
        <el-dialog
          v-if="verification.visible"
          :visible.sync="verification.visible"
          :close-on-click-modal="false"
          :title="verification.title"
          width="600px"
          append-to-body
          custom-class="base-dialog-wrapper"
        >
          <Verification :data="currentData" @close="verification.visible = false" @getList="getList" @handlePreview="handlePreview" @sign="handleSign" />
        </el-dialog>

        <!-- 签名 -->
        <el-dialog
          v-if="signVisible"
          :visible.sync="signVisible"
          :close-on-click-modal="false"
          width="600px"
          custom-class="base-dialog-wrapper"
          append-to-body
        >
          <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>
  </div>
</template>
<script>
import { getReadingClinicalDataList, deleteReadingClinicalData, ReadClinicalDataSign } from '@/api/trials'
import AddOrEditCD from './AddOrEditCD'
import Verification from './Verification'
import SignForm from '@/views/trials/components/newSignForm'
import const_ from '@/const/sign-code'
import { getToken } from '@/utils/auth'
export default {
  name: 'ClinicalData',
  components: { AddOrEditCD, SignForm, Verification },
  props: {
    trialReadingCriterionId: {
      type: String,
      default() { return '' }
    },
    data: {
      type: Object,
      default() { return {} }
    }
  },
  watch: {
    clinicalType() {
      this.getList()
    },
  },
  data() {
    return {
      clinicalType: null,
      loading: false,
      searchData: {},
      list: [],
      total: 0,
      dialogVisible: false,
      addOrUpdateCD: { title: '', visible: false },
      verification: { title: '', visible: false },
      currentData: {},
      signCode: '',
      currentUser: zzSessionStorage.getItem('userName'),
      signVisible: false,
      otherInfo: {},
      spanArr: [],
      pos: 0,
    }
  },
  mounted() {
    if (!(this.data.IsVisit || this.data.IsBaseLine)) {
      this.clinicalType = this.$d.GetClinicalType[0].value.toString()
    } else {
      this.getList(true)
    }
    window.addEventListener('message', (res) => {
      if (res.data.type === 'pmConfirmClinical') {
        this.getList()
      }
    })
  },
  methods: {
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 6 && row.IsNeedMerge) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    getSpanArr(data) {
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1)
          this.pos = 0
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].IsNeedMerge === data[i - 1].IsNeedMerge) {
            this.spanArr[this.pos] += 1
            this.spanArr.push(0)
          } else {
            this.spanArr.push(1)
            this.pos = i
          }
        }
      }
    },
    getList(is) {
      this.searchData.ReadingId = this.data.Id
      this.searchData.SubjectId = this.data.SubjectId
      this.searchData.IsVisit = this.data.IsVisit
      this.searchData.TrialId = this.data.TrialId
      this.searchData.IsBaseLine = this.data.IsBaseLine
      this.searchData.TrialReadingCriterionId = this.trialReadingCriterionId
      if (!is) {
        this.searchData.GetClinicalType = this.clinicalType
      }
      this.loading = true
      getReadingClinicalDataList(this.searchData).then(res => {
        this.list = res.Result
        this.pos = 0
        this.getSpanArr(this.list)
        this.otherInfo = res.OtherInfo
        this.loading = false
      }).catch(() => { this.loading = false })
    },
    handleAdd() {
      this.currentData = Object.assign({}, { TrialId: this.data.TrialId, ReadingId: this.data.Id, IsVisit: this.data.IsVisit, SubjectId: this.data.SubjectId, IsBaseLine: this.data.IsBaseLine })
      this.addOrUpdateCD.title = this.$t('common:button:new')
      this.addOrUpdateCD.visible = true
    },
    handleEdit(row) {
      this.currentData = { ...row }
      this.currentData.TrialId = this.data.TrialId
      this.currentData.SubjectId = this.data.SubjectId
      this.currentData.ReadingId = this.data.Id
      this.currentData.IsVisit = this.data.IsVisit
      this.currentData.IsBaseLine = this.data.IsBaseLine
      this.addOrUpdateCD.title = this.$t('common:button:edit')
      this.addOrUpdateCD.visible = true
    },
    handleVerification(row, type) {
      if (type === 'unconfirm') {
        var token = getToken()
        const routeData = this.$router.resolve({
          path: `/clinicalData?type=unconfirm&ClinicalDataTrialSetId=${row.ClinicalDataTrialSetId}&subjectId=${this.data.SubjectId}&trialId=${this.data.TrialId}&readingId=${this.data.Id}&readingClinicalDataId=${row.readingClinicalDataId || ''}&readModuleId=${row.ReadModuleId}&getClinicalType=${this.clinicalType}&isConfirm=1&IsOnlyGetCRCReadModule=1&TokenKey=${token}`
        })
        window.open(routeData.href, '_blank')
        return
      }
      if (row.IsNeedMerge) {
        var token = getToken()
        const routeData = this.$router.resolve({
          path: `/clinicalData?ClinicalDataTrialSetId=${row.ClinicalDataTrialSetId}&subjectId=${this.data.SubjectId}&trialId=${this.data.TrialId}&readingId=${this.data.Id}&readingClinicalDataId=${row.readingClinicalDataId || ''}&readModuleId=${row.ReadModuleId}&getClinicalType=${this.clinicalType}&isConfirm=1&IsOnlyGetCRCReadModule=1&TokenKey=${token}`
        })
        window.open(routeData.href, '_blank')
      } else {
        this.currentData = { ...row }
        this.currentData.TrialId = this.data.TrialId
        this.currentData.SubjectId = this.data.SubjectId
        this.currentData.ReadingId = this.data.Id
        this.currentData.IsVisit = this.data.IsVisit
        this.currentData.IsBaseLine = this.data.IsBaseLine
        this.verification.title = this.$t('trials:readingPeriod:cd:title:cdCheck') // '核查'
        this.verification.visible = true
      }
    },
    handleDelete(row) {
      this.$confirm(this.$t('trials:readingPeriod:cd:message:delete'), {
        type: 'warning',
        distinguishCancelAndClose: true
      })
        .then(() => {
          this.loading = true
          deleteReadingClinicalData(row.Id)
            .then(res => {
              this.loading = false
              if (res.IsSuccess) {
                this.getList()
                this.$message.success(this.$t('common:message:deletedSuccessfully'))
              }
            }).catch(() => { this.loading = false })
        }).catch(() => {})
    },
    handleSign(from) {
      // this.currentData = { ...row }
      this.currentData.IsBlind = from.IsBlind
      this.currentData.IsComplete = from.IsComplete
      const { CDQualityConfirmation } = const_.processSignature
      this.signCode = CDQualityConfirmation
      this.signVisible = true
    },
    signConfirm(signInfo) {
      this.loading = true
      const params = {
        data: {
          readingClinicalDataId: this.currentData.Id,
          IsBlind: this.currentData.IsBlind,
          IsComplete: this.currentData.IsComplete,
          TrialReadingCriterionId: this.trialReadingCriterionId
        },
        signInfo: signInfo
      }
      ReadClinicalDataSign(params).then(res => {
        this.loading = false
        if (res.IsSuccess) {
          this.$message.success(this.$t('common:message:savedSuccessfully'))
          this.$refs['signForm'].btnLoading = false

          this.signVisible = false

          this.getList()
          this.$nextTick(() => { this.verification.visible = false })
        }
      }).catch(_ => {
        this.loading = false
        this.$refs['signForm'].btnLoading = false
      })
    },
    // 关闭签名框并设置确认状态
    closeSignDialog(isSign, signInfo) {
      if (isSign) {
        this.signConfirm(signInfo)
      } else {
        this.signVisible = false
      }
    },
    handlePreview(readingClinicalDataId, row) {
      if (row && row.IsNeedMerge) {
        var token = getToken()
        const routeData = this.$router.resolve({
          path: `/clinicalData?ClinicalDataTrialSetId=${row.ClinicalDataTrialSetId}&subjectId=${this.data.SubjectId}&trialId=${this.data.TrialId}&readingId=${this.data.Id}&readingClinicalDataId=${row.readingClinicalDataId || ''}&getClinicalType=${this.clinicalType}&readModuleId=${row.ReadModuleId}&IsOnlyGetCRCReadModule=1&TokenKey=${token}`
        })
        window.open(routeData.href, '_blank')

      } else {
        var token = getToken()
        var routeData
        if (row) {
          routeData = this.$router.resolve({
            path: `/clinicalData?ClinicalDataTrialSetId=${row.ClinicalDataTrialSetId}&subjectId=${this.data.SubjectId}&trialId=${this.data.TrialId}&readingId=${this.data.Id}&readingClinicalDataId=${readingClinicalDataId || ''}&getClinicalType=${this.clinicalType}&TokenKey=${token}`
          })
        } else {
          routeData = this.$router.resolve({
            path: `/clinicalData?subjectId=${this.data.SubjectId}&trialId=${this.data.TrialId}&readingId=${this.data.Id}&readingClinicalDataId=${readingClinicalDataId || ''}&getClinicalType=${this.clinicalType}&TokenKey=${token}`
          })
        }
        window.open(routeData.href, '_blank')
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.clinical-data_content{
  .top{
    text-align: right;
  }
  /deep/ .el-divider--horizontal{
    margin: 10px;
  }
}
</style>
