<template>
  <div class="upload-info">
    <el-upload
      class="upload-pic"
      :action="domain"
      :data="QiniuData"
      :on-remove="handleRemove"
      :on-error="uploadError"
      :on-success="uploadSuccess"
      :before-remove="beforeRemove"
      :before-upload="beforeAvatarUpload"
      :limit="100"
      :on-exceed="handleExceed"
      :file-list="fileList"
      :list-type="isBtn"
      :multiple="false"
    >
      <slot name="upbtn">
        <i class="el-icon-plus"></i>
        <div slot="tip" class="logoTip">
          {{
            upTip || "尺寸：200*200像素; 格式：jpg,jpeg,png; 大小：建议小于1M。"
          }}
        </div>
      </slot>
    </el-upload>
  </div>
</template>

<script>
  import { getEnToken } from "@/utils/accessToken";
  import { apiUrl } from "@/config/settings";
  import { uploadToken, UploadDel } from "@/api/common";
  export default {
    props: {
      multiple: {
        type: Boolean,
        default: false,
      },
      imgHeight: {
        type: Number,
        default: 750,
      },
      limit: {
        type: Number,
        default: 1,
      },
      isBtn: {
        type: String,
        default: "picture-card",
      },
      upTip: {
        type: String,
        default: "",
      },
      fileList: {
        type: Array,
        default: () => {
          return [];
        },
      },
      // 是否请求删除接口
      trueDel: {
        type: Boolean,
        default: true,
      },
    },
    data() {
      return {
        img_url: apiUrl.QINIU_URL,
        formData: "",
        loading: false,
        pic_model_show: false,
        QiniuData: {
          key: "", // 图片名字处理
          token: "", // 七牛云token
        },
        domain: apiUrl.QINIU_UP, // 七牛云的上传地址（华南区）
        uploadPicUrl: "", // 提交到后台图片地址
      };
    },
    mounted() {
      // this.getQiniuToken()
    },
    methods: {
      // 移除图片 请求七牛云接口
      async handleRemove(file, fileList) {
        let urlArr = "";
        if (!file.response) {
          urlArr = file.url.split("/");
        } else {
          urlArr = file.response.key.split("/");
        }
        const nameSlice = urlArr[urlArr.length - 6];
        let name = "";
        if (urlArr[urlArr.length - 1] === "750") {
          name = nameSlice.slice(0, nameSlice.indexOf("?"));
        } else {
          name = urlArr[urlArr.length - 1];
        }

        let key = `${getEnToken()}/${name}`;
        if (this.trueDel) {
          const data = await UploadDel({
            bucket: apiUrl.QINIU_KEY,
            key: key,
          });

          this.uploadPicUrl = "";
          this.$emit("handleRemove", file, fileList);
        } else {
          this.uploadPicUrl = "";
          this.$emit("handleRemove", file, fileList);
        }
      },
      // 文件超出个数限制时的钩子
      handleExceed(files, fileList) {
        this.$message.warning(
          `当前限制选择 ${this.limit} 张图片，如需更换，请删除上一张图片在重新选择！`
        );
      },
      async beforeAvatarUpload(file) {
        const isPNG = file.type === "image/png";
        const isJPEG = file.type === "image/jpeg";
        const isJPG = file.type === "image/jpg";
        const isLt2M = file.size / 1024 / 1024 < 1;

        if (!isPNG && !isJPEG && !isJPG) {
          this.$message.error("上传图片只能是 jpg、png、jpeg 格式!");
          return;
        }
        // if (!isLt2M) {
        //   this.$message.error('上传图片大小不能超过 1MB!')
        //   return false
        // }
        // 添加时间戳，防止同名图片上传和删除出错
        const nowTime = new Date().getTime();

        this.QiniuData.key = `${getEnToken()}/${nowTime}${file.name}`;
        // console.log(this.QiniuData.key)
        // return
        this.$emit("beforeUpload", file);
        await this.getQiniuToken(this.QiniuData.key);
      },
      // 上传成功
      uploadSuccess(response, file, fileList) {
        const uploadPicUrlY = `${this.img_url}/${response.key}`;
        const fileListY = fileList.map((item) => {
          if (item.response) {
            item.response = {
              ...item.response,
              key: item.response.key,
            };
          }
          return {
            ...item,
          };
        });
        this.$emit("uploadSuccess", uploadPicUrlY, response, file, fileListY);
      },
      uploadError(erro, file, fileList) {
        this.$message({
          message: "上传出错，请重试！",
          type: "error",
          center: true,
        });
      },
      beforeRemove(file, fileList) {
        // return this.$confirm(`确定移除 ${ file.name }？`);
      },
      // 请求后台拿七牛云token
      async getQiniuToken(key) {
        const data = await uploadToken({
          bucket: apiUrl.QINIU_KEY,
          key: key,
        });

        this.QiniuData.token = data.data;
      },
    },
  };
</script>
<style scoped>
  .logoTip {
    font-size: 12px;
  }
</style>
