<template>
  <div v-loading="loading" class="img-container">
    <el-card class="box-card left">
      <div class="title" style="display: flex;align-items: center;">
        <div style="margin-right: 5px;cursor: pointer;" @click.stop="sortFile">
          <i :class="['el-icon-caret-top', Asc === false || Asc === null ? '' : 'icon_check']"
            style="display: block;margin-bottom: -5px;"></i>
          <i :class="['el-icon-caret-bottom', Asc === true || Asc === null ? '' : 'icon_check']"
            style="display: block; margin-top: -5px;"></i>
        </div>
        {{ $t('trials:none-dicom-show:fileList') }}
      </div>
      <div class="left-content">
        <!-- 检查层级 -->
        <el-collapse v-model="activeNames" @change="handleChange">
          <el-collapse-item v-for="(study, i) in studyList" :key="study.CodeView" :name="study.CodeView"><template
              slot="title">
              <div class="study-desc">
                <span>{{ study.CodeView }}</span>
                <span v-if="OtherInfo.IsShowStudyName" style="margin-left: 5px">
                  {{ study.StudyName }}
                </span>
                <span style="margin: 0 5px">{{ study.Modality }}</span>
                <span>{{ getBodyPart(study.BodyPart, study.BodyPartForEditOther) }}</span>
              </div>
            </template>
            <!-- 文件层级 -->
            <div v-if="study.NoneDicomStudyFileList.length === 0" class="empty-text">
              <slot name="empty">{{ $t('trials:audit:message:noData') }}</slot>
            </div>
            <div v-else id="imgList" style="height: 100%; overflow: hidden">
              <template v-for="(item, j) in study.NoneDicomStudyFileList">
                <div :id="`img${item.Id}`" :key="item.Id" :class="{
                  'is-boxActive': item.Id === currentFileId,
                }" class="img-box" @click="selected(item, i, j, true)">
                  <div class="file-image">
                    <el-image v-if="
                      [
                        'image/jpeg',
                        'image/jpg',
                        'image/png',
                        'image/bmp',
                      ].includes(item.FileType)
                    " style="width: 100%; height: 100%"
                      :src="`${OSSclientConfig.basePath}${item.Path}?x-oss-process=image/resize,w_50,h_50/format,png`"
                      fit="contain" crossorigin="anonymous" />
                    <el-image v-else-if="item.FileType === 'application/pdf'" style="width: 100%; height: 100%"
                      :src="pdf" fit="contain" crossorigin="anonymous" />
                    <el-image v-else-if="
                      item.FileType === 'application/x-zip-compressed'
                    " style="width: 100%; height: 100%" :src="zip" fit="contain" crossorigin="anonymous" />
                    <el-image v-else-if="
                      !!~item.FileType.indexOf('mp4')
                    " style="width: 100%; height: 100%" :src="mp4" fit="contain" crossorigin="anonymous" />
                  </div>
                  <div v-if="item.FileName.length < 15" class="img-text">
                    {{ `${j + 1}. ${item.FileName}` }}
                  </div>
                  <el-tooltip v-else :content="item.FileName" placement="bottom">
                    <div class="img-text">
                      {{ `${j + 1}. ${item.FileName}` }}
                    </div>
                  </el-tooltip>
                  <div v-if="isQcCheck" class="switchBox">
                    <div class="item">
                      <span>{{ $t('trials:audit:table:isReading') }}</span>
                      <el-switch v-model="item.IsReading" :disabled="item.IsDeleted || isAudit"
                        @change="changeReadingStatus($event, study, item)" :active-text="$fd('YesOrNo', true)"
                        :inactive-text="$fd('YesOrNo', false)" />
                    </div>
                    <div class="item">
                      <span>{{ $t('trials:audit:table:isDelete') }}</span>
                      <el-switch v-model="item.IsDeleted" :disabled="isAudit"
                        @change="changeDeleteStatus($event, study, item)" :active-text="$fd('YesOrNo', true)"
                        :inactive-text="$fd('YesOrNo', false)" />
                    </div>
                  </div>
                </div>
              </template>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
    </el-card>
    <!-- 预览图像 -->
    <el-card class="box-card right">
      <div style="width: 100%; height: 100%" v-if="!showPDF">
        <Preview v-if="previewImage.imgList.length > 0" ref="previewImage" style="width: 100%"
          :preview-image="previewImage" :value="currentStudyFileIndex" @selectedImg="selectedImg"
          :currentFileId="currentFileId" />
      </div>
      <div style="width: 100%; height: 100%" v-else>
        <PreviewFile :file-path="pdfFile.path" :file-type="pdfFile.type" />
      </div>
    </el-card>

    <!-- <el-card class="box-card" style="width:300px;height:100%;padding: 10px;margin-left:10px;">
      <CheckForm />
    </el-card> -->
  </div>
</template>

<script>
import { getNoneDicomStudyList, setNodicomStudyState } from '@/api/trials'
import store from '@/store'
import pdf from '@/assets/pdf.png'
import zip from '@/assets/zip.jpg'
import mp4 from '@/assets/mp4.png'
import { changeURLStatic } from '@/utils/history.js'
import Preview from './components/preview'
import PreviewFile from '@/components/PreviewFile'
import FileNameSorter from "@/utils/customSort";
// import CheckForm from './components/form'
export default {
  name: 'Notice',
  components: {
    Preview,
    PreviewFile,
    // CheckForm
  },
  data() {
    return {
      pdf,
      zip,
      mp4,
      activeName: 'first',
      currentFileId: '',
      currentStudyIndex: 0,
      currentStudyFileIndex: 0,
      pageSize: 0, // 一页展示的图片数
      previewImage: {
        imgList: [],
        index: 0, // 当前点击的图片的索引
        infinite: true, // 是否可以循环切换
        popup: true, // 弹窗的显示隐藏
        studyCode: '',
        modality: '',
        bodyPart: '',
      },
      previewVisible: false,
      studyList: [],
      subjectVisitId: '',
      sudyId: '',
      loading: false,
      BodyPart: {},
      OtherInfo: {},
      showPDF: false,
      pdfFile: {
        path: null,
        type: null,
      },
      isQcCheck: false,
      isAudit: false,

      activeNames: [],
      Asc: false,
      IsReadingTaskViewInOrder: 2
    }
  },
  async created() {
    this.BodyPart.Bodypart = await this.$getBodyPart(this.$route.query.trialId)
    this.isQcCheck = !!this.$route.query.isQcCheck
  },
  async mounted() {
    if (this.$router.currentRoute.query.TokenKey) {
      store.dispatch('user/setToken', this.$router.currentRoute.query.TokenKey)
      changeURLStatic('TokenKey', '')
    }
    if (this.$router.currentRoute.query.IsReadingTaskViewInOrder) {
      this.IsReadingTaskViewInOrder = Number(this.$router.currentRoute.query.IsReadingTaskViewInOrder)
    }
    this.subjectVisitId = this.$router.currentRoute.query.subjectVisitId
    this.studyId = this.$router.currentRoute.query.studyId
    this.getNoneDicomList()
    // 默认选择第一个文件
  },
  computed: {
    CriterionType() {
      return this.OtherInfo.CriterionType ? this.OtherInfo.CriterionType : 0
    }
  },
  methods: {
    sortFile() {
      if (this.Asc) {
        this.Asc = false
      } else {
        this.Asc = true
      }
      console.log(this.Asc, 'this.Asc')
      this.studyList.forEach(study => {
        if (study.NoneDicomStudyFileList.length > 0) {
          study.NoneDicomStudyFileList = FileNameSorter.sortFileNames(study.NoneDicomStudyFileList, {
            direction: this.Asc ? 'asc' : 'desc',
            key: 'FileName'
          })
        }
      })
      this.previewImage.imgList = this.studyList[this.currentStudyIndex].NoneDicomStudyFileList
      this.previewImage.index = this.studyList[this.currentStudyIndex].NoneDicomStudyFileList.findIndex(item => item.Id === this.currentFileId)
    },
    handleChange() { },
    changeReadingStatus(callback, row, file) {
      let statusStr = ''
      if (callback) {
        statusStr = this.$t('trials:audit:label:setSeriesReading')
        file.IsReading = false
      } else {
        statusStr = this.$t('trials:audit:label:setSeriesNotReading')
        file.IsReading = true
      }
      var message = this.$t('trials:audit:message:changeSeriesStatus').replace(
        'xxx',
        statusStr
      )
      message = message.replace('yyy', this.$fd('YesOrNo', !file.IsReading))
      this.$confirm(message, {
        distinguishCancelAndClose: true,
        type: 'warning',
      })
        .then(() => {
          const state = file.IsReading ? 1 : 2
          this.loading = true
          let params = {
            SubjectVisitId: row.SubjectVisitId,
            NoneDicomStudyId: row.Id,
            State: state,
            NoneDicomStudyFileId: file.Id,
          }
          return setNodicomStudyState(params)
            .then((res) => {
              this.loading = false
              if (res.IsSuccess) {
                this.$message.success(
                  this.$t('common:message:savedSuccessfully')
                )
                file.IsReading = !file.IsReading
                // this.getNoneDicomList()
              }
            })
            .catch(() => {
              this.loading = false
            })
        })
        .catch(() => { })
    },
    changeDeleteStatus(callback, row, file) {
      let statusStr = ''
      if (callback) {
        statusStr = this.$t('trials:audit:label:setSeriesDeleted')
        file.IsDeleted = false
      } else {
        statusStr = this.$t('trials:audit:label:setSeriesNotDelete')
        file.IsDeleted = true
      }
      var message = this.$t('trials:audit:message:changeSeriesStatus').replace(
        'xxx',
        statusStr
      )
      message = message.replace('yyy', this.$fd('YesOrNo', !file.IsDeleted))
      this.$confirm(message, {
        distinguishCancelAndClose: true,
        type: 'warning',
      })
        .then(() => {
          const state = file.IsDeleted ? 5 : 4
          this.loading = true

          let params = {
            SubjectVisitId: row.SubjectVisitId,
            NoneDicomStudyId: row.Id,
            State: state,
            NoneDicomStudyFileId: file.Id,
          }
          return setNodicomStudyState(params)
            .then((res) => {
              this.loading = false
              if (res.IsSuccess) {
                this.$message.success(
                  this.$t('common:message:savedSuccessfully')
                )
                file.IsDeleted = !file.IsDeleted
                // this.getNoneDicomList()
              }
            })
            .catch(() => {
              // file.IsDeleted = !file.IsDeleted
              this.loading = false
            })
        })
        .catch(() => {
          // file.IsDeleted = !file.IsDeleted
        })
    },
    getBodyPart(bodyPart, other) {
      if (!bodyPart && !other) return ''
      var separator = ','
      if (bodyPart.indexOf('|') > -1) {
        separator = '|'
      } else if (bodyPart.indexOf(',') > -1) {
        separator = ','
      } else if (bodyPart.indexOf('，') > -1) {
        separator = '，'
      }
      var arr = bodyPart.split(separator)
      var newArr = arr.map((i) => {
        return this.$fd('Bodypart', i.trim(), 'Code', this.BodyPart, 'Name')
      })
      if (other) {
        newArr.push(other)
      }
      newArr = newArr.filter(Boolean)
      return newArr.join(' | ')
    },
    // 获取非Dicom检查信息
    getNoneDicomList() {
      this.loading = true
      getNoneDicomStudyList(
        this.subjectVisitId,
        this.studyId,
        false,
        this.$route.query.visitTaskId,
        !!this.$route.query.isReading,
        this.$route.query.isImageSegmentLabel,
      )
        .then((res) => {
          this.studyList = res.Result
          this.OtherInfo = res.OtherInfo
          this.isAudit = res.OtherInfo.AuditState * 1 > 6
          this.loading = false
          const studyIndex = this.studyList.findIndex((item) => {
            return item.NoneDicomStudyFileList.length > 0
          })
          this.activeNames = this.studyList.map((item) => item.CodeView)
          if (studyIndex > -1) {
            var fileObj = this.studyList[studyIndex]['NoneDicomStudyFileList']
            this.selected(fileObj[0], studyIndex, 0, true)
          }
          if (this.CriterionType === 19 || this.CriterionType === 20) {
            this.sortFile()
          }
        })
        .catch(() => {
          this.loading = false
        })
    },
    selected(file, studyIndex, fileIndex, isChangeSub = false) {
      this.currentFileId = file.Id
      if (!!~file.FileType.indexOf('pdf')) {
        this.pdfFile.path = file.Path || file.FullFilePath
        this.pdfFile.type = 'pdf'
        this.showPDF = true
        return true
      } else if (!!~file.FileType.indexOf('mp4')) {
        this.pdfFile.path = file.Path || file.FullFilePath
        this.pdfFile.type = file.FileType
        this.showPDF = true
        return true
      } else {
        this.showPDF = false
      }
      console.log(this.pdfFile)
      this.currentStudyIndex = studyIndex
      this.previewImage.imgList =
        this.studyList[studyIndex].NoneDicomStudyFileList
      this.currentStudyFileIndex = fileIndex
      this.previewImage.index = fileIndex
      this.previewImage.studyCode = this.studyList[studyIndex].CodeView
      this.previewImage.bodyPart = this.studyList[studyIndex].BodyPart
      this.previewImage.modality = this.studyList[studyIndex].Modality
      this.$nextTick(() => {
        if (isChangeSub) {
          this.$refs['previewImage'].selected(this.currentFileId)
        }
      })
    },
    selectedImg(id) {
      if (this.studyList.length > 0) {
        let fileIndex = this.studyList[this.currentStudyIndex].NoneDicomStudyFileList.findIndex(item => item.Id === id)
        this.currentStudyFileIndex = fileIndex
        this.currentFileId =
          this.studyList[this.currentStudyIndex].NoneDicomStudyFileList[
            fileIndex
          ].Id
        this.previewImage.index = fileIndex
        this.previewImage.studyCode =
          this.studyList[this.currentStudyIndex].CodeView
        this.previewImage.bodyPart =
          this.studyList[this.currentStudyIndex].BodyPart
        this.previewImage.modality =
          this.studyList[this.currentStudyIndex].Modality
        this.$nextTick(() => {
          const target = document.getElementById(`img${this.currentFileId}`)
          const parent = document.getElementsByClassName('left-content')[0]
          parent.scrollTop = target.offsetTop - parent.offsetTop
        })
      }
    },
    preview() {
      this.previewVisible = true
    },
  },
}
</script>

<style lang="scss" scoped>
.icon_check {
  color: #409EFF;
}

.img-container {
  position: relative;
  width: 100%;
  height: 100%;
  padding: 10px;
  display: flex;

  ::-webkit-scrollbar {
    width: 7px;
    height: 7px;
  }

  ::-webkit-scrollbar-thumb {
    border-radius: 10px;
    background: #d0d0d0;
  }

  ::v-deep .el-card__body {
    padding: 0px;
  }
}

.study-desc {
  padding: 10px 5px;
  line-height: 20px;
  background-color: #d5d5d5;
  font-weight: 500;
}

.left {
  width: 220px;
  height: 100%;

  ::v-deep .el-card__body {
    height: 100%;
    width: 100%;
    display: flex;
    flex-direction: column;
  }

  .title {
    height: 40px;
    line-height: 40px;
    border: 1ppx solid;
    border: 1px solid #ebe7e7;
    padding-left: 10px;
    background-color: #4e4e4e;
    color: #ffffff;
  }

  .left-content {
    flex: 1;
    overflow-y: auto;
  }

  // ::v-deep .el-tabs{
  //   height: 100%;
  // }
  // ::v-deep .el-tabs__header{
  //   height: 40px;
  // }
  // ::v-deep .el-tabs__content{
  //   flex: 1;
  //   overflow-y: auto;
  //   padding: 0;
  // }
  .img-box {
    // position: relative;
    display: inline-block;
    box-sizing: border-box;
    border-bottom: 2px solid #f3f3f3;
    display: flex;
    align-items: center;
    flex-wrap: wrap;
    justify-content: flex-start;
    padding: 5px 10px;

    cursor: pointer;
    // margin-bottom: 5px;
    padding-left: 5px;
  }

  .img-text {
    display: inline-block;
    width: calc(100% - 60px);
    margin-left: 5px;
    height: 50px;
    line-height: 50px;
    overflow: hidden;
    text-overflow: ellipsis;
    /* 用省略号表示溢出的文本 */
    white-space: nowrap;
  }

  .img-box:nth-last-child(1) {
    margin-bottom: 0px;
  }

  .is-boxActive {
    // border-color: #409eff;
    color: #409eff;
  }

  .is-boxActiv:after {
    opacity: 0;
  }
}

.right {
  flex: 1;
  height: 100%;
  margin-left: 10px;

  ::v-deep .el-card__body {
    height: 100%;
    width: 100%;
  }
}

.switchBox {
  width: 100%;
  margin: 5px 0;
  color: #4e4e4e;

  .item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 5px;
  }
}

.file-image {
  width: 50px;
  height: 50px;
}

::v-deep .el-collapse-item__header {
  background-color: #d5d5d5;
}

::v-deep .el-collapse-item__header {
  min-height: 48px;
  height: auto;
}

::v-deep .el-collapse-item__content {
  padding-bottom: 0;
}
</style>