<template>
  <div id="uploadFile">
    <el-upload
            v-if="url"
            ref="upload"
            accept=".mp4"
            :before-upload="beforeUpload"
            :action="url"
            :list-type="listType"
            :file-list="fileList"
            :limit="limit"
            :on-exceed="outLimit"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="onSuccess"
            :show-file-list="showList"
    >
      <el-button size="small" class="isBtn" v-if="isBtn">点击上传文件</el-button>
      <template v-else>
        <i class="el-icon-plus"></i>
      </template>
      <template #tip v-if="tip">
        <span class="tip">{{ tip }}</span>
      </template>
    </el-upload>
  </div>
</template>

<script>
  import _ from 'lodash';
  export default {
    name: 'uploadFile',
    props: {
      url: { type: null },
      limit: { type: Number },
      data: { type: null },
      isBtn: { type: Boolean, default: false },
      showList: { type: Boolean, default: true },
      tip: { type: String, default: undefined },
      listType: { type: String, default: 'text' },
    },
    components: {},
    data: () => ({
      fileList: [],
    }),
    created() {
    },
    mounted(){
    },
    watch: {
      data: {
        handler(val) {
          this.defaultProcess(val);
        },
        deep: true,
        immediate: true,
      },
    },
    computed: {},
    methods: {
      handlePictureCardPreview(file) {
        let eleLink = document.createElement('a');
        eleLink.setAttribute("download", file.name);
        eleLink.href = file.url;
        eleLink.style.display = 'none';
        document.body.appendChild(eleLink);
        eleLink.click();
        document.body.removeChild(eleLink);
      },
      handleRemove(file) {
        this.$emit('remove', file);
      },
      outLimit() {
        this.$message.error(`只允许上传${this.limit}个文件`);
      },
      onSuccess(response, file, fileList) {
        this.$emit('uploadSuccess', {data: response});
      },
      defaultProcess(val) {
        if(val){
          this.$set(this, 'fileList',  [{name:val,url:val}]);
        }else {
          this.$set(this, 'fileList', []);
        }
      },
      beforeUpload (file) {
        if (file != null) {
          const isLt1M = file.size / 1024 / 1024 < 7;
          if (!isLt1M) {
            this.$message.error('上传文件大小不能超过7MB!');
            return false;
          }
        }
      }
    },
  };
</script>

<style lang="less" scoped>
  .isBtn {
    background-color: #e9021d;
    color: #ffffff;
  }
  .links {
    margin: 0 0 0 15px;
  }
  .tip {
    padding: 0 10px;
    display: inline-block;
    color: #999999;
  }
</style>
