<template>
  <div>
    <el-input v-model="input" placeholder="" clearable></el-input>
    <el-input v-model="pageIndex" placeholder="" clearable></el-input>
    <el-input v-model="pageSize" placeholder="" clearable></el-input>
    <el-button type="primary" size="small" :disabled="!input" @click.stop="getTrialUnreadVisitList">下载</el-button>
  </div>
</template>

<script>
import { downLoadFile } from '@/utils/stream.js'
import { getTrialUnreadVisitList, getExportSubjectVisitImageList } from '@/api/trials'
export default {
  // components: {
  //   GridLayout,
  // },
  data() {
    return {
      input: '08deab4a-f842-a7a4-0242-0a0001000000',
      pageIndex: 1,
      pageSize: 250
    };
  },
  methods: {
    async getTrialUnreadVisitList() {
      let params = {
        TrialId: this.input,
        PageIndex: this.pageIndex,
        PageSize: this.pageSize,
      }
      let res = await getTrialUnreadVisitList(params)
      if (res.IsSuccess) {
        let arr = res.Result
        this.LoopDownload(arr, 0)
      }
    },
    async LoopDownload(arr, index) {
      if (index >= arr.length) return false
      let res = await this.handleExportImage(false, true, arr[index])
      console.log(res, arr[index], 'res')
      index++
      this.LoopDownload(arr, index)
    },
    async handleExportImage(IsKeyImage = false, IsExportReading = false, SubjectVisitId) {
      try {
        let data = {
          TrialId: this.input,
          IsKeyImage,
          IsExportReading
        }
        data.SubjectVisitIdList = [SubjectVisitId]
        // if (!IsKeyImage) {
        //   let confirm = await this.$confirm(this.$t('trials:imageSummary:confirm:space').replace('xxx', this.image_size.CheckImageSize))
        //   if (!confirm) return false
        // }
        let res = await getExportSubjectVisitImageList(data)
        if (res.IsSuccess) {
          return this.downLoad(IsKeyImage, res.Result, IsExportReading)
        }
        return false
      } catch (err) {
        return false
        console.log(err)
      }
    },
    // 下载
    async downLoad(IsKeyImage = false, row, IsExportReading = false) {
      try {
        let { files, name } = this.formatDownloadFile(IsKeyImage, row, IsExportReading)
        return await downLoadFile(files, name, 'zip')
        // }
      } catch (err) {
        return false
        console.log(err)
      }
    },
    // 格式化下载文件路径
    formatDownloadFile(IsKeyImage = false, row, IsExportReading = false) {
      let files = [],
        name = `${this.$route.query.researchProgramNo}_${this.$t('trials:imageSummary:downloadname:dicom')}_${Date.now()}.zip`;
      if (IsExportReading) {
        name = `${row.VisitList[0].SubjectCode}_${row.VisitList[0].VisitName}.zip`;
      }
      if (!IsKeyImage) {
        //中心ID/受试者ID/访视名/Study ID_Study Date_Modality/文件  
        row.VisitList.forEach(visit => {
          if (visit.StudyList && visit.StudyList.length > 0) {
            visit.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 && !study.dirHas) {
                study.dirHas = true
                let obj = {
                  name: `${study.StudyCode}_${time}_${str}/DICOMDIR`,
                  url: this.OSSclientConfig.basePath + study.StudyDIRPath,
                }
                files.push(obj)
              }
              if (study.SeriesList && study.SeriesList.length > 0) {
                study.SeriesList.forEach(serie => {

                  if (serie.InstanceList && serie.InstanceList.length > 0) {
                    serie.InstanceList.forEach(instance => {
                      let instanceArr = instance.Path.split("/")
                      let fileName = instance.FileName || instanceArr[instanceArr.length - 1]
                      let obj = {
                        name: `${study.StudyCode}_${time}_${str}/IMAGE/${fileName}`,
                        url: this.OSSclientConfig.basePath + instance.Path,
                        IsEncapsulated: instance.IsEncapsulated
                      }
                      files.push(obj)
                    })
                  }
                })
              }
            })
          }
          if (visit.NoneDicomStudyList && visit.NoneDicomStudyList.length > 0) {
            visit.NoneDicomStudyList.forEach(noneDicomStudy => {
              if (noneDicomStudy.FileList && noneDicomStudy.FileList.length > 0) {
                noneDicomStudy.FileList.forEach(file => {
                  let time = noneDicomStudy.ImageDate.split(' ')[0]
                  let obj = {
                    name: `${noneDicomStudy.StudyCode}_${time}_${noneDicomStudy.Modality}/${file.FileName}`,
                    url: this.OSSclientConfig.basePath + file.Path,
                  }
                  files.push(obj)
                })
              }
            })
          }
        })
      }

      return { files, name }
    },
  }
};
</script>