<template>
  <div>
    <el-upload
      :disabled="disable"
      ref="upload"
      :http-request="upload"
      class="upload-demo"
      :file-list="value"
      list-type="picture-card"
      :on-remove="removeFile"
      :on-exceed="fileExceed"
      :before-upload="fileLimitFn"
      :limit="limit"
      :on-success="fileSuccess"
      :on-error="fileError"
      :on-preview="handlePreview"
      action="#"
      multiple
    >
      <!-- <el-button size="small" type="primary" icon="el-icon-upload"
        >点击上传</el-button
      > -->
      <i class="el-icon-plus avatar-uploader-icon"></i>
      <div class="el-upload__tip" slot="tip">
        <!-- <gaopaiyi @input="baseFileData"></gaopaiyi> -->
        {{ tip }}
      </div>
    </el-upload>

    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <el-image
        fit="contain"
        :src="url"
        style="width: 100%; margin: 20px auto"
      />
    </el-dialog>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";

import axios from "axios";
//import gaopaiyi from "./gaopaiyi.vue";
import { config } from "@/utils/request";

export default {
  name: "FileUpload",
  components: {},
  props: {
    data: {
      type: Array,
      require: true,
      default: () => {
        return [];
      },
    },
    fileType: {
      type: String,
      default: () => {
        return "img";
      },
    },
    fileSize: {
      type: Number,
      default: () => {
        return 50;
      },
    },
    limit: {
      type: Number,
      default: () => {
        return 10;
      },
    },
    disable: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
    needValid: {
      type: Boolean,
      default: () => {
        return false;
      },
    },
  },
  data() {
    return {
      progressFlag: true,
      dialogImageUrl: "",
      dialogVisible: false,
      imgType: ["jpg", "jpeg", "png", "gif"],
      fileList: [],
      url: "",
    };
  },
  computed: {
    tip() {
      return `支持上传${
        this.fileType == "all"
          ? "任意格式"
          : this.fileType == "img"
          ? "图片类型"
          : "非图片类型"
      }文件，且单个文件不能超过${this.fileSize}MB，最多上传${this.limit}个文件`;
    },
    value: {
      get() {
        return this.data;
      },
      set(val) {
        this.$emit("update:data", val);
      },
    },
  },
  methods: {
    // 文件上传操作
    upload(file) {
      let formData = new FormData();
      formData.append("file", file.file);
      axios
        .post(`${config.proxy}/admin-api/file/uploadImg`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
            Authorization: getToken() ? "Bearer " + getToken() : "",
          },
          onUploadProgress: (progressEvent) => {
            let percent =
              ((progressEvent.loaded / progressEvent.total) * 100) | 0;
            //调用onProgress方法来显示进度条，需要传递个对象 percent为进度值
            file.onProgress({ percent: percent });
          },
        })
        .then((res) => {
          if (res.data.code == 200) {
            file.onSuccess(res.data);
          } else {
            file.onError(res.data);
          }
        })
        .catch((error) => {
          file.onError(error);
        });
    },
    // 文件移除操作
    removeFile(file, fileList) {
      this.value = fileList;
      this.needValid ? this.$emit("fileValid") : "";
    },
    chargeImg(name) {
      let type = name
        ? name.substring(name.lastIndexOf(".") + 1).toLowerCase()
        : "";
      return this.imgType.includes(type);
    },
    // 上传前的限制
    fileLimitFn(file) {
      const fileSize = file.size / 1024 / 1024;
      // 类型限制
      if (this.fileType == "img" && !this.chargeImg(file.name)) {
        this.$notify.warning(`非图片类型的文件不支持上传`);
        return false;
      } else if (this.fileType == "file" && this.chargeImg(file.name)) {
        this.$notify.warning(`图片类型的文件不支持上传`);
        return false;
      }
      // 大小限制
      if (fileSize > this.fileSize) {
        this.$notify.warning(`${file.name}文件大小不得超过${this.fileSize}MB`);
        return false;
      }
    },
    // 文件超出个数限制
    fileExceed() {
      this.$notify.warning(`允许上传的最大个数${this.limit}个`);
    },
    // 文件上传成功
    fileSuccess(responese, file, fileList) {
      console.log(responese, file, fileList, "fileSuccess");
      // if (file.uid) {
      //   this.$fileReady[file.uid] = "success";
      //   this.$store.commit("utils/SET_FILEREADY", this.$fileReady);
      // }
      file.url = responese.data;
      delete file.raw;
      delete file.percentage;
      delete file.response;
      delete file.size;
      this.value = fileList;
    },
    // 文件上传失败
    fileError(res, file) {
      if (file.uid) {
        delete this.$fileReady[file.uid];
        // this.$store.commit("utils/SET_FILEREADY", this.$fileReady);
      }
      this.$notify.warning("上传文件失败");
    },
    // 文件预览
    handlePreview(file) {
      this.url = file.url;
      this.dialogVisible = true;
    },
  },
};
</script>
<style>
.upload-demo .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.upload-demo .el-upload:hover {
  border-color: #409eff;
}
.upload-demo .avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100% !important;
  height: 100% !important;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
