<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" @sort-change="handleSortByColumn"-->
    <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 v-if="isReadingTaskViewInOrder !== 0" />
      <!--访视名称-->
      <el-table-column prop="VisitName" :label="$t('download:table:VisitName')" sortable v-if="IsImageSegment" />
      <!--任务名称-->
      <el-table-column :label="$t('download:table:taskName')" min-width="130" show-overflow-tooltip prop="TaskBlindName"
        sortable v-else />
      <!--检查类型-->
      <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')" :disabled="forbid"
            @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"
      :subjectVisitId="modelSubjectVisitId" :IsDicom="IsDicom" :isDownload="true" :visitTaskId="modelTaskId"
      :IsImageSegment="IsImageSegment" :Criterion="Criterion" :IsReadingTaskViewInOrder="isReadingTaskViewInOrder" />
  </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,
    },
    forbid: {
      type: Boolean,
      default: false,
    },
    SubjectId: {
      type: String,
      default: '',
    },
    TaskId: {
      type: String,
      default: '',
    },
    SubjectCode: {
      type: String,
      default: '',
    },
    Criterion: {
      type: Object,
      default: () => {
        return {}
      },
    },
    IsImageSegment: {
      type: Boolean,
      default: false,
    },
    isReadingTaskViewInOrder: {
      type: Number,
      default: 2,
    },
    isReading: {
      type: Boolean,
      default: false,
    }
  },
  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,
      modelSubjectVisitId: null,
    }
  },
  async mounted() {
    this.bodyPart.Bodypart = await this.$getBodyPart(this.$route.query.trialId)
    this.getList()
    this.title = `Download Images：${this.SubjectCode}（${this.Criterion.TrialReadingCriterionName}）`
    if (this.IsImageSegment) this.title = `Download Images：${this.SubjectCode}`
    if (this.isReadingTaskViewInOrder === 0) this.title = ''
  },
  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
        }
        if (this.IsImageSegment) {
          this.searchData.IsImageSegmentLabel = true
        }
        else if (this.Criterion.CriterionType == 19 || this.Criterion.CriterionType == 20) {
          this.searchData.IsImageSegmentLabel = false
        }
        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]
          }
        }
        if (this.IsImageSegment) {
          data.IsImageSegmentLabel = true
        }
        else if (this.Criterion.CriterionType == 19 || this.Criterion.CriterionType == 20) {
          data.IsImageSegmentLabel = false
        }
        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.IsImageSegment) {
        name = `${list[0].SubjectCode}.zip`
      } else {
        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) => {
            let arr = []
            study.SeriesList.forEach(item => {
              if (!arr.includes(item.Modality)) {
                arr.push(item.Modality)
              }
            })
            let str = arr.join('_')
            let time = study.StudyTime.split(' ')[0]
            if (study.StudyDIRPath) {
              let obj = {
                name: `${data.SubjectCode}/${data.TaskBlindName
                  }/${this.$fd('IsDicom', true)}/${study.StudyCode
                  }/DICOMDIR`,
                url: this.OSSclientConfig.basePath + study.StudyDIRPath,
              }
              if (this.IsImageSegment) {
                obj = {
                  name: `${data.SubjectCode}/${data.VisitName
                    }/${this.$fd('IsDicom', true)}/${study.StudyCode
                    }_${time}_${str}/DICOMDIR`,
                  url: this.OSSclientConfig.basePath + study.StudyDIRPath,
                }
              } else if (this.IsReadingTaskViewInOrder === 0) {
                obj = {
                  name: `${data.TaskBlindName}/${this.$fd(
                    'IsDicom',
                    true
                  )}/DICOMDIR`,
                  url: this.OSSclientConfig.basePath + study.StudyDIRPath,
                }
              }
              files.push(obj)
            }
            if (study.SeriesList.length > 0) {
              study.SeriesList.forEach((series) => {
                if (series.InstanceList.length > 0) {
                  series.InstanceList.forEach((instance) => {
                    let fileName = instance.Path.split('/').pop()
                    if (instance.FileName) {
                      fileName = instance.FileName
                    }
                    let obj = {
                      name: `${data.SubjectCode}/${data.TaskBlindName
                        }/${this.$fd('IsDicom', true)}/${study.StudyCode
                        }/IMAGE/${fileName}`,
                      url: this.OSSclientConfig.basePath + instance.Path,
                      IsEncapsulated: instance.IsEncapsulated
                    }
                    if (this.IsImageSegment) {
                      obj = {
                        name: `${data.SubjectCode}/${data.VisitName
                          }/${this.$fd('IsDicom', true)}/${study.StudyCode
                          }_${time}_${str}/IMAGE/${fileName}`,
                        url: this.OSSclientConfig.basePath + instance.Path,
                        IsEncapsulated: instance.IsEncapsulated
                      }
                    } else if (this.IsReadingTaskViewInOrder === 0) {
                      obj = {
                        name: `${data.TaskBlindName}/${this.$fd(
                          'IsDicom',
                          true
                        )}/IMAGE/${fileName}`,
                        url: this.OSSclientConfig.basePath + instance.Path,
                        IsEncapsulated: instance.IsEncapsulated
                      }
                    }
                    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.IsImageSegment) {
                  obj = {
                    name: `${data.SubjectCode}/${data.VisitName}/${this.$fd(
                      'IsDicom',
                      false
                    )}/${study.StudyCode}/${item.FileName}`,
                    url: this.OSSclientConfig.basePath + item.Path,
                  }
                }
                else 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,
        }
        if (this.isReading) {
          params.VisitTaskId = this.TaskId
        }
        await downloadImageSuccess(params)
      } catch (err) {
        console.log(err)
      }
    },
    handleOpenDialog(item) {
      this.model_cfg.title = `${item.SubjectCode || ''} > ${item.TaskBlindName}`
      if (this.IsImageSegment) {
        this.model_cfg.title = `${item.SubjectCode || ''} > ${item.VisitName}`
      }
      if (this.isReadingTaskViewInOrder === 0) {
        this.model_cfg.title = ''
      }
      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.modelSubjectVisitId = item.SourceSubjectVisitId
      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()
      let routeData = null
      if (!this.IsImageSegment && (this.Criterion.CriterionType == 19 || this.Criterion.CriterionType == 20)) {
        routeData = this.$router.resolve({
          path: `/showNoneDicoms?trialId=${trialId}&isImageSegmentLabel=${false}&visitTaskId=${row.VisitTaskId}&subjectVisitId=${row.SourceSubjectVisitId}&TokenKey=${token}&isReading=true&IsReadingTaskViewInOrder=${this.isReadingTaskViewInOrder}`,
        })
      } else {
        routeData = this.$router.resolve({
          path: `/showNoneDicoms?trialId=${trialId}&visitTaskId=${row.VisitTaskId}&subjectVisitId=${row.SourceSubjectVisitId}&TokenKey=${token}&isReading=true&IsReadingTaskViewInOrder=${this.isReadingTaskViewInOrder}`,
        })
      }
      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}&IsReadingTaskViewInOrder=${this.isReadingTaskViewInOrder}`,
      })
      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>