<template>
  <div>
    <el-upload
      action="#"
      :limit="limit"
      :multiple="multiple"
      :file-list="fileList"
      :show-file-list="true" :auto-upload="false"
      list-type="picture-card"
      :accept="accept"
      :on-change="fileChange"
      :disabled="disabled"
      :class="{ disabled: uploadDisabled }"
      :on-exceed="handleExceed"
      @upload-success="handleUploadSuccess"
    >
      <!-- 文件格式下载，图片格式预览 -->
      <div slot="file" slot-scope="{file}">
        <img class="el-upload-list__item-thumbnail" :src="file.url" alt="">
        <span class="el-upload-list__item-actions">
          <div style="margin-top: 30%;">
            <span class="el-upload-list__item-delete" v-if="file.id" @click="handleDownload(file)">
              <i class="el-icon-download" />
            </span>
            <span class="el-upload-list__item-preview" v-if="file.id" @click="picturePreview(file)">
              <i class="el-icon-zoom-in" />
            </span>
            <span class="el-upload-list__item-delete" @click="fileRemove(file)">
              <i class="el-icon-delete" />
            </span>
             <div class="file-info">
              <p :title="file.name">{{ file.name.length > 12 ? file.name.substr(0, 10) + '..' : file.name }}</p>
              <p>{{ formatFileSize(file.size) }}/{{ file.createTime }}</p>
            </div>
          </div>
        </span>
      </div>

      <i class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>

  </div>
</template>

<script>
import { downloadFile } from '@/api/tool/select'
import { lookFaceFile, parseTime } from '@/utils/bonus'

export default {
  name: 'uploadFile',
  data() {
    return {
      fileList: [],
      num: 0,
      lookFaceFile: ''
    }
  },
  props: {
    limit: {
      type: [String, Number],
      default: ''
    },
    uploadList: {
      type: Array,
      default: function() {
        return []
      }
    },
    disabled: {
      type: Boolean,
      default: false
    },
    accept: {
      type: String,
      default: '.png, .jpg, .jpeg'
    },
    multiple: {
      type: Boolean,
      default: false
    }
  },
  computed: {
    //图片上传超出限制，隐藏上传框
    uploadDisabled() {
      return this.fileList.length >= Number(this.limit)
    }
  },
  mounted() {
    this.lookFaceFile = lookFaceFile()
    console.log('mounted：-----------------')
    console.log(this.$props.uploadList)
    this.assign()
  },
  methods: {
    parseTime,
    lookFaceFile,
    formatFileSize(size) {
      const units = ['B', 'KB', 'MB', 'GB', 'TB']
      let idx = 0
      while (size >= 1024 && idx < units.length - 1) {
        size /= 1024
        idx++
      }
      return `${Number(size).toFixed(2)}${units[idx]}`
    },
    handleUploadSuccess(file, fileList) {
      console.log('handleUploadSuccess', file, fileList)
      // Update specific properties of the uploaded file
      fileList.forEach(f => {
        if (f.uid === file.uid) {
          f.customProperty = 'customValue'; // Example of setting a custom property
        }
      });
      this.form.scenePhotoList = fileList;
    },
    assign() {
      this.num++
      if (this.$props.uploadList.length === 0) {
        console.log('assign:' + this.num)
        setTimeout(() => {
          if (this.num > 2) {
            this.updateIcon()
            return
          }
          this.assign()
        }, 1000)
      } else {
        console.log('assign:' + this.num)
        this.updateIcon()
      }
    },
    updateIcon() {
      this.fileList = this.$props.uploadList.map(item => {
        let pointIndex = item.name.lastIndexOf(".") + 1
        let fileName = item.name.substring(pointIndex).toLowerCase();
        if (fileName === 'png' || fileName === 'jpg' || fileName === 'jpeg') {
          return {
            id: item.id,
            name: item.name,
            url: this.lookFaceFile + item.url,
            fileName: item.name,
            filePreviewUrl: item.url,
            size: item.fileSize,
            createTime: item.createTime
          }
        } else if (fileName === 'pdf') {
          return {
            id: item.id,
            name: item.name,
            url: require('../../../assets/file/pdf.png'),
            fileName: item.name,
            filePreviewUrl: item.url,
            size: item.fileSize,
            createTime: item.createTime
          }
        } else if (fileName === 'doc' || fileName === 'docx') {
          return {
            id: item.id,
            name: item.name,
            url: require('../../../assets/file/word.png'),
            fileName: item.name,
            filePreviewUrl: item.url,
            size: item.fileSize,
            createTime: item.createTime
          }
        } else if (fileName === 'xls' || fileName === 'xlsx') {
          return {
            id: item.id,
            name: item.name,
            url: require('../../../assets/file/excel.png'),
            fileName: item.name,
            filePreviewUrl: item.url,
            size: item.fileSize,
            createTime: item.createTime
          }
        }
      })
    },
    handleExceed() {
      //提示最多只能上传5个
      this.$message.warning('最多上传5个文件')
    },

    fileChange(file, fileList) {
      console.log('w2e')
      if (file.size > 1024 * 1024 * 30) {
        this.$message.warning('文件单个大小不能超过30Mb')
        fileList = fileList.filter(item => {
          return item.uid !== file.uid
        })
      }
      fileList.forEach(file => {
        const fileType = file.name.split('.').pop().toLowerCase();
        if (['doc', 'docx'].includes(fileType)) {
          file.url = require('@/assets/file/word.png');
        } else if (['xls', 'xlsx'].includes(fileType)) {
          file.url = require('@/assets/file/excel.png');
        } else if (fileType === 'pdf') {
          file.url = require('@/assets/file/pdf.png');
        }
        file.id = file.id || '';
        file.createTime = parseTime(new Date(), '{y}-{m}-{d}')
        if (file && file.raw) {
          file.size = file.size || file.raw.size || 0; // Ensure size is retained
        } else {
          file.size = 0; // Fallback if file.raw is undefined
        } // Ensure size is retained
        console.log(file)
      })
      this.fileList = fileList.map(file => ({ ...file }));
      this.$emit('update:uploadList', this.fileList)
      this.$emit('up')
    },
    fileRemove(file) {
      let sum = 0
      this.fileList.forEach((item, index) => {
        if (item.uid === file.uid) {
          sum = index
        }
      })
      console.log(this.fileList[sum])
      if (this.fileList[sum].id !== '') {
        this.$emit('delFile', this.fileList[sum].id)
      }
      this.fileList.splice(sum, 1)
      // this.$emit('uploadList', this.fileList)
      this.$emit('update:uploadList', this.fileList)

    },
    handleDownload(file) {
      downloadFile(file.filePreviewUrl, file.name)
    },
    //上传组件-图片查看
    picturePreview(file) {
      this.$emit('picturePreview', file)
    },
    // 判断文件类型,图片预览，文件下载
    updataIf(e) {
      if (e.fileName) {
        if (e.fileName.split('.')[1] === 'png' || e.fileName.split('.')[1] === 'jpeg' || e.fileName.split('.')[1] === 'jpg') {
          return false
        } else {
          return true
        }
      } else {
        if (e.name.split('.')[1] === 'png' || e.name.split('.')[1] === 'jpeg' || e.name.split('.')[1] === 'jpg') {
          return false
        } else {
          return true
        }
      }
    }

  }
}
</script>

<style lang="scss" scoped>
::v-deep.disabled {
  .el-upload--picture-card {
    display: none;
  }
}

.file-info {
  font-size: 12px;
  margin-top: 5px;
}
</style>
