<template>
  <el-form ref="fusionForm" :model="fusionForm" label-width="120px" label-position="left">
    <!-- 任务名称 -->
    <el-form-item
      :label="$t('trials:lugano:fusionDialog:label:taskBlindName')"
      prop="taskBlindName"
    >
      <el-select
        v-model="fusionForm.visitTaskId"
        clearable
        @change="handleTaskIdChange"
      >
        <el-option
          v-for="item in taskList"
          :key="item.VisitTaskId"
          :label="item.TaskBlindName"
          :value="item.VisitTaskId"
        />
      </el-select>
    </el-form-item>
    <!-- 检查 -->
    <el-form-item
      :label="$t('trials:lugano:fusionDialog:label:study')"
      prop="studyId"
      :rules="[
        { required: true, message: $t('common:ruleMessage:select'), trigger: 'blur' }
      ]"
    >
      <el-select
        v-model="fusionForm.studyId"
        clearable
        @change="handleStudyIdChange"
      >
        <el-option
          v-for="item in studyList"
          :key="item.StudyId"
          :label="item.StudyCode"
          :value="item.StudyId"
        />
      </el-select>
    </el-form-item>
    <!-- 融合图像 -->
    <label style="color: #dfdfdf;line-height: 36px;vertical-align: middle;font-size: 14px;">{{ $t('trials:lugano:fusionDialog:label:fusionImages') }}</label>
    <div style="display: flex;flex-direction: row;justify-content: space-between;margin-bottom:10px;" class="series-table">

      <div style="border: 1px solid #5e5e5e;border-radius: 5px;padding: 0 10px;">
        <!-- CT/MRI序列 -->
        <h3 style="color:#ddd">{{ $t('trials:lugano:fusionDialog:label:ctSeries') }}</h3>
        <el-table
          ref="ctSeries"
          :data="ctSeries"
          :show-header="false"
          style="width: 380px"
          size="mini"
          height="300"
          :default-sort="{prop: 'instanceCount', order: 'descending'}"
          @selection-change="handleCTSelectionChange"
          @select="handleCTSelect"
        >

          <el-table-column
            type="selection"
            width="30"
          />
          <el-table-column
            label=""
            width="100"
          >
            <template slot-scope="scope">
              <el-image
                style="width: 60px; height: 60px"
                :src="`${OSSclientConfig.basePath}${scope.row.ImageResizePath}`"
                fit="fit"
                crossorigin="anonymous"
              />
            </template>
          </el-table-column>
          <el-table-column
            label=""
            min-width="50"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div>#{{ scope.row.SeriesNumber }} </div>
              <div>{{ scope.row.Modality }}: {{ scope.row.InstanceCount }} images  T: {{ parseFloat(scope.row.SliceThickness).toFixed(digitPlaces) }}</div>
              <div>{{ scope.row.Description }}</div>
            </template>
          </el-table-column>

        </el-table>
      </div>

      <div style="border: 1px solid #5e5e5e;border-radius: 5px;padding: 0 10px;">
        <!-- PET序列 -->
        <h3 style="color:#ddd">{{ $t('trials:lugano:fusionDialog:label:ptSeries') }}</h3>
        <el-table
          ref="petSeries"
          :data="petSeries"
          :show-header="false"
          style="width: 380px"
          size="mini"
          height="300"
          @selection-change="handlePTSelectionChange"
          @select="handlePTSelect"
        >
          <el-table-column
            type="selection"
            width="30"
          />
          <el-table-column
            label=""
            width="100"
          >
            <template slot-scope="scope">
              <el-image
                style="width: 60px; height: 60px"
                :src="`${OSSclientConfig.basePath}${scope.row.ImageResizePath}`"
                fit="fit"
                crossorigin="anonymous"
              />
            </template>
          </el-table-column>
          <el-table-column
            label=""
            min-width="50"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <div>#{{ scope.row.SeriesNumber }} </div>
              <div>{{ scope.row.Modality }}: {{ scope.row.InstanceCount }} images  T: {{ parseFloat(scope.row.SliceThickness).toFixed(digitPlaces) }}</div>
              <div>{{ scope.row.Description }}</div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <el-form-item style="text-align:right;">
      <!-- 取消 -->
      <el-button size="mini" @click="handleCancel">{{ $t('common:button:cancel') }}</el-button>
      <!-- 确认 -->
      <el-button
        type="primary"
        size="mini"
        :loading="submitLoading"
        :disabled="submitLoading"
        @click="handleSubmitFusionSeries"
      >
        {{ $t('common:button:confirm') }}</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { getPTAndCtSeries } from '@/api/trials'
import { getToken } from '@/utils/auth'
export default {
  name: 'FusionForm',
  data() {
    return {
      fusionForm: {
        visitTaskId: '',
        studyId: '',
        taskBlindName: '',
        isBaseLineTask: null,
        ctSeriesInfo: {},
        petSeriesInfo: {},
        defaultStudyId: '',
        defaultCTSeriesId: '',
        defaultPTSeriesId: ''
      },
      visitTaskId: '',
      taskList: [],
      studyList: [],
      ctSeries: [],
      petSeries: [],
      petctWindow: null,
      digitPlaces: 2,
      submitLoading: false
    }
  },
  mounted() {
    var digitPlaces = Number(localStorage.getItem('digitPlaces'))
    this.digitPlaces = digitPlaces === -1 ? this.digitPlaces : digitPlaces
    this.visitTaskId = this.$route.query.visitTaskId
    this.getSeriesInfo()
  },
  methods: {
    getSeriesInfo() {
      const loading = this.$loading({ fullscreen: true })
      getPTAndCtSeries({ visitTaskId: this.visitTaskId }).then(res => {
        this.taskList = res.Result
        this.initForm()
        loading.close()
      }).catch(() => {
        loading.close()
      })
    },
    initForm() {
      if (this.taskList.length === 0) return
      this.fusionForm.visitTaskId = this.taskList[0].VisitTaskId
      this.fusionForm.taskBlindName = this.taskList[0].TaskBlindName
      this.fusionForm.isBaseLineTask = this.taskList[0].IsBaseLineTask

      this.studyList = this.taskList[0].StudyInfoList
      const studyIdx = this.taskList[0].StudyInfoList.findIndex(i => i.StudyId === this.taskList[0].StudyId)
      this.fusionForm.studyId = this.studyList[studyIdx].StudyId
      this.fusionForm.defaultStudyId = this.taskList[0].StudyId
      this.fusionForm.defaultCTSeriesId = this.taskList[0].CTSeriesId
      this.fusionForm.defaultPTSeriesId = this.taskList[0].PTSeriesId
      this.ctSeries = this.studyList[studyIdx].CTSeriesList
      this.petSeries = this.studyList[studyIdx].PTSeriesList
      const ctSexiesIdx = this.ctSeries.findIndex(i => i.Id === this.taskList[0].CTSeriesId)

      const ptSexiesIdx = this.petSeries.findIndex(i => i.Id === this.taskList[0].PTSeriesId)

      this.$nextTick(() => {
        this.fusionForm.ctSeriesInfo = Object.assign({}, this.ctSeries[ctSexiesIdx])
        this.fusionForm.petSeriesInfo = Object.assign({}, this.petSeries[ptSexiesIdx])
        this.$refs.ctSeries.toggleRowSelection(this.ctSeries[ctSexiesIdx])
        this.$refs.petSeries.toggleRowSelection(this.petSeries[ptSexiesIdx])
      })
    },
    async handleSubmitFusionSeries() {
      if (this.submitLoading) return
      this.submitLoading = true
      try {
        const valid = await this.$refs['fusionForm'].validate()
        if (!valid) return
        if (Object.keys(this.fusionForm.ctSeriesInfo).length === 0 || Object.keys(this.fusionForm.petSeriesInfo).length === 0) {
          // '请选择序列信息！'
          await this.$confirm(this.$t('trials:lugano:fusionDialog:message:checkSeries'), this.$t('trials:lugano:fusionDialog:warning'), {
            showCancelButton: false,
            type: 'warning'
          }).catch(() => {})
          return
        }
        var count = Math.abs(this.fusionForm.ctSeriesInfo.instanceCount - this.fusionForm.petSeriesInfo.instanceCount)
        if (count > 10) {
          // '选择的两组序列，影像数存在较大差距, 是否继续?'
          const confirm = await this.$confirm(this.$t('trials:lugano:fusionDialog:message:validSeries'), this.$t('trials:lugano:fusionDialog:warning'), {
            type: 'warning'
          }).catch(() => false)
          if (confirm !== 'confirm') return
        }
        this.fusion()
      } finally {
        this.submitLoading = false
      }
    },
    fusion() {
      const token = getToken()
      const trialReadingCriterionId = this.$route.query.TrialReadingCriterionId
      const trialId = this.$route.query.trialId
      const digitPlaces = Number(localStorage.getItem('digitPlaces'))
      const isReadingShowSubjectInfo = this.$route.query.isReadingShowSubjectInfo
      const subjectCode = this.$route.query.subjectCode
      const path = `/petct?TrialReadingCriterionId=${trialReadingCriterionId}&trialId=${trialId}&visitTaskId=${this.fusionForm.visitTaskId}&taskBlindName=${this.fusionForm.taskBlindName}&subjectCode=${subjectCode}&readingTaskState=2&isBaseLineTask=${this.fusionForm.isBaseLineTask}&isCurrentTask=false&isReadingShowSubjectInfo=${isReadingShowSubjectInfo}&studyId=${this.fusionForm.studyId}&ctseriesId=${this.fusionForm.ctSeriesInfo.Id}&ptseriesId=${this.fusionForm.petSeriesInfo.Id}&digitPlaces=${digitPlaces}&TokenKey=${token}&lang=${this.$i18n.locale}`
      var routeData = this.$router.resolve({ path })
      if (this.petctWindow) {
        this.petctWindow.close()
      }
      this.petctWindow = window.open(routeData.href, '_blank')
      this.$emit('close')
    },
    handleCancel() {
      this.$emit('close')
    },
    handleTaskIdChange(v) {
      var idx = this.taskList.findIndex(i => i.VisitTaskId === v)
      this.studyList = idx > -1 ? this.taskList[idx].StudyInfoList : []
      this.fusionForm.taskBlindName = idx > -1 ? this.taskList[idx].TaskBlindName : ''
      this.fusionForm.isBaseLineTask = idx > -1 ? this.taskList[idx].IsBaseLineTask : null
      this.studyList = idx > -1 ? this.taskList[idx].StudyInfoList : null
      this.fusionForm.studyId = ''
      this.fusionForm.defaultStudyId = idx > -1 ? this.taskList[idx].StudyId : ''
      this.fusionForm.defaultCTSeriesId = idx > -1 ? this.taskList[idx].CTSeriesId : ''
      this.fusionForm.defaultPTSeriesId = idx > -1 ? this.taskList[idx].PTSeriesId : ''
      this.ctSeries = []
      this.petSeries = []
    },
    handleStudyIdChange(v) {
      var idx = this.studyList.findIndex(i => i.StudyId === v)
      this.ctSeries = idx > -1 ? this.studyList[idx].CTSeriesList : []
      this.petSeries = idx > -1 ? this.studyList[idx].PTSeriesList : []
      if (v === this.fusionForm.defaultStudyId) {
        this.$nextTick(() => {
          const ctSexiesIdx = this.ctSeries.findIndex(i => i.Id === this.fusionForm.defaultCTSeriesId)
          const ptSexiesIdx = this.petSeries.findIndex(i => i.Id === this.fusionForm.defaultPTSeriesId)
          this.fusionForm.ctSeriesInfo = Object.assign({}, this.ctSeries[ctSexiesIdx])
          this.fusionForm.petSeriesInfo = Object.assign({}, this.petSeries[ptSexiesIdx])
          this.$refs.ctSeries.clearSelection()
          this.$refs.ctSeries.toggleRowSelection(this.ctSeries[ctSexiesIdx])
          this.$refs.petSeries.clearSelection()
          this.$refs.petSeries.toggleRowSelection(this.petSeries[ptSexiesIdx])
        })
      }
    },
    handleCTSelectionChange(rows) {
      if (rows.length > 0) {
        this.fusionForm.ctSeriesInfo = Object.assign({}, rows[0])
      } else {
        this.fusionForm.ctSeriesInfo = {}
      }
    },
    handleCTSelect(selection) {
      if (selection.length > 1) {
        const del_row = selection.shift()
        this.$refs.ctSeries.toggleRowSelection(del_row, false)
      }
    },
    handlePTSelectionChange(rows) {
      if (rows.length > 0) {
        this.fusionForm.petSeriesInfo = Object.assign({}, rows[0])
      } else {
        this.fusionForm.petSeriesInfo = {}
      }
    },
    handlePTSelect(selection) {
      if (selection.length > 1) {
        const del_row = selection.shift()
        this.$refs.petSeries.toggleRowSelection(del_row, false)
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.series-table{
  ::v-deep .el-table{
    background-color:  #1e1e1e !important;
    color: #dfdfdf;
  }
  ::v-deep .el-table td.el-table__cell, .el-table th.el-table__cell.is-leaf{
    border-bottom: 1px solid #dfdfdf;
  }
  .el-table--border::after, .el-table--group::after, .el-table::before{
    background-color: #1e1e1e;
  }
  ::v-deep .el-table__header-wrapper{
    th{
      background-color:  #1e1e1e !important;
      color: #dfdfdf;
    }
  }
  ::v-deep .el-table__body-wrapper{
    tr{
      background-color:  #1e1e1e !important;
      color: #dfdfdf;
    }
    tr:hover > td{
      background-color:  #1e1e1e !important;
    }
  }
  ::v-deep .el-table__empty-block{
    background-color:  #1e1e1e !important;
  }
}

</style>
