<template>
<message-bubble :isMine=isMine :message=message>
  <div class="file-element-wrapper" title="单击下载" @click="downloadFile">
    <div class="header">
      <i class="el-icon-document file-icon"></i>
      <div class="file-element">
        <span class="file-name">{{ fileName }}</span>
        <span class="file-size">{{ size }}</span>
      </div>
    </div>
    <el-progress
      v-if="showProgressBar"
      :percentage="percentage"
      :color="percentage => (percentage === 100 ? '#67c23a' : '#409eff')"
    />
  </div>
</message-bubble>
</template>

<script>
import MessageBubble from '../message-bubble'
import { Progress } from 'element-ui'
export default {
  name: 'FileElement',
  props: {
    payload: {
      type: Object,
      required: true
    },
    message: {
      type: Object,
      required: true
    },
    isMine: {
      type: Boolean
    }
  },
  components: {
    MessageBubble,
    ElProgress: Progress
  },
  computed: {
    fileName() {
      return this.payload.fileName
    },
    fileUrl() {
      return this.payload.sourceUrl
    },
    size() {
      const size = this.payload.fileSize
      if (size > 1024) {
        if (size / 1024 > 1024) {
          return `${this.toFixed(size / 1024 / 1024)} Mb`
        }
        return `${this.toFixed(size / 1024)} Kb`
      }
      return `${this.toFixed(size)}B`
    },
    showProgressBar() {
      return this.$parent.message.status === 'unSend'
    },
    percentage() {
      return Math.floor((this.$parent.message.progress || 0) * 100)
    }
  },
  methods: {
    toFixed(number, precision = 2) {
      return number.toFixed(precision)
    },
    downloadFile() {
      console.log(this.payload)
      console.log(this.message)
      const fileUrl = this.fileUrl;
      const fileName = this.fileName;
      console.log(fileUrl)
      fetch(fileUrl)
        .then(response => {
          if (!response.ok) throw new Error(`下载失败，状态码：${response.status}`);
          return response.blob();
        })
        .then(blob => {
          const mime = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
          const docBlob = new Blob([blob], { type: mime }); // 💡 明确指定 MIME 类型
          const blobUrl = window.URL.createObjectURL(docBlob);

          const a = document.createElement('a');
          a.href = blobUrl;
          a.download = fileName;
          document.body.appendChild(a);
          a.click();
          document.body.removeChild(a);
          window.URL.revokeObjectURL(blobUrl); // 释放资源
        })
        .catch(err => {
          console.error('下载失败:', err);
        });
    }
  }
}
</script>

<style lang="stylus" scoped>
.file-element-wrapper {
  cursor pointer
}
.header {
  display: flex;
}
.file-icon {
  font-size: 40px !important;
}
.file-element {
  display: flex;
  flex-direction: column;
  margin-left: 12px;
}
.file-size {
  font-size: 12px;
  padding-top 5px
}
</style>
