<template>
  <el-dialog
    :visible.sync="visible"
    :fullscreen="true"
    :close-on-click-modal="false"
    :before-close="beforeClose"
    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"
          :loading="btnLoading"
          v-if="hasDicom"
          @click.stop="getIRReadingDownloadStudyInfo('dicom')"
        >
          {{ $t('download:button:downloadDicom') }}
        </el-button>
        <el-button
          type="primary"
          size="mini"
          :loading="btnLoading"
          v-if="hasNonedicom"
          @click.stop="getIRReadingDownloadStudyInfo('noneDicom')"
        >
          {{ $t('download:button:downloadNonedicom') }}
        </el-button>
        <el-button
          type="primary"
          size="mini"
          :loading="btnLoading"
          @click.stop="getIRReadingDownloadStudyInfo('all')"
        >
          {{ $t('download:button:downloadAll') }}
        </el-button>
      </div>
    </div>
    <!--上传列表@selection-change="handleSelectionChange"-->
    <el-table
      ref="dicomFilesTable"
      v-adaptive="{ bottomOffset: 85 }"
      height="100"
      :data="list"
      :loading="loading"
      class="dicomFiles-table"
      @sort-change="handleSortByColumn"
      :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="custom"
      />
      <!--检查类型-->
      <el-table-column
        :label="$t('download:table:studyType')"
        min-width="130"
        show-overflow-tooltip
        prop="IsDicom"
        sortable="custom"
      >
        <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"
      :IsDicom="IsDicom"
    />
  </el-dialog>
</template>
<script>
import {
  getSubjectImageDownloadSelectList,
  getIRReadingDownloadStudyInfo,
} from '@/api/load.js'
import studyView from '@/components/uploadDicomAndNonedicom/study-view.vue'
import store from '@/store'
import { downLoadFile } from '@/utils/stream.js'
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: '',
    },
    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,
    }
  },
  mounted() {
    this.getList()
    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
        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,
          TrialReadingCriterionId: this.Criterion.TrialReadingCriterionId,
          SubjectCode: this.SubjectCode,
          SubjectVisitIdList: [],
          DicomStudyIdList: [],
          NoneDicomStudyIdList: [],
        }
        if (type === 'dicom' || type === 'all') {
          this.list.forEach((item) => {
            if (
              item.IsDicom &&
              item.DicomStudyList &&
              item.DicomStudyList.length > 0
            ) {
              data.SubjectVisitIdList.push(item.SourceSubjectVisitId)
              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.SubjectVisitIdList.push(item.SourceSubjectVisitId)
              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.SubjectVisitIdList.push(row.SourceSubjectVisitId)
            let arr = row.DicomStudyList.map((d) => d.Id)
            data.DicomStudyIdList = [...data.DicomStudyIdList, ...arr]
          }
          if (
            !row.IsDicom &&
            row.NoneDicomStudyList &&
            row.NoneDicomStudyList.length > 0
          ) {
            data.SubjectVisitIdList.push(row.SourceSubjectVisitId)
            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.downloadImage(res.Result)
        }
      } catch (err) {
        this.btnLoading = false
        console.log(err)
      }
    },
    // 打包下载
    async downloadImage(data) {
      try {
        let { files, name, fileType } = this.formatDownloadFile(data)
        await downLoadFile(files, name, 'zip')
      } catch (err) {
        console.log(err)
      }
    },
    // 格式化下载文件路径
    formatDownloadFile(data) {
      let files = [],
        name = `${data.SubjectCode}_${data.VisitName}.zip`
      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.VisitName}/${this.$fd(
                      'IsDicom',
                      true
                    )}/${study.StudyCode}/${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.VisitName}/${this.$fd(
                  'IsDicom',
                  false
                )}/${study.StudyCode}/${item.FileName}`,
                url: this.OSSclientConfig.basePath + item.Path,
              }
              files.push(obj)
            })
          }
        })
      }
      return { files, name }
    },
    handleOpenDialog(item) {
      this.model_cfg.title = `${item.SubejctCode || ''}>${item.TaskBlindName}`
      if (item.IsDicom) {
        this.modelList = item.DicomStudyList
      } else {
        this.modelList = item.NoneDicomStudyList
      }
      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()
    },
  },
}
</script>
<style lang="scss" scoped>
.top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 10px 0;
}
</style>