<template>
  <div>


    <el-upload
      class="upload-demo"
      ref="upload"
      :action="uploadFileUrl"
      :headers="headers"
      :on-remove="handleRemove"
      :on-success="handleUploadSuccess"
      :file-list="fileList"
      :auto-upload="true"
    >
      <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from '@/utils/auth'
import { addFile, delFile } from '../../../../api/sist/file'

export default {
  name: 'ArticleFile',
  props: {

    value: {
      type: Object,
      default: function () {
        return {
          fileList: [],
          fileMapper: []
        }
      }
    },
    fileList:{
      type:Array,
      default: function () {
        return []
      }
    },
    fileMapper:{
      type:Array,
      default: function () {
        return []
      }
    },
  },
  data() {
    return {
      uploadFileUrl: process.env.VUE_APP_BASE_API + '/common/upload', // 上传的图片服务器地址
      headers: {
        Authorization: 'Bearer ' + getToken()
      },
      // fileList: value.fileList,
      // fileList: [{
      //   name: 'food.jpeg',
      //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
      // }, {
      //   name: 'food2.jpeg',
      //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
      // }],
      // fileMapper: value.fileMapper
    }
  },
  computed: {},
  methods: {
    handleRemove(file, fileList) {
      let fileId = null
      let index = 0
      for (let item of this.fileMapper) {
        console.log(file.uid, item)
        if (file.uid == item.uid) {
          fileId = item.id
          break
        }
        index++
      }
      console.log(index)
      let that = this
      delFile(fileId).then(res => {
        that.fileMapper.splice(index, 1)
        console.log(that.fileMapper)
        that.$message.success('提交成功!')
      })
      this.$emit('input', {
        fileList: this.fileList,
        fileMapper: this.fileMapper
      })
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      console.log(file)
      console.log(res)
      let data = {
        isPublic: '1',
        fileType: '',
        fileAddr: res.fileName
      }
      addFile(data).then(res => {
        console.log(res)
        let data = res.data
        let mapperItem = {
          id: data.fileId,
          uid: file.uid
        }
        this.fileMapper.push(mapperItem)
      })
      this.$message.success('提交成功!')

      this.$emit('input', {
        fileList: this.fileList,
        fileMapper: this.fileMapper
      })
      this.$emit('change', {
        fileList: this.fileList,
        fileMapper: this.fileMapper
      })
    }
  }

}
</script>

<style scoped>

</style>
