<template>
  <el-dialog :visible.sync="visible" :fullscreen="true" :close-on-click-modal="false" :before-close="beforeClose"
    :append-to-body="true" v-loading="btnLoading" class="downloadDicomAndNonedicom">
    <span slot="title">{{ title }}</span>
    <div class="top">
      <span>{{ $t('download:top:title') }}</span>
      <div class="btnBox">
        <el-button type="primary" size="mini" v-if="hasDicom" @click.stop="getIRReadingDownloadStudyInfo('dicom')">
          {{ $t('download:button:downloadDicom') }}
        </el-button>
        <el-button type="primary" size="mini" v-if="hasNonedicom"
          @click.stop="getIRReadingDownloadStudyInfo('noneDicom')">
          {{ $t('download:button:downloadNonedicom') }}
        </el-button>
        <el-button type="primary" size="mini" v-if="hasDicom || hasNonedicom"
          @click.stop="getIRReadingDownloadStudyInfo('all')">
          {{ $t('download:button:downloadAll') }}
        </el-button>
      </div>
    </div>
    <div class="tip">
      <i class="el-icon-warning-outline"></i>
      <div v-html="$t('download:tip:message')"></div>
    </div>
    <!--上传列表@selection-change="handleSelectionChange"-->
    <el-table ref="dicomFilesTable" v-adaptive="{ bottomOffset: 85 }" height="100" :data="list" :loading="loading"
      class="dicomFiles-table" 
      :default-sort="{ prop: 'TaskBlindName', order: 'descending' }">
      <!-- <el-table-column
        type="selection"
        width="55"
        :selectable="handleSelectable"
      /> -->
      <el-table-column type="index" width="40" />
      <!--受试者-->
      <el-table-column :label="$t('download:table:subjectCode')" min-width="130" prop="SubjectCode"
        show-overflow-tooltip />
      <!--任务名称-->
      <el-table-column :label="$t('download:table:taskName')" min-width="130" show-overflow-tooltip prop="TaskBlindName"
        sortable />
      <!--检查类型-->
      <el-table-column :label="$t('download:table:studyType')" min-width="130" show-overflow-tooltip prop="IsDicom"
        sortable>
        <template slot-scope="scope">
          <span>{{ $fd('IsDicom', scope.row.IsDicom) }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('download:table:orginalStudyListNum')" min-width="150" show-overflow-tooltip>
        <template slot-scope="scope">
          <el-button v-if="
            (scope.row.IsDicom &&
              scope.row.DicomStudyList &&
              scope.row.DicomStudyList.length >= 1) ||
            (!scope.row.IsDicom &&
              scope.row.NoneDicomStudyList &&
              scope.row.NoneDicomStudyList.length >= 1)
          " type="text" @click="handleOpenDialog(scope.row)">
            <span>{{
              scope.row.IsDicom
                ? scope.row.DicomStudyList.length
                : scope.row.NoneDicomStudyList.length
            }}</span>
          </el-button>
          <span v-else>0</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('common:action:action')" fixed="right" width="150">
        <template slot-scope="scope">
          <!--预览--->
          <el-button circle icon="el-icon-view" :title="$t('download:button:preview')"
            @click.stop="preview(scope.row)" />
          <!--下载--->
          <el-button circle icon="el-icon-download" :title="$t('download:button:download')"
            @click.stop="getIRReadingDownloadStudyInfo('one', scope.row)" />
        </template>
      </el-table-column>
    </el-table>
    <study-view v-if="model_cfg.visible" :model_cfg="model_cfg" :modelList="modelList" :bodyPart="bodyPart"
      :IsDicom="IsDicom" :visitTaskId="modelTaskId" />
  </el-dialog>
</template>
<script>
import {
  getSubjectImageDownloadSelectList,
  getIRReadingDownloadStudyInfo,
  downloadImageSuccess,
} from '@/api/load.js'
import studyView from '@/components/uploadDicomAndNonedicom/study-view.vue'
import store from '@/store'
import { downLoadFile } from '@/utils/stream.js'
import { getToken } from '@/utils/auth'
let defaultSearchData = () => {
  return {
    SubjectId: null,
    TrialReadingCriterionId: null,
    SubjectCode: null,
    Asc: false,
    SortField: 'TaskBlindName',
  }
}
export default {
  name: 'downloadDicomAndNonedicom',
  components: {
    'study-view': studyView,
  },
  props: {
    visible: {
      required: true,
      type: Boolean,
      default: false,
    },
    SubjectId: {
      type: String,
      default: '',
    },
    TaskId: {
      type: String,
      default: '',
    },
    SubjectCode: {
      type: String,
      default: '',
    },
    Criterion: {
      type: Object,
      default: () => {
        return {}
      },
    },
  },
  data() {
    return {
      title: null,
      loading: false,
      list: [],
      searchData: defaultSearchData(),
      btnLoading: false,
      hasDicom: false,
      hasNonedicom: false,
      // 检查数弹框
      model_cfg: {
        visible: false,
        showClose: true,
        width: '1000px',
        title: '',
        appendToBody: true,
      },
      modelList: [],
      IsDicom: true,
      open: null,
      downloadId: null,
      IsReadingTaskViewInOrder: 0, // 阅片规则
      bodyPart: [],
      modelTaskId: null,
    }
  },
  async mounted() {
    this.getList()
    this.bodyPart = await this.$getBodyPart(this.$route.query.trialId)
    this.title = `Download Images：${this.SubjectCode}（${this.Criterion.TrialReadingCriterionName}）`
  },
  beforeDestroy() {
    store.dispatch('trials/setUnLock', false)
  },
  methods: {
    beforeClose() {
      this.$emit('update:visible', false)
    },
    // 获取列表
    async getList() {
      try {
        this.searchData.SubjectId = this.SubjectId
        this.searchData.TrialReadingCriterionId =
          this.Criterion.TrialReadingCriterionId
        this.searchData.SubjectCode = this.SubjectCode
        if (this.TaskId) {
          this.searchData.VisitTaskId = this.TaskId
        }
        this.loading = true
        let res = await getSubjectImageDownloadSelectList(this.searchData)
        this.loading = false
        if (res.IsSuccess) {
          this.list = res.Result
          this.hasDicom = this.list.some((item) => item.IsDicom)
          this.hasNonedicom = this.list.some((item) => !item.IsDicom)
        }
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    // 获取下载文件信息
    async getIRReadingDownloadStudyInfo(type, row) {
      try {
        let data = {
          SubjectId: this.SubjectId || this.list[0].SubjectId,
          TrialReadingCriterionId: this.Criterion.TrialReadingCriterionId,
          SubjectCode: this.SubjectCode || this.list[0].SubjectCode,
          SubjectVisitTaskList: [],
          DicomStudyIdList: [],
          NoneDicomStudyIdList: [],
        }
        if (type === 'dicom' || type === 'all') {
          this.list.forEach((item) => {
            if (
              item.IsDicom &&
              item.DicomStudyList &&
              item.DicomStudyList.length > 0
            ) {
              data.SubjectVisitTaskList.push({
                SubjectvisitId: item.SourceSubjectVisitId,
                TaskId: item.VisitTaskId,
              })
              let arr = item.DicomStudyList.map((d) => d.Id)
              data.DicomStudyIdList = [...data.DicomStudyIdList, ...arr]
            }
          })
        }
        if (type === 'noneDicom' || type === 'all') {
          this.list.forEach((item) => {
            if (
              !item.IsDicom &&
              item.NoneDicomStudyList &&
              item.NoneDicomStudyList.length > 0
            ) {
              data.SubjectVisitTaskList.push({
                SubjectvisitId: item.SourceSubjectVisitId,
                TaskId: item.VisitTaskId,
              })
              let arr = item.NoneDicomStudyList.map((d) => d.Id)
              data.NoneDicomStudyIdList = [...data.NoneDicomStudyIdList, ...arr]
            }
          })
        }
        if (type === 'one') {
          if (
            row.IsDicom &&
            row.DicomStudyList &&
            row.DicomStudyList.length > 0
          ) {
            data.SubjectVisitTaskList.push({
              SubjectvisitId: row.SourceSubjectVisitId,
              TaskId: row.VisitTaskId,
            })
            let arr = row.DicomStudyList.map((d) => d.Id)
            data.DicomStudyIdList = [...data.DicomStudyIdList, ...arr]
          }
          if (
            !row.IsDicom &&
            row.NoneDicomStudyList &&
            row.NoneDicomStudyList.length > 0
          ) {
            data.SubjectVisitTaskList.push({
              SubjectvisitId: row.SourceSubjectVisitId,
              TaskId: row.VisitTaskId,
            })
            let arr = row.NoneDicomStudyList.map((d) => d.Id)
            data.NoneDicomStudyIdList = [...data.NoneDicomStudyIdList, ...arr]
          }
        }
        this.btnLoading = true
        let res = await getIRReadingDownloadStudyInfo(data)
        this.btnLoading = false
        if (res.IsSuccess) {
          this.downloadId = res.OtherInfo.PreDownloadId
          this.IsReadingTaskViewInOrder = res.OtherInfo.IsReadingTaskViewInOrder
          this.downloadImage(res.Result)
        }
      } catch (err) {
        this.btnLoading = false
        console.log(err)
      }
    },
    // 打包下载
    async downloadImage(data) {
      try {
        let { files, name, fileType } = this.formatDownloadFile(data)
        let res = await downLoadFile(files, name, 'zip')
        if (res && this.downloadId) {
          this.downloadImageSuccess()
        }
      } catch (err) {
        console.log(err)
      }
    },
    // 格式化下载文件路径
    formatDownloadFile(list) {
      let files = [],
        name = `${list[0].SubjectCode}_${new Date().getTime()}.zip`
      if (this.IsReadingTaskViewInOrder === 1) {
        name = `${list[0].SubjectCode}_${list[0].TaskBlindName}.zip`
      }
      if (this.IsReadingTaskViewInOrder === 0) {
        // name = `${list[0].TaskBlindName}.zip`
        name = `${list[0].SubjectCode}_${list[0].TaskBlindName}.zip`
      }
      list.forEach((data) => {
        if (data.StudyList && data.StudyList.length > 0) {
          let StudyList = data.StudyList
          StudyList.forEach((study) => {
            if (study.SeriesList.length > 0) {
              study.SeriesList.forEach((series) => {
                if (series.InstancePathList.length > 0) {
                  series.InstancePathList.forEach((instance) => {
                    let fileName = instance.Path.split('/').pop()
                    let obj = {
                      name: `${data.SubjectCode}/${data.TaskBlindName
                        }/${this.$fd('IsDicom', true)}/${study.StudyCode
                        }/${fileName}`,
                      url: this.OSSclientConfig.basePath + instance.Path,
                    }
                    if (this.IsReadingTaskViewInOrder === 0) {
                      obj = {
                        name: `${data.TaskBlindName}/${this.$fd(
                          'IsDicom',
                          true
                        )}/${fileName}`,
                        url: this.OSSclientConfig.basePath + instance.Path,
                      }
                    }
                    files.push(obj)
                  })
                }
              })
            }
          })
        }
        if (data.NoneDicomStudyList && data.NoneDicomStudyList.length > 0) {
          let NoneDicomStudyList = data.NoneDicomStudyList
          // 多文件
          NoneDicomStudyList.forEach((study) => {
            if (study.FileList.length > 0) {
              study.FileList.forEach((item) => {
                let obj = {
                  name: `${data.SubjectCode}/${data.TaskBlindName}/${this.$fd(
                    'IsDicom',
                    false
                  )}/${study.StudyCode}/${item.FileName}`,
                  url: this.OSSclientConfig.basePath + item.Path,
                }
                if (this.IsReadingTaskViewInOrder === 0) {
                  obj = {
                    name: `${data.TaskBlindName}/${this.$fd(
                      'IsDicom',
                      false
                    )}/${item.FileName}`,
                    url: this.OSSclientConfig.basePath + item.Path,
                  }
                }
                files.push(obj)
              })
            }
          })
        }
      })
      return { files, name }
    },
    // 影像下载成功确认
    async downloadImageSuccess() {
      try {
        let params = {
          TrialImageDownloadId: this.downloadId,
        }
        await downloadImageSuccess(params)
      } catch (err) {
        console.log(err)
      }
    },
    handleOpenDialog(item) {
      this.model_cfg.title = `${item.SubjectCode || ''} > ${item.TaskBlindName}`
      if (item.IsDicom) {
        this.modelList = item.DicomStudyList
      } else {
        this.modelList = item.NoneDicomStudyList
        this.modelList.forEach((data) => {
          data.SourceSubjectVisitId = item.SourceSubjectVisitId
        })
      }
      this.modelTaskId = item.VisitTaskId
      this.IsDicom = item.IsDicom
      this.model_cfg.visible = true
    },
    // 排序
    handleSortByColumn(column) {
      if (column.order === 'ascending') {
        this.searchData.Asc = true
      } else {
        this.searchData.Asc = false
      }
      this.searchData.SortField = column.prop
      this.searchData.PageIndex = 1
      this.getList()
    },
    preview(row) {
      if (!row.IsDicom) {
        this.handlePreviewNoneDicomFiles(row)
      } else {
        this.handleViewReadingImages(row)
      }
    },
    // 预览单个检查下非Dicom文件
    handlePreviewNoneDicomFiles(row) {
      if (this.open) {
        this.open.close()
      }
      let trialId = this.$route.query.trialId
      var token = getToken()
      const routeData = this.$router.resolve({
        path: `/showNoneDicoms?trialId=${trialId}&subjectVisitId=${row.SourceSubjectVisitId}&TokenKey=${token}&isReading=true`,
      })
      this.open = window.open(routeData.href, '_blank')
    },
    // 预览阅片影像
    handleViewReadingImages(row) {
      if (this.open) {
        this.open.close()
      }
      var token = getToken()
      let trialId = this.$route.query.trialId
      const routeData = this.$router.resolve({
        path: `/showvisitdicoms?page=download&trialId=${trialId}&visitTaskId=${row.VisitTaskId}&subjectVisitId=${row.SourceSubjectVisitId}&isReading=1&TokenKey=${token}`,
      })
      this.open = window.open(routeData.href, '_blank')
    },
  },
}
</script>
<style lang="scss" scoped>
.top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 10px 0;
}

.tip {
  display: flex;
  align-items: flex-start;
  margin-top: 5px;

  i {
    margin: 3px 5px 0 0;
  }
}
</style>