<template>
  <div id="upload">
    <el-upload
      v-if="url"
      ref="upload"
      :action="url"
      list-type="picture-card"
      :file-list="fileList"
      :limit="limit"
      :on-exceed="outLimit"
      :on-preview="handlePictureCardPreview"
      :before-remove="handleRemove"
      :on-success="onSuccess"
    >
      <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>
import _ from 'lodash';
export default {
  name: 'upload',
  props: {
    url: { type: null },
    limit: { type: Number },
    data: { type: null },
    type: { type: String },
  },
  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) {
      if (typeof val === 'object' && _.get(val, length) !== undefined && val.length > 0) {
        let newArr = [];
        val.map(item => {
          let object = {};
          object.name = item.name;
          object.url = `${item.uri}`;
          newArr.push(object);
        });
        this.$set(this, `fileList`, newArr);
      } else if (typeof val === 'object' && _.get(val, length) === undefined) {
        let object = {};
        object.name = val.name;
        object.url = `${val.uri}`;
        this.$set(this, `fileList`, [object]);
      } else if (typeof val === 'string') {
        this.$set(this, `fileList`, [{ name: '附件', url: val }]);
      }
    },
  },
};
</script>

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