<template>
  <div id="upload">
    <el-upload
      v-if="url"
      ref="upload"
      :action="url"
      :limit="limit"
      :on-exceed="outLimit"
      :on-preview="handlePictureCardPreview"
      :before-remove="handleRemove"
      :on-success="onSuccess"
      :show-file-list="false"
    >
      <el-avatar :size="80" fit="fill" :src="`${fileUrl}?${new Date().getTime()}`"></el-avatar>
    </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 },
  },
  components: {},
  data: () => ({
    dialogVisible: false,
    dialogImageUrl: '',
    fileList: [],
    fileUrl: '',
  }),
  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.fileUrl = response.uri;
      //将文件整理好传回父组件
      this.$emit('upload', { type: this.type, data: response });
    },
    defalutProcess(val) {
      this.fileUrl = this.data;
      this.$set(this, `fileList`, [{ name: this.type, url: this.data }]);
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.el-upload-list__item {
  width: 5rem;
  height: 5rem;
}
/deep/.el-upload.el-upload--picture-card {
  width: 5rem;
  height: 5rem;
  line-height: 5rem;
}
</style>
