<template>
  <div id="uploadImage">
    <el-upload
            v-if="url"
            ref="upload"
            :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"
            :accept="accept"
    >
      <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>
    <el-dialog
            :visible.sync="dialogVisible"
            width="30%"
    >
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'uploadImage',
    props: {
      url: { type: null },
      limit: { type: Number },
      data: { type: null },
      isBtn: { type: Boolean, default: false },
      showList: { type: Boolean, default: true },
      accept: { type: String },
      tip: { type: String, default: undefined },
      listType: { type: String, default: 'picture-card' },
    },
    components: {},
    data: () => ({
      dialogVisible: false,
      dialogImageUrl: '',
      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);*/
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      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', []);
        }
      },
    },
  };
</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>
