<template>
  <div id="upload">
    <el-upload
      v-if="url"
      ref="upload"
      :action="url"
      :list-type="listType"
      :file-list="fileList"
      :limit="limit"
      :on-exceed="outLimit"
      :on-preview="handlePictureCardPreview"
      :before-remove="handleRemove"
      :on-success="onSuccess"
      accept=".jpg,.jpeg,.png,.bmp,.gif,.svg,.mp4"
    >
      <template>
        <i class="el-icon-plus"></i>
      </template>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'upload',
  props: {
    url: { type: null },
    limit: { type: Number },
    data: { type: null },
    type: { type: String },
    listType: { type: String, default: 'picture-card' },
  },
  components: {},
  data: () => ({
    dialogVisible: false,
    dialogImageUrl: '',
    fileList: [],
  }),
  created() {
    if (this.data) {
      this.defalutProcess(this.data);
    }
  },
  watch: {
    data: {
      handler(val) {
        this.defalutProcess(val);
      },
    },
  },
  computed: {},
  methods: {
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file) {
      return true;
    },
    outLimit() {
      this.$message.error('只允许上传1张图片');
    },
    onSuccess(response, file, fileList) {
      //将文件整理好传回父组件
      this.$emit('upload', { type: this.type, data: response });
    },
    defalutProcess(val) {
      this.$set(this, `fileList`, [{ name: this.type, url: `${this.data}?${new Date().getTime()}` }]);
    },
  },
};
</script>

<style lang="less" scoped></style>
