<template>
  <div>
    <el-upload
      :headers="headersConfig"
      :action="actionUri"
      :file-list="fileList"
      :on-success="handleSuccess"
      :on-change="handleChange"
      :show-file-list="showFileList"
      :before-upload="beforeUpload"
      :disabled="disabled"
      :accept="accept"
      list-type="picture"
    >
      <el-button type="primary" :disabled="disabled">点击上传</el-button
      ><span
        v-if="checkWidth"
        class="size_tips"
        style="  color: red;
    font-size: 14px; margin-left: 10px;"
        >请上传{{ width }}*{{ height }}尺寸的图片</span
      >
      <div
        v-if="checksize && showTip"
        slot="tip"
        style="margin-left:15px"
        class="el-upload__tip"
      >
        {{ tip + size / 1024 + "M" }}
      </div>
    </el-upload>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";

export default {
  props: {
    // 限制文件个数
    fileCount: {
      type: Number,
      default: 1
    },
    // 控制是否显示已上传文件列表
    showFileList: {
      type: Boolean,
      default: false
    },
    // 控制上传按钮
    disabled: {
      type: Boolean,
      default: false
    },
    // 是否校验上传图片尺寸
    checkWidth: {
      type: Boolean,
      default: false
    },
    // 限制上传尺寸宽度
    width: {
      type: Number,
      default: 250
    },
    // 限制上传尺寸长度
    height: {
      type: Number,
      default: 250
    },
    // 是否校验上传图片大小
    checksize: {
      type: Boolean,
      default: true
    },
    // 限制上传图片大小
    size: {
      type: Number,
      default: 1024 * 10
    },
    // 限制上传文本类型
    accept: {
      type: String,
      default: ".jpg,.png,.gif"
    },
    // 是否显示tip
    showTip: {
      type: Boolean,
      default: true
    },
    // tip文本
    tip: {
      type: String,
      default: "只能上传jpg/png文件，且不超过"
    },
    // 校验上传文件格式
    imgType: {
      type: Array,
      default: () => {
        return ["image/jpeg", "image/png", "image/gif"];
      }
    }
  },

  data() {
    return {
      fileList: [],
      fileWidth: 0,
      fileHeight: 0,
      // actionUri: `${config.H5WebUrl}/uploadFiles`
      actionUri: `/admin/common/file/upload`,
      headersConfig: {
        Authorization: "Bearer " + getToken(),
        "X-File-Size": 0
      }
    };
  },

  methods: {
    handleSuccess(response) {
      if (response.iRet === -1) {
        this.$message.error(response.message);
      } else {
        this.$emit(
          "imgUrlChange",
          response.data.url,
          this.fileHeight,
          this.fileWidth
        );
      }
    },
    handleChange(file, fileList) {
      this.fileList =
        fileList.length > 1 ? fileList.splice(-this.fileCount) : fileList;
    },

    beforeUpload(file) {
      const imgType = file.type;
      // 校验上传格式
      let isType = true;
      let isLtSize = true;
      let isSize = true;
      // 校验图片类型
      if (!this.imgType.includes(imgType)) {
        isType = false;
        this.$message.error("非法图片格式，不允许上传");
      }
      // 校验上传图片大小
      if (this.checksize) {
        // 校验上传图片大小
        isLtSize = file.size / 1024 / 1024 < this.size / 1024;
        const ltSizeText =
          this.size / 1024 >= 1 ? `${this.size / 1024}M` : `${this.size}KB`;
        if (!isLtSize) {
          this.$message.error(`上传图片大小不能超过 ${ltSizeText}!`);
        }
      }
      // 获取图片尺寸

      const reader = new FileReader();
      reader.onload = e => {
        const img = new Image();
        img.onload = () => {
          // 在这里可以获取到图片的宽度和高度
          this.fileWidth = img.width;
          this.fileHeight = img.height;
          return true;
        };
        img.src = e.target.result;
      };
      // 以DataURL的形式读取文件
      reader.readAsDataURL(file);

      // 校验图片尺寸
      if (this.checkWidth) {
        const width = this.width;
        const height = this.height;
        isSize = new Promise(function(resolve, reject) {
          // window对象，将blob或file读取成一个url
          const _URL = window.URL || window.webkitURL;
          const img = new Image();
          // image对象的onload事件，当图片加载完成后执行的函数
          img.onload = function() {
            const valid = img.width === width && img.height === height;
            valid ? resolve() : reject(new Error("error"));
          };
          img.src = _URL.createObjectURL(file);
        }).then(
          () => {
            return file;
          },
          () => {
            this.$message.error(
              `上传失败，图片尺寸不符，请上传${width}*${height}尺寸的图片。`
            );
            return Promise.reject(new Error("error"));
          }
        );
      }
      return isType && isLtSize && isSize;
    }
  }
};
</script>
