<template>
  <div class="education-info">
    <div class="btn-wrapper">
      <el-button style="margin-left:auto" size="small" :disabled="checkID.length==0" @click="downloadAttachement">{{$t('resumeInfo:button:Download')}}</el-button>
    </div>
    <el-table
      :data="tblList"
      :span-method="objectSpanMethod"
      size="small"
      @selection-change="selectMore"
    >
      <template slot="empty">
        <span></span>
      </template>
      <el-table-column type="selection" align="left" width="50" />
      <el-table-column type="index"  :label="$t('resumeInfo:label:No')" width="50" />
      <el-table-column prop="Type" :label="$t('resumeInfo:label:Type')" min-width="50" show-overflow-tooltip />
      <el-table-column
        prop="FileName"
        :label="$t('resumeInfo:label:FileName')"
        min-width="80"
        show-overflow-tooltip
      />
      <el-table-column
        prop="CreateTime"
        :label="$t('resumeInfo:label:CreateTime')"
        min-width="50"
        show-overflow-tooltip
      />
      <el-table-column :label="$t('common:action:action')" min-width="150">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="preview(scope.$index, scope.row)">{{$t('resumeInfo:button:view')}}</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
import { getDoctorAttachment } from '@/api/reviewers'
import axios from "axios";
import JSZip from "jszip";
import { saveAs } from 'file-saver'
export default {
  props: {
    attachmentList: {
      type: Array,
      default() {
        return []
      }
    },
    doctorId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      tblList: [],
      checkID: [],
      spanArr: [],
      pos: 0
    }
  },
  created() {
    this.tblList = this.filterListByType(this.attachmentList)
    this.getSpanArr(this.tblList)
  },
  methods: {
    filterListByType(arr) {
      var list = []
      if (arr.length > 0) {
        arr.forEach(item => {
          if (item.Type === 'Diploma of the highest medical degree') {
            list.push(item)
          }
        })
        arr.forEach(item => {
          if (item.Type === 'Medical Qualification Certificate') {
            list.push(item)
          }
        })
        arr.forEach(item => {
          if (item.Type === 'Practice License') {
            list.push(item)
          }
        })
        arr.forEach(item => {
          if (item.Type === 'Modality Certificate(CT)') {
            list.push(item)
          }
        })
        arr.forEach(item => {
          if (item.Type === 'Modality Certificate(MRI)') {
            list.push(item)
          }
        })
        arr.forEach(item => {
          if (item.Type === 'Modality Certificate(NM)') {
            list.push(item)
          }
        })
        arr.forEach(item => {
          if (item.Type === 'Modality Certificate(US)') {
            list.push(item)
          }
        })
      }
      return list
    },
    getFileData(fileUrl) {
      return new Promise((resolve, reject) => {
        axios(fileUrl, {
          method: 'GET',
          responseType: 'blob'  // 返回的数据会被强制转为blob类型 ，转换成arraybuffer 也行
        }).then((res) => {
          console.log('res', res)
          resolve(res)
        }).catch(error => {
          reject(error)
        })
      })
    },
    async handleBatchDown(dataSource) {
      return new Promise(resolve => {
        const zip = new JSZip() // 创建实例对象
        const promises = []
        dataSource.FileList.forEach((item) => {
          console.log(this.OSSclientConfig.basePath + item.Path)
          const promise = this.getFileData(this.OSSclientConfig.basePath + item.Path).then((res) => {
            const fileName = item.FileName + ''
            // 创建文件用file()，创建文件夹用 floder()
            zip.file(fileName, res.data, {binary: true})
          })
          promises.push(promise)
        })
        console.log(promises)
        // 生成 zip 文件
        Promise.all(promises).then(() => {
          // 生成zip 文件
          zip.generateAsync({
            type: 'blob',
            compression: 'DEFLATE',  // STORE: 默认不压缩， DEFLATE：需要压缩
            compressionOptions: {
              level: 9          // 压缩等级 1~9   1 压缩速度最快， 9 最优压缩方式
            }
          }).then((res) => {
            saveAs(res, dataSource.ReviewerCode + '_Credentials.zip') // 使用FileSaver.saveAs保存文件，文件名可自定义
            resolve()
          })
        }).catch(reason => {
          resolve()
        })
      })
    },
    downloadAttachement() {
      getDoctorAttachment({
        DoctorId: this.doctorId,
        AttachmentIdList: this.checkID
      }).then(res => {
        this.handleBatchDown(res.Result)
      })
    },
    preview(index, row) {
      const filePath = row.FullPath
      if (filePath) {
        window.open(this.OSSclientConfig.basePath + filePath, '_blank')
      }
    },
    selectMore(val) {
      const arr = []
      for (let index = 0; index < val.length; index++) {
        arr.push(val[index].Id)
      }
      this.checkID = arr
    },
    getSpanArr(data) {
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1)
          this.pos = 0
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].Type === data[i - 1].Type) {
            this.spanArr[this.pos] += 1
            this.spanArr.push(0)
          } else {
            this.spanArr.push(1)
            this.pos = i
          }
        }
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 2) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      } else if (columnIndex === 3) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      } else if (columnIndex === 4) {
        const _row = this.spanArr[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    },
    timeFormatter(row) {
      return new Date(row.UpdateTime).format('yyyy-MM-dd hh:mm:ss')
    }
  }
}
</script>

<style lang="scss">
.education-info{
  padding:5px 15px;
  font-size:13px;
  .btn-wrapper{
    display: flex;
    align-items: center;
  }
}
</style>
