<template>
  <div class="edit-add-detail detail">
    <div class="form-content" v-if="!previewFile">
      <el-form
        ref="detailForm"
        :model="detailForm"
        class="detail-form"
        label-suffix="："
      >
        <div class="archives-page-content-table">
          <div>
            <div class="rows">
              <div class="rows-left">
                <div class="rows-hr"></div>
              </div>
              <div class="rows-title">
                <div class="text-overflow">视频资料基本信息</div>
              </div>
            </div>
            <el-descriptions :column="3" border>
              <!-- 资料名称 -->
              <el-descriptions-item
                label="资料名称"
                :labelStyle="{width: '8%'}"
                :contentStyle="{width: '20%'}"
              >
                <span :title="detailForm.fileName" class="text-ellipsis">
                  {{ detailForm.fileName || '-' }}</span
                >
              </el-descriptions-item>
              <!-- 上传人 -->
              <el-descriptions-item
                label="上传人"
                :labelStyle="{width: '8%'}"
                :contentStyle="{width: '20%'}"
              >
                <span :title="detailForm.createName" class="text-ellipsis">
                  {{ detailForm.createName || '-' }}
                </span>
              </el-descriptions-item>
              <!-- 上传时间 -->
              <el-descriptions-item
                label="上传时间"
                :labelStyle="{width: '8%'}"
                :contentStyle="{width: '20%'}"
              >
                <span :title="detailForm.createTime" class="text-ellipsis">
                  {{ detailForm.createTime || '-' }}</span
                >
              </el-descriptions-item>
              <!-- 资料简介 -->
              <el-descriptions-item
                label="资料简介"
                :labelStyle="{width: '8%'}"
                :contentStyle="{width: '20%'}"
              >
                <span
                  :title="detailForm.fileIntroduction"
                  class="text-ellipsis"
                >
                  {{ detailForm.fileIntroduction || '-' }}</span
                >
              </el-descriptions-item>
            </el-descriptions>
            <div class="rows">
              <div class="rows-left">
                <div class="rows-hr"></div>
              </div>
              <div class="rows-title">
                <div class="text-overflow">附件</div>
              </div>
            </div>
          </div>

          <el-table
            ref="multipleSelection"
            :data="detailForm.fileList"
            border
            class="table-list"
            row-key="id"
            stripe
          >
            <el-table-column
              :index="index => index + 1"
              align="center"
              label="序号"
              type="index"
              width="80"
            />
            <el-table-column
              align="center"
              label="附件名称"
              min-width="200"
              prop="fileName"
              show-overflow-tooltip
            >
            </el-table-column>
            <el-table-column
              :formatter="({size}) => formatFileSize(size)"
              align="center"
              label="附件大小"
              min-width="100"
              prop="size"
            />
            <el-table-column
              align="center"
              label="操作"
              min-width="130"
              show-overflow-tooltip
            >
              <template v-slot="{row}">
                <el-link
                  :underline="false"
                  type="primary"
                  @click="handleDownload(row)"
                >
                  文件下载
                </el-link>
                <el-link
                  :underline="false"
                  type="primary"
                  @click="handlePreview(row)"
                >
                  视频预览
                </el-link>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>
      <el-backtop :visibility-height="10" target=".detail-form">
        <div class="top-box">UP</div>
      </el-backtop>
    </div>
    <previewVideo v-else @back="back" :fileData="currentFile" />
  </div>
</template>

<script>
import {tableDetail} from '@/api/patrolAndRescue/documentation/videoMaterials'
import previewVideo from '@/components/previewVideo'
import PubSub from 'pubsub-js'
import {dictionaryEscape} from '@/utils/dictionary'
import moment from 'moment'
import 'moment-duration-format'

export default {
  name: 'DetailPage',
  components: {
    previewVideo
  },
  props: {
    componentName: {
      default: 'TablePage',
      type: String
    }
  },
  data() {
    return {
      detailForm: {
        fileInfo: []
      },
      currentFile: null,
      previewFile: false,
      pubSub: null
    }
  },
  watch: {
    componentName: {
      handler(newVal) {
        if (newVal === this.$options.name) {
          this.openPage()
        } else {
          this.closePage()
        }
      }
    }
  },
  computed: {
    previewUrl: _ =>
      window.context.portal + '/file/onlinePreviewController/v1/getFileById_',
    downloadUrl: _ => window.context.portal + '/file/v1/downloadFile?fileId='
  },
  mounted() {
    this.pubSub = PubSub.subscribe('DetailPage', (_, data) => {
      if (data.id) {
        this.getDetail(data.id)
      }
    })
  },
  methods: {
    dictionaryEscape,

    // 打开页面执行
    openPage() {},

    // 关闭页面执行
    closePage() {
      // 重置组件数据
      Object.assign(this.$data, this.$options.data.call(this), {
        pubSub: this.pubSub
      })
      this.$nextTick(_ => {
        this.$refs.detailForm.$el.scrollTop = 0
      })
    },

    // 获取详情
    async getDetail(id) {
      const {files = [], ...detailForm} = await tableDetail(id)

      this.detailForm = {
        fileList: files?.map(i => ({
          ...i,
          size: i.byteCount
        })),
        ...detailForm
      }

      console.log(this.detailForm)
    },

    // 格式化文件大小
    formatFileSize(bytes) {
      const k = 1024
      const sizes = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
      if (bytes < k) return '0 KB' // 最小单位为 kb
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      const size = bytes / Math.pow(k, i)
      const formattedSize = parseFloat(size.toFixed(2))
      return `${formattedSize} ${sizes[i - 1]}` // i-1 因为 kb 是最小单位
    },

    // 格式化时间为时分秒（可大于24个小时）
    formatTime(time) {
      return moment
        .duration(time, 'seconds')
        .format('H小时m分ss秒', {trim: false})
    },

    // 已上传文件点击
    handleDownload(file) {
      const fileId = file.id || '' // 文件ID
      const fileName = file.fileName || '' // 文件名
      if (!(fileId && fileName)) return this.$message.warning('文件信息错误！')
      window.open(this.downloadUrl + fileId, '_blank')
    },
    // 已上传文件点击预览
    async handlePreview(file) {
      this.previewFile = true
      this.currentFile = file
    },

    back() {
      this.previewFile = false
    },

    // 改变页面
    changePage(pageName = '', type = '') {
      if (!pageName) return
      this.$emit('changePage', pageName, _ => {
        PubSub.publish(pageName, {type})
      })
    }
  },
  beforeDestroy() {
    // 在组件销毁之前 清除订阅消息
    PubSub.unsubscribe(this.pubSub)
  }
}
</script>

<style lang="scss" scoped>
@import '~@/assets/css/element-variables';
.archives-page-content-table {
  padding: 0 200px;
  ::v-deep .el-descriptions {
    margin-top: -1px;

    &.el-descriptions-table {
      .el-descriptions__table {
        tbody {
          &:not(:first-child) {
            .el-descriptions-row {
              &:first-child {
                display: none;
              }
            }
          }
        }
      }
    }

    .el-descriptions__body {
      .el-descriptions-row {
        .el-descriptions-item__label {
          width: 222px;
        }

        .el-descriptions-item__content {
          .high-item {
            min-height: 70px;
          }
        }
      }
    }
  }
}
</style>
