<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" disabled>
        <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="taskInfo.IsReadingTaskViewInOrder !== 0 ? item.StudyCode : `${item.Modalities}(${item.SeriesCount})`"
          :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" @click="handleSubmitFusionSeries">
        {{ $t('common:button:confirm') }}</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
export default {
  name: 'FusionForm',
  props: {
    taskList: {
      type: Array,
      default: () => {
        return []
      }
    },
    activeTaskIndex: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      fusionForm: {
        visitTaskId: '',
        studyId: '',
        taskBlindName: '',
        isBaseLineTask: null,
        ctSeriesInfo: {},
        petSeriesInfo: {},
        defaultStudyId: '',
        defaultCTSeriesId: '',
        defaultPTSeriesId: ''
      },
      studyList: [],
      ctSeries: [],
      petSeries: [],
      petctWindow: null,
      digitPlaces: 2,
      taskInfo: {}
    }
  },
  mounted() {
    this.taskInfo = JSON.parse(sessionStorage.getItem('taskInfo'))
    var digitPlaces = Number(localStorage.getItem('digitPlaces'))
    this.digitPlaces = digitPlaces === -1 ? this.digitPlaces : digitPlaces
    this.initForm()
  },
  methods: {
    initForm() {
      if (this.taskList.length === 0) return
      this.getStudyList(this.taskList[this.activeTaskIndex])
      this.handleStudyIdChange(this.studyList[0].StudyId)
      if (this.studyList.length > 0) {
        this.fusionForm.studyId = this.studyList[0].StudyId
        this.handleStudyIdChange(this.studyList[0].StudyId)
      } else {
        this.fusionForm.studyId = ''
        this.ctSeries = []
        this.petSeries = []
      }
      this.fusionForm.visitTaskId = this.taskList[this.activeTaskIndex].VisitTaskId
      this.fusionForm.readingTaskState = this.taskList[this.activeTaskIndex].ReadingTaskState
      this.fusionForm.taskBlindName = this.taskList[this.activeTaskIndex].TaskBlindName
      this.fusionForm.subjectCode = this.taskList[this.activeTaskIndex].SubjectCode
      this.fusionForm.isBaseLineTask = this.taskList[this.activeTaskIndex].IsBaseLineTask
      this.fusionForm.isCurrentTask = this.taskList[this.activeTaskIndex].IsCurrentTask
    },
    getStudyList(obj) {
      if (obj) {
        var studyList = obj.StudyList || []
        studyList = studyList.filter(i => !i.IsCriticalSequence && (i.Modalities.indexOf('CT') !== -1 || i.Modalities.indexOf('MR') !== -1) && (i.Modalities.indexOf('PT') !== -1 || i.Modalities.indexOf('NM') !== -1))
        if (studyList.length === 0) return
        this.studyList = studyList
      }
    },
    handleSubmitFusionSeries() {
      this.$refs['fusionForm'].validate((valid) => {
        if (!valid) return
        if (Object.keys(this.fusionForm.ctSeriesInfo).length === 0 || Object.keys(this.fusionForm.petSeriesInfo).length === 0) {
          // '请选择序列信息！'
          this.$confirm(this.$t('trials:lugano:fusionDialog:message:checkSeries'), this.$t('trials:lugano:fusionDialog:warning'), {
            showCancelButton: false,
            type: 'warning'
          }).then(() => { }).catch(() => { })
          return
        }
        var count = Math.abs(this.fusionForm.ctSeriesInfo.InstanceCount - this.fusionForm.petSeriesInfo.InstanceCount)
        if (count > 10) {
          // '选择的两组序列，影像数存在较大差距, 是否继续?'
          this.$confirm(this.$t('trials:lugano:fusionDialog:message:validSeries'), this.$t('trials:lugano:fusionDialog:warning'), {
            type: 'warning'
          }).then(() => {
            this.fusion()
          }).catch(() => { })
        } else {
          this.fusion()
        }
      })
    },
    fusion() {
      this.$emit('fusion', { ct: this.fusionForm.ctSeriesInfo, pt: this.fusionForm.petSeriesInfo })
    },
    handleCancel() {
      this.$emit('close')
    },
    handleTaskIdChange(v) {
      var idx = this.taskList.findIndex(i => i.VisitTaskId === v)
      this.studyList = idx > -1 ? this.getStudyList(this.taskList[idx]) : []
      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].StudyList : 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 i = this.studyList.findIndex(i => i.StudyId === v)
      if (i === -1) {
        this.ctSeries = []
        this.petSeries = []
      } else {
        var seriesList = this.studyList[i].SeriesList
        var series = seriesList.filter(series => series.Modality === 'CT' || series.Modality === 'MR')
        this.ctSeries = series.sort((a, b) => b.instanceCount - a.instanceCount)

        series = seriesList.filter(series => series.Modality === 'PT' || series.Modality === 'NM')
        this.petSeries = series.sort((a, b) => b.instanceCount - a.instanceCount)
      }
    },
    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>
