<template>
  <div>
    <el-row>
      <el-upload
        :file-list="imgList"
        v-loading.fullscreen.lock="mark"
        ref="upload"
        action=""
        :headers="myHeaders"
        list-type="picture-card"
        :multiple="true"
        :auto-upload="false"
        :limit="limit"
        :on-change="handleChange"
        :disabled="limit <= value.length"
      >
        <i slot="default" class="el-icon-plus" />
        <div slot="file" slot-scope="{ file }">
          <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
          <span class="el-upload-list__item-actions">
            <span
              class="el-upload-list__item-preview"
              @click="handlePictureCardPreview(file)"
            >
              <i class="el-icon-zoom-in" />
            </span>
            <span
              class="el-upload-list__item-preview"
              @click="handleDeleteItem(file)"
            >
              <i class="el-icon-delete" />
            </span>
          </span>
        </div>
      </el-upload>
    </el-row>

    <el-row style="text-align: right;">
      <el-button
        class="mt-40"
        style="margin-left: 10px;"
        size="small"
        type="success"
        @click="submitUpload"
        >上传到服务器</el-button
      >
    </el-row>

    <el-dialog :visible.sync="dialogVisible" :modal="false">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import { UPLOAD_URL } from '@/const/urlKey';
import { getToken } from '@/utils/auth';

export default {
  name: 'Upload',
  props: {
    value: {
      type: Array,
      default: () => []
    },
    limit: {
      type: Number,
      default: 1
    },
    params: {
      type: String,
      default: ''
    },
    paramsData: {
      type: Object,
      default: () => ({})
    },
    api: {
      type: Function,
      default: () => {}
    },
    error: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      mark: false,
      url: UPLOAD_URL,
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      myHeaders: {
        authorization: 'Bearer swagger-ui',
        token: getToken()
      },
      imgList: [],
      tmp: []
    };
  },

  computed: {
    newUrl() {
      const params = this.params;
      const url = this.uploadUrl;
      let baseUrl = UPLOAD_URL;
      if (url !== '') {
        baseUrl = url;
      }
      if (params === '') {
        return baseUrl;
      } else {
        return baseUrl + `?${params}`;
      }
    }
  },

  // watch: {
  //   value: {
  //     handler(val) {
  //       // if (this.imgList.length < val.length) {
  //       this.imgList = val;
  //       console.log(this.imgList);
  //       // }
  //     },
  //     immediate: true
  //   }
  // },

  methods: {
    handleChange(fileList) {
      this.imgList.push(fileList);
    },
    submitUpload() {
      if (this.error) {
        this.$error(this.error);
        return false;
      }
      if (this.imgList.length == 0) {
        this.$error('未选择图片,请先选择图片');
        return false;
      }

      this.mark = true;
      let form = new FormData();
      for (let key in this.paramsData) {
        form.append(key, this.paramsData[key]);
      }

      this.imgList.forEach(file => {
        form.append('file', file.raw);
      });

      this.api(form)
        .then(({ success }) => {
          if (success) {
            this.mark = false;
            this.$emit('finish');
          } else {
            this.$error('上传失败，请稍后重试...');
            this.mark = false;
          }
        })
        .catch(err => {
          console.error(err);
          this.$error('上传失败，请稍后重试...');
          this.mark = false;
        });
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDeleteItem(file) {
      const index = this.imgList.findIndex(x => x.uid === file.uid);
      this.imgList.splice(index, 1);
    }
  }
};
</script>

<style scoped>
.page-select {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 20px;
}
</style>
