<template>
  <div>
    <!-- :wrapper-closable="false" -->
    <el-drawer
      :with-header="false"
      :visible.sync="fileDrawer"
      :modal="false"
      :show-close="false"
      direction="rtl"
      :class="((selectedCategory.arrangeType === 2 && isAjNo === 0) || (selectedCategory.arrangeType === 3 && isAjNo === 1)) ? 'drawer2-modal' : (isAjNo === 1) ? 'drawer1-modal' : (selectedCategory.arrangeType === 1) ? 'drawer1-modal' : 'drawer3-modal'"
      :size="((selectedCategory.arrangeType === 2 && isAjNo === 0) || (selectedCategory.arrangeType === 3 && isAjNo === 1)) ? '80%' : (isAjNo === 1) ? '90%' : (selectedCategory.arrangeType === 1) ? '90%' : '70%'"
    >
      <CollectHeader ref="collectHeaderRef" :is-title-type="isTitleType" :selected-category="selectedCategory" :selections="selections" :test="test" :is-recycle="isRecycle" />
      <span class="closed-btn" @click="closeDrawer" />
      <div class="collect-table">
        <el-table
          ref="table"
          v-loading="crud.loading || getTableDisplayFieldsLoading"
          class="archives-table"
          :data="fileData"
          highlight-current-row
          style="width: 100%;"
          height="calc(100vh - 418px)"
          :row-class-name="tableRowClassName"
          :row-key="rowKey"
          @select-all="selectAll"
          @selection-change="crud.selectionChangeHandler"
          @row-click="clickRowHandler"
          @cell-dblclick="tableDoubleClick"
          @select="handleCurrentChange"
        >
          <el-table-column type="selection" width="55" :reserve-selection="true" align="center" />
          <el-table-column label="序号" width="55" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <span>{{ page.page * page.size + scope.$index + 1 }}</span>
            </template>
          </el-table-column>
          <!-- <el-table-column type="index" label="序号" width="55" align="center" /> -->
          <el-table-column prop="file_name" label="原文名称" show-overflow-tooltip min-width="140" />
          <el-table-column prop="file_type" label="格式" min-width="60" align="center" />
          <el-table-column prop="file_size" label="大小" min-width="80" align="right" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ getFileSize(scope.row.file_size) }}
            </template>
          </el-table-column>
          <el-table-column prop="file_dpi" label="尺寸" min-width="100" align="center" show-overflow-tooltip>
            <template slot-scope="scope">
              <div v-if="!scope.row.file_dpi || scope.row.file_dpi === 'null'"> - </div>
              <div v-else> {{ scope.row.file_dpi }} </div>
            </template>
          </el-table-column>
          <!-- @click="showCoverPreview(scope.row)" -->
          <el-table-column prop="file_thumbnail" label="缩略图" min-width="60" align="center">
            <template slot-scope="scope">
              <div :class="getFileIconClass(scope.row.file_type)">
                <i class="fileIcon" :class="getFileIconClass(scope.row.file_type)" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" min-width="120" align="center" />
          <!-- && !recycleMain.isRecycle -->
          <el-table-column v-if=" !parentsData.isRecycle" label="操作" min-width="80" align="center">
            <template slot-scope="scope">
              <div class="handle-btn">
                <el-button class="iconfont icon-sulan" @click="toPreview(scope.row)" />
                <el-button class="iconfont icon-xiazai" @click="downloadFile(scope.row)" />
                <!-- <el-button class="iconfont icon-dayin" /> -->
              </div>
            </template>
          </el-table-column>
        </el-table>
        <!--分页组件-->
        <el-pagination
          v-if="fileData.length !== 0"
          :current-page="currentPage"
          :total="page.total"
          :page-size="page.size"
          :pager-count="5"
          layout="total, prev, pager, next, sizes"
          @size-change="handleSizeChange"
          @current-change="handleCurrentPage"
        />
      </div>
    </el-drawer>

    <!-- 点击缩略图看大图 -->
    <el-dialog class="preview-dialog" :append-to-body="true" :close-on-click-modal="false" :before-close="handleClose" :visible="showCoverVisible" title="查看大图">
      <span class="dialog-right-top" />
      <span class="dialog-left-bottom" />
      <div class="setting-dialog" style="max-height:calc(100vh - 230px); overflow:auto;">
        <img style="max-width:100%; object-fit: contain;" :src="previewSrc" :onerror="defaultImg">
      </div>
    </el-dialog>
    <div v-if="fileDrawer" :class="['mask-modal',((selectedCategory.arrangeType === 2 && isAjNo === 0) || (selectedCategory.arrangeType === 3 && isAjNo === 1)) ? 'level2-modal' : (isAjNo === 1) ? 'level1-modal' : (selectedCategory.arrangeType === 1) ? 'level1-modal' : 'level3-modal']" @click="closeDrawer" />
  </div>
</template>

<script>
import { collectionLibraryCrud } from '../mixins/index'
import { header, form } from '@crud/crud'
import CollectHeader from '../module/collectHeader'
import { mapGetters } from 'vuex'
import { downloadFile } from '@/utils/index'
import { getToken } from '@/utils/auth'
export default {
  name: 'File',
  components: { CollectHeader },
  mixins: [
    header(),
    form({}),
    collectionLibraryCrud
  ],
  props: {
    selectedCategory: {
      type: Object,
      default: function() {
        return {}
      }
    },
    isRecycle: {
      type: Boolean,
      default: false
    },
    smartQuery: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  inject: ['parentsData'],
  data() {
    return {
      defaultImg: 'this.src="' + require('@/assets/images/cover-bg.png') + '"',
      isTitleType: 6,
      fileDrawer: false,
      test: '',
      isAjNo: 0,
      selections: [],
      showCoverVisible: false,
      previewSrc: null,
      currentPage: 1,
      parentInfo: null
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  watch: {
    selectedCategory: function(newValue, oldValue) {
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    getFileIconClass(fileType) {
      if (!fileType) return 'icon-other'

      const lowerFileType = fileType.toLowerCase()

      switch (lowerFileType) {
        case 'jpg':
        case 'jpeg':
        case 'png':
        case 'bmp':
        case 'gif':
          return 'icon-image'
        case 'xlsx':
        case 'xls':
          return 'icon-excel'
        case 'docx':
        case 'doc':
          return 'icon-word'
        case 'pdf':
          return 'icon-pdf'
        case 'ppt':
        case 'pptx':
          return 'icon-ppt'
        case 'zip':
        case 'rar':
          return 'icon-zip'
        case 'txt':
          return 'icon-txt'
        case 'ofd':
          return 'icon-ofd'
        // 其他未匹配的文件类型
        default:
          return 'icon-other'
      }
    },
    getFileSize(fileSize) {
      // 1. 先将接口返回的KB值转为数字，处理非数字/空值情况
      const sizeInKB = Number(fileSize)
      if (isNaN(sizeInKB) || sizeInKB < 0) {
        return '0 KB' // 异常值默认显示0 KB
      }

      // 2. 定义单位换算关系（1 MB = 1024 KB，1 GB = 1024 MB）
      const KB = 1
      const MB = 1024 * KB
      const GB = 1024 * MB

      // 3. 根据大小自动选择单位并格式化
      if (sizeInKB >= GB) {
        // 大于等于1GB，显示GB（保留2位小数）
        return (sizeInKB / GB).toFixed(2) + ' GB'
      } else if (sizeInKB >= MB) {
        // 大于等于1MB且小于1GB，显示MB（保留2位小数）
        return (sizeInKB / MB).toFixed(2) + ' MB'
      } else if (sizeInKB < 1) {
        // 不足1KB，统一显示1 KB（保持你之前的需求）
        return '1 KB'
      } else {
        // 1KB到1MB之间，显示KB（保留2位小数）
        return sizeInKB + ' KB'
      }
    },
    getCommonData(categoryLevel, parentId, type) {
      this.getViewTable(categoryLevel, parentId, type)
    },
    closeDrawer() {
      console.log('关闭文件annnn')
      localStorage.removeItem('currentPageSize')
      localStorage.removeItem('currentPage')
      this.fileDrawer = false
      if (this.selectedCategory.arrangeType === 1) {
        this.$parent.parentsAnjuanId = null
      } else {
        this.$parent.parentsJuanneiId = null
      }
    },
    rowKey(row) {
      return row.id
    },
    // table选中加上选中状态
    tableRowClassName({ row, rowIndex }) {
      let color = ''
      this.selections.forEach(item => {
        if (item.id === row.id) {
          color = 'rowStyle'
        }
      })
      return color
    },
    // table - 全选
    selectAll(val) {
      this.selections = val
    },
    // table - 双击查看详情
    tableDoubleClick(row) {
    },
    // table - 当前选中得row
    clickRowHandler(row) {
      // this.parentsData.smartQuery = {
      //   'retention': null,
      //   'security_class': null,
      //   'doc_type': null,
      //   'medium_type': null,
      //   'archive_year': null,
      //   'fonds_no': null
      // }
      this.selections = this.crud.selections
    },
    // 触发单选
    handleCurrentChange(selection, row) {
      this.selections = selection
    },
    handleSizeChange(size) {
      this.currentPage = 1
      this.page.size = size
      this.page.page = 0
      localStorage.setItem('currentPageSize', size)
      if (this.selectedCategory.arrangeType === 1) {
        this.getViewTable(4, this.parentsData.parentsAnjuanId)
      } else {
        this.getViewTable(4, this.parentsData.parentsJuanneiId)
      }
    },
    handleCurrentPage(pageVal) {
      this.currentPage = pageVal
      this.page.page = pageVal - 1
      localStorage.setItem('currentPage', JSON.stringify(this.page.page))
      if (this.selectedCategory.arrangeType === 1) {
        this.getViewTable(4, this.parentsData.parentsAnjuanId)
      } else {
        this.getViewTable(4, this.parentsData.parentsJuanneiId)
      }
    },
    // dialog - close
    handleClose(done) {
      this.showCoverVisible = false
      done()
    },
    showCoverPreview(row) {
      this.showCoverVisible = true
      this.previewSrc = this.baseApi + '/downloadFile' + row.file_path
    },
    toPreview(row) {
      console.log('row', row)
      console.log('selectedCategory', row)
      console.log('parentsData', this.parentsData)

      if (this.selectedCategory.arrangeType === 1) {
        this.parentInfo = this.parentsData.parentsAnjuanRow
      } else {
        this.parentInfo = this.parentsData.parentsJuanneiRow
      }
      console.log('this.parentInfo', this.parentInfo)
      const routeData = this.$router.resolve({
        path: '/preview',
        query: {
          'archiveNo': this.parentInfo.archive_no
        }})
      window.open(routeData.href, '_blank')
      if (localStorage.getItem('documentId')) {
        localStorage.removeItem('documentId')
      }
      localStorage.setItem('fileParentInfo', JSON.stringify(this.parentInfo))
      localStorage.setItem('fileTables', JSON.stringify(this.fileData))
      localStorage.setItem('fileCurrent', JSON.stringify(row))
    },
    // 下载附件
    // downloadFile(row) {
    //   const url = this.baseApi + '/downloadFile' + row.file_path
    //   fetch(url).then(res => res.blob()).then(blob => {
    //     downloadFile(blob, row.file_name.split('.')[0], row.file_type)
    //   }).catch(() => {
    //     this.$message({ message: '下载文件失败!', type: 'error', offset: 8 })
    //   })
    // }
    downloadFile(row) {
      const url = this.baseApi + '/api/minioUpload/getFile?filePath=' + row.file_path + '&bucketType=2'
      const fetchOptions = {
        method: 'GET',
        headers: {
          'Authorization': getToken()
        }
      }
      fetch(url, fetchOptions).then(res => res.blob()).then(blob => {
        downloadFile(blob, row.file_name.split('.')[0], row.file_type)
        this.downloading = false
      }).catch(() => {
        this.$message({ message: '下载文件失败', type: 'error', offset: 8 })
        this.downloading = false
      })
    }
  }
}
</script>
<style lang='scss' scoped>
@import "~@/assets/styles/collect-reorganizi.scss";
.svg-style{
  width: 60px;
  height: 32px;
}

</style>
