<template>
  <!--  七牛多图上传-->
  <el-upload
    ref="upload"
    class="upload-pic"
    :action="upload_qiniu_area"
    :auto-upload="true"
    :limit="limit"
    accept="image/jpg,image/png,image/jpeg,image/gif"
    :file-list="fileList"
    list-type="text"
    :on-preview="picCardPreview"
    :before-upload="beforePicUpload"
    :on-exceed="handleExceed"
    :on-remove="removePic"
    :http-request="uploadQiniu"
    :multiple="true"
  >
    <slot name="upbtn">
      <i class="el-icon-plus"></i>
    </slot>
    <!--      <i class="el-icon-plus"></i>-->
  </el-upload>
</template>

<script>
  import { getEnToken } from "@/utils/accessToken";
  import { uploadToken, UploadDel } from "@/api/common";
  import { apiUrl } from "@/config/settings";
  import axios from "axios";
  export default {
    name: "QiniuMultipleUp",
    data() {
      return {
        img_url: apiUrl.QINIU_URL,
        dialogImageUrl: "",
        dialogVisible: false,
        fileList: [],
        upload_qiniu_area: apiUrl.QINIU_UP, // 七牛云上传储存区域的上传域名
        token: "",
        limit: 50,
      };
    },
    created() {
      // 上来获取七牛token
      this.getQiniuToken();
    },
    methods: {
      // 请求后台拿七牛云token
      async getQiniuToken(key) {
        const data = await uploadToken({
          bucket: apiUrl.QINIU_KEY,
          key: 0,
        });

        this.token = data.data;
      },
      picCardPreview(file) {
        // 上传图预览
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      beforePicUpload(file) {
        // 图片校验
        const limitPic =
          file.type === "image/png" ||
          file.type === "image/jpg" ||
          file.type === "image/jpeg" ||
          file.type === "image/gif";
        if (!limitPic) {
          this.$notify.warning({
            title: "警告",
            message:
              "请上传格式为image/png,image/jpg,image/jpeg,image/gif的图片",
          });
        }
        const limitSize = file.size / 1024 / 1024 / 5 < 5;
        if (!limitSize) {
          this.$notify.warning({
            title: "警告",
            message: "图片大小必须小于5M",
          });
        }
        return limitPic && limitSize;
      },

      async removePic(file, fileList) {
        const data = await UploadDel({
          bucket: apiUrl.QINIU_KEY,
          key: `${getEnToken()}/${file.name}`,
        });
        // 移除图片
        this.fileList = fileList;
      },
      handleExceed(files, fileList) {
        // 文件超出个数限制
        this.$message.warning(`当前限制上传 ${this.limit} 张图片`);
      },
      // this.$refs.upload.clearFiles()
      uploadQiniu(request) {
        // 上传七牛
        const Loading = this.$baseColorfullLoading(2, "图片正在上传...");
        this.handleUpload(request)
          .then((result) => {
            Loading.close();
            if (!result.data.key) {
              this.$message.error({
                message: "图片上传失败,请重新上传",
                duration: 2000,
              });
            } else {
              const url = this.img_url + "/" + result.data.key;
              const name = request.file.name;
              // this.fileList.push({ url: this.img_url + '/' + result.data.key, name: request.file.name })
              this.$refs.upload.clearFiles();
              this.$emit("uploadSuccess", name, url);
            }
          })
          .catch((err) => {
            Loading.close();
            this.$message.error({
              message: `图片上传失败${err}`,
              duration: 2000,
            });
          });
      },
      handleUpload(request) {
        const fileName = request.file.name;
        const promise = new Promise((resolve, reject) => {
          const config = {
            headers: { "Content-Type": "multipart/form-data" },
          };
          const key = `${new Date().getTime()}${Math.floor(
            Math.random() * 100
          )}/${getEnToken()}/${fileName}`; // 自定义图片名
          const fd = new FormData();
          fd.append("file", request.file);
          fd.append("token", this.token);
          fd.append("key", key);
          axios
            .post(this.upload_qiniu_area, fd, config)
            .then((res) => {
              if (res.status && res.data) {
                resolve(res);
              } else {
                reject(res);
              }
            })
            .catch((err) => {
              this.$message.error({
                message: `上传失败[${err.status}]`,
                duration: 2000,
              });
            });
        });
        return promise;
      },
    },
  };
</script>
