<template>
  <div>
    <!-- :wrapper-closable="false" -->
    <el-drawer
      class="management-drawer"
      :with-header="false"
      :visible.sync="fileDrawer"
      :modal="false"

      :show-close="false"
      direction="rtl"
      :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>
        <el-table
          ref="table"
          v-loading="crud.loading || getTableDisplayFieldsLoading"
          class="archives-table"
          :data="fileData"
          highlight-current-row
          style="width: 100%;"
          height="calc(100vh - 364px)"
          :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="85" align="right">
            <template slot-scope="scope">
              {{ getFileSize(scope.row.file_size) }}
            </template>
          </el-table-column>
          <el-table-column prop="file_dpi" label="尺寸" min-width="85" align="center">
            <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>
          <el-table-column prop="file_thumbnail" label="缩略图" min-width="60" align="center">
            <template slot-scope="scope">
              <div v-if="scope.row.file_type === 'jpg' || scope.row.file_type === 'jpeg' || scope.row.file_type === 'png' || scope.row.file_type === 'bmp'|| scope.row.file_type === 'gif'">
                <i class="fileIcon icon-image" />
              </div>
              <div v-else-if="scope.row.file_type === 'xlsx' || scope.row.file_type === 'xls'">
                <i class="fileIcon icon-excel" />
              </div>
              <div v-else-if="scope.row.file_type === 'docx' || scope.row.file_type === 'doc'">
                <i class="fileIcon icon-word" />
              </div>
              <div v-else-if="scope.row.file_type === 'pdf'">
                <i class="fileIcon icon-pdf" />
              </div>
              <div v-else-if="scope.row.file_type === 'ppt' || scope.row.file_type === 'pptx'">
                <i class="fileIcon icon-ppt" />
              </div>
              <div v-else-if="scope.row.file_type === 'zip' || scope.row.file_type === 'rar'">
                <i class="fileIcon icon-zip" />
              </div>
              <div v-else-if="scope.row.file_type === 'txt'">
                <i class="fileIcon icon-txt" />
              </div>
              <div v-else-if="scope.row.file_type === 'ofd'">
                <i class="fileIcon icon-ofd" />
              </div>
              <div v-else>
                <i class="fileIcon icon-other" />
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="create_time" label="创建时间" min-width="110" align="center" />
        </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>
  </div>
</template>

<script>
import { manageLibraryCrud } from '../mixins/index'
import { header, form } from '@crud/crud'
import CollectHeader from '../module/collectHeader'
import { mapGetters } from 'vuex'
export default {
  name: 'File',
  components: { CollectHeader },
  mixins: [
    header(),
    form({}),
    manageLibraryCrud
  ],
  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
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  watch: {
    selectedCategory: function(newValue, oldValue) {
    }
  },
  created() {
  },
  mounted() {
  },
  methods: {
    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() {
      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) {
      // console.log('tableDoubleClick', row)
      // this.arcId = row.id
      // console.log(this.selectedCategory.isType)
    },
    // 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
    }
  }
}
</script>

<style lang='scss' scoped>
@import "~@/assets/styles/collect-reorganizi.scss";
.svg-style{
  width: 60px;
  height: 32px;
}
</style>
