<template>
  <el-dialog class="detail-dialog" title="详情" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :visible.sync="archivesInfoVisible" :before-close="handleClose">
    <!-- <span class="dialog-right-top" />
    <span class="dialog-left-bottom" /> -->
    <div class="setting-dialog">
      <div class="detail-tab tab-content">
        <!-- tab -->
        <ul class="tab-nav">
          <li :class="{'active-tab-nav': archivesTabIndex == 0}" @click="changeActiveTab(0)">基本信息</li>
          <li :class="{'active-tab-nav': archivesTabIndex == 1}" @click="changeActiveTab(1)">电子原件</li>
          <li :class="{'active-tab-nav': archivesTabIndex == 2}" @click="changeActiveTab(2)">元数据</li>
        </ul>
        <!-- 基本信息 -->
        <div v-if="archivesTabIndex===0" class="base-info item-content">
          <el-row>
            <el-col v-for="(item,index) in archivesDetailsData" :key="index" :span="item.isLine ? 24 : 12" class="base-info-item">
              <span>{{ item.fieldCnName }}：</span>
              <p :style="{ width: ( item.editLength ? item.editLength+'px' : '' ), flex: ( !item.editLength ? 1 : '' )}">{{ item.context }}</p>
            </el-col>
          </el-row>
        </div>
        <!-- 电子原件 -->
        <div v-if="archivesTabIndex===1" class="item-content">
          <el-table
            ref="table"
            :data="tableData"
            style="min-width: 100%"
            height="calc(100vh - 382px)"
            @row-click="clickRowHandler"
            @selection-change="selectionChangeHandler"
          >
            <el-table-column prop="file_name" label="文件名称" show-overflow-tooltip min-width="140" align="center" />
            <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 :class="getFileIconClass(scope.row.file_type)">
                  <i class="fileIcon" :class="getFileIconClass(scope.row.file_type)" />
                </div>
              </template>
            </el-table-column>
            <el-table-column 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>
        </div>
        <!-- 元数据 -->
        <div v-if="archivesTabIndex==2" class="metadata-cont item-content">
          <pre v-highlightjs="xml_show">
            <code class="highlight_s">
              {[xml_show]}
            </code>
          </pre>
        </div>
        <!-- 点击缩略图看大图 -->
        <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>
    </div>
  </el-dialog>
</template>

<script>
import { form } from '@crud/crud'
import { FetchArchivesDetails, FetchFileListByDocumentId, FetchArchivesMetadata } from '@/api/prearchiveLibrary/prearchiveLibrary'
import { mapGetters } from 'vuex'
import { downloadFile } from '@/utils/index'
import { getToken } from '@/utils/auth'

export default {
  name: 'PrearchiveLibraryDetail',
  components: { },
  mixins: [
    form({})
  ],
  props: {
    selectedDocument: {
      type: Object,
      default: function() {
        return {}
      }
    }
  },
  data() {
    return {
      defaultImg: 'this.src="' + require('@/assets/images/cover-bg.png') + '"',
      archivesInfoVisible: false,
      archivesTabIndex: 0,
      archivesDetailsData: [],
      archivesDetailsMetadata: [],
      xml_show: null,
      selections: [],
      tableData: [],
      showCoverVisible: false,
      previewSrc: '', // 查看大图src
      parentInfo: null
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  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'
      }
    },
    downloadFile(row) {
      // filePath 保存的文件路径
      // bucketType 1预归档 2档案
      const url = this.baseApi + '/api/minioUpload/getFile?filePath=' + row.file_path + '&bucketType=1'
      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)
      }).catch(() => {
        this.$message({ message: '下载文件失败', type: 'error', offset: 8 })
      })
    },
    toPreview(row) {
      const routeData = this.$router.resolve({
        path: '/preview',
        query: {
          'archiveNo': this.parentInfo.maintitle
        }})
      window.open(routeData.href, '_blank')
      localStorage.setItem('documentId', JSON.stringify(this.selectedDocument.id))
      localStorage.setItem('fileParentInfo', JSON.stringify(this.parentInfo))
      localStorage.setItem('fileTables', JSON.stringify(this.tableData))
      localStorage.setItem('fileCurrent', JSON.stringify(row))
    },
    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'
      }
    },
    getDetial(rowId) {
      const params = {
        documentId: this.selectedDocument.id,
        archivesId: rowId
      }
      FetchArchivesDetails(params).then(data => {
        this.archivesDetailsData = data
      })
      FetchFileListByDocumentId(params).then(data => {
        this.tableData = data.returnlist
      })
      FetchArchivesMetadata(params).then(data => {
        this.archivesDetailsMetadata = data
      })
    },
    changeActiveTab(index) {
      this.archivesTabIndex = index
      if (this.archivesTabIndex === 2) {
        this.setXml()
      }
    },
    // table
    clickRowHandler(row) {
      this.$refs.table.toggleRowSelection(row)
    },
    // table
    selectionChangeHandler(val) {
      this.selections = val
    },
    // dialog - close
    handleClose(done) {
      this.showCoverVisible = false
      done()
    },
    // 查看大图
    showCoverPreview(row) {
      this.showCoverVisible = true
      this.previewSrc = this.baseApi + '/downloadFile' + row.file_path
    },
    setXml() {
      const xmlstr = this.archivesDetailsMetadata
      this.xml_show = this.showXml(xmlstr)
    },
    // xml格式化
    showXml(str) {
      var that = this
      var text = str
      // 去掉多余的空格
      text =
        '\n' +
        text
          .replace(/(<\w+)(\s.*?>)/g, function($0, name, props) {
            return name + ' ' + props.replace(/\s+(\w+=)/g, ' $1')
          })
          .replace(/>\s*?</g, '>\n<')
      // 把注释编码
      text = text
        .replace(/\n/g, '\r')
        .replace(/<!--(.+?)-->/g, function($0, text) {
          var ret = '<!--' + escape(text) + '-->'
          return ret
        })
        .replace(/\r/g, '\n')

      // 调整格式
      var rgx = /\n(<(([^\?]).+?)(?:\s|\s*?>|\s*?(\/)>)(?:.*?(?:(?:(\/)>)|(?:<(\/)\2>)))?)/gm
      var nodeStack = []
      var output = text.replace(rgx, function(
        $0,
        all,
        name,
        isBegin,
        isCloseFull1,
        isCloseFull2,
        isFull1,
        isFull2
      ) {
        var isClosed =
          isCloseFull1 === '/' ||
          isCloseFull2 === '/' ||
          isFull1 === '/' ||
          isFull2 === '/'
        var prefix = ''
        if (isBegin === '!') {
          prefix = that.getPrefix(nodeStack.length)
        } else {
          if (isBegin !== '/') {
            prefix = that.getPrefix(nodeStack.length)
            if (!isClosed) {
              nodeStack.push(name)
            }
          } else {
            nodeStack.pop()
            prefix = that.getPrefix(nodeStack.length)
          }
        }
        var ret = '\n' + prefix + all
        return ret
      })
      var outputText = output.substring(1)
      // 把注释还原并解码，调格式
      outputText = outputText
        .replace(/\n/g, '\r')
        .replace(/(\s*)<!--(.+?)-->/g, function($0, prefix, text) {
          if (prefix.charAt(0) === '\r') prefix = prefix.substring(1)
          text = unescape(text).replace(/\r/g, '\n')
          var ret =
            '\n' + prefix + '<!--' + text.replace(/^\s*/gm, prefix) + '-->'
          return ret
        })
      outputText = outputText.replace(/\s+$/g, '').replace(/\r/g, '\r\n')
      return outputText
    },
    getPrefix(prefixIndex) {
      var span = '    '
      var output = []
      for (var i = 0; i < prefixIndex; ++i) {
        output.push(span)
      }
      return output.join('')
    }
  }
}
</script>

<style lang="scss" scoped>
.base-info,
.metadata-cont{
  background-color: #F6F8FC;
}

// 档案详情
.base-info{
  padding: 20px 0;
  overflow: hidden;
  overflow-y: scroll;
  .base-info-item{
    display: flex;
    flex-direction: row;
    margin-bottom: 20px;
    color: #545B65;
    span{
      display: block;
      width: 160px;
      font-weight: bold;
      margin-right: 5px;
      text-align: right;
      color: #0C0E1E;
    }
  }
}

code.hljs {
  font-size: 12px;
  color: #0C0E1E !important;
  height: 530px !important;
}
::v-deep .hljs-name{
  color: #0C0E1E !important;
}
.base-info .base-info-item span.el-tag{
  width: auto;
  color: #fff;
}

.svg-style{
  width: 60px;
  height: 32px;
}

</style>
