<template>
  <el-dialog class="detail-dialog" :title="detailTitle" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :visible.sync="archivesInfoVisible" :before-close="handleClose">
    <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 v-if="isHasFile" :class="{'active-tab-nav': archivesTabIndex == 2}" @click="changeActiveTab(2)">附件</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" v-show="index<archivesDetailsData.length-5" :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>
          <el-row v-if="isDetailsInfo">
            <el-col v-for="(item,index) in archivesDetailsData.slice(archivesDetailsData.length-5,archivesDetailsData.length)" :key="'last'+index" :span=" 12" class="base-info-item">
              <span>{{ item.fieldCnName }}：</span>
              <div v-if="item.fieldName === 'folder_location' && item.context" :style="{ width: item.editLength+'px', marginTop:'-6px'}">
                <div v-if="item.context.indexOf(',')">
                  <el-tag
                    v-for="(val,key) in item.context.split(',')"
                    :key="key"
                    :type="val"
                    effect="dark"
                  >
                    {{ val }}
                  </el-tag>
                </div>
                <div v-else-if="!item.context.indexOf(',')">
                  <el-tag effect="dark">{{ item.context }}</el-tag>
                </div>
              </div>
              <div v-else :style="{ width: item.editLength+'px'}" :class="[ (item.fieldName === 'borrow_type') ? 'row-state row-lending' : '' ]">
                {{ item.context }}
              </div>
            </el-col>
          </el-row>
        </div>
        <!-- 附件 -->
        <!-- <UploadFile v-if="archivesTabIndex==1" ref="uploadFile" class="item-content" :is-upload-detail="false" :category-id="categoryId" :arc-id="arcId" /> -->
        <!-- <ArchivesList v-if="archivesTabIndex==1" ref="dialogList" class="item-content" :is-upload-detail="false" :category-id="categoryId" :arc-id="arcId" /> -->
        <div v-if="archivesTabIndex==1">
          <el-table
            ref="table"
            :data="tableData"
            style="min-width: 100%"
            height="500"
            @row-click="clickRowHandler"
            @selection-change="selectionChangeHandler"
          >
            <el-table-column type="index" label="序号" width="55" align="center" />
            <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="center">
              <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'">
                  <img width="60px" height="32px" class="screenshot" :src="baseApi+ '/downloadFile' +scope.row.file_path" :onerror="defaultImg" @click="showCoverPreview(scope.row)">
                </div>
                <div v-else>
                  <svg-icon icon-class="fujian" class-name="svg-style" />
                </div>
              </template>
            </el-table-column>
          </el-table>
          <!-- @size-change="sizeChangeHandler($event)" @current-change="pageChangeHandler"  -->
          <el-pagination :page-size.sync="page.size" :total="page.total" :current-page.sync="page.page" style="margin-top: 8px;" layout="total, prev, pager, next, sizes" />
        </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>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="archivesInfoVisible=false">确定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<script>
import { form } from '@crud/crud'
import { FetchArchivesDetails, FetchArchivesMetadata } from '@/api/archivesManage/archivesList'
// import UploadFile from './uploadFile/index'
// import ArchivesList from './list/index'
export default {
  name: 'ArchivesInfo',
  components: { },
  mixins: [
    form({})
  ],
  props: {
    categoryId: {
      type: String,
      default: function() {
        return ''
      }
    },
    arcId: {
      type: String,
      default: function() {
        return ''
      }
    }
  },
  data() {
    return {
      detailTitle: '',
      isHasFile: false, // 卷内/文件才有附件
      isDetailsInfo: false, // 项目不显示最下面5行基本信息
      isTidOrBorrow: true, // 卷内不显示tid/借阅状态
      archivesInfoVisible: false,
      archivesTabIndex: 0,
      archivesDetailsData: [],
      archivesDetailsMetadata: [],
      xml_show: null,
      page: {
        total: 0,
        size: 10,
        page: 1
      },
      tableData: [
        {
          isType: '卷案表',
          group: ' 全宗A',
          category: '文书档案（案卷）',
          number: 'DAS-Y-2020-001',
          title: '人事劳资文件级文书档案人事'
        }, {
          isType: '卷案表',
          group: ' 全宗A',
          category: '文书档案（案卷）',
          number: 'DAS-Y-2020-001',
          title: '人事劳资文件级文书档案人事'
        }, {
          isType: '卷案表',
          group: ' 全宗A',
          category: '文书档案（案卷）',
          number: 'DAS-Y-2020-001',
          title: '人事劳资文件级文书档案人事'
        }, {
          isType: '卷案表',
          group: ' 全宗A',
          category: '文书档案（案卷）',
          number: 'DAS-Y-2020-001',
          title: '人事劳资文件级文书档案人事'
        }
      ], // list
      selections: [] // table - 选中的
    }
  },
  mounted() {
  },
  methods: {
    getFileSize(fileSize) {
      const fileSizeInKB = (fileSize / 1024).toFixed(2) + 'kB'
      const fileSizeInB = fileSize + 'B'
      return (fileSize / 1024) <= 0.01 ? fileSizeInB : fileSizeInKB
    },
    getDetial(rowId) {
      const params = {
        // categoryId: this.categoryId,
        categoryId: 'B073E8430B85B4821E7360',
        // archivesId: rowId
        archivesId: '2946C34412182B73FBC287'
      }
      FetchArchivesDetails(params).then(data => {
        this.archivesDetailsData = data
        // 案卷 / 文件的借阅状态
        this.archivesDetailsData.forEach(item => {
          if (item.fieldName === 'borrow_type') {
            if (item.context === 1) {
              item.context = '待登记'
            } else if (item.context === 2) {
              item.context = '待借阅'
            } else if (item.context === 3) {
              item.context = '待归还'
            } else if (item.context === 4 || item.context === '' || item.context === null) {
              item.context = '-'
            } else if (item.context === -1) {
              item.context = '在库'
            }
          }
        })
        // 如果是卷内 - 不显示‘tid’/'借阅状态'
        if (!this.isTidOrBorrow) {
          const indexBorrow = this.archivesDetailsData.findIndex(item => item.fieldName === 'borrow_type')
          const indexTid = this.archivesDetailsData.findIndex(item => item.fieldName === 'tid')
          this.archivesDetailsData.splice(indexBorrow, 1)
          this.archivesDetailsData.splice(indexTid, 1)
        }
      })
      FetchArchivesMetadata(params).then(data => {
        this.archivesDetailsMetadata = data
      })
    },
    setXml() {
      const xmlstr = this.archivesDetailsMetadata
      // console.log('xmlstr:', xmlstr)
      // console.log('xml转json:', this.$x2js.xml2js(xmlstr))
      // console.log('json转xml:', this.$x2js.js2xml(this.$x2js.xml2js(xmlstr)))
      // this.xml_show = vkbeautify.xml(xmlstr)
      this.xml_show = this.showXml(xmlstr)
    },
    changeActiveTab(index) {
      this.archivesTabIndex = index
      if (this.archivesTabIndex === 2) {
        this.setXml()
      }
      this.$nextTick(() => {
        if (this.$refs.uploadFile) {
          this.$refs.uploadFile.tableData = []
          this.$refs.uploadFile.getFileList()
        }
      })
    },
    // 删除 - 关闭
    handleClose(done) {
      this.archivesInfoVisible = false
      done()
    },
    // 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('')
    },
    // table
    clickRowHandler(row) {
      this.$refs.table.toggleRowSelection(row)
    },
    // table
    selectionChangeHandler(val) {
      this.selections = val
    }
  }
}
</script>

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

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

code.hljs {
  color: #0C0E1E !important;
  height: 530px !important;
}
::v-deep .hljs-name{
  color: #0C0E1E !important;
}

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