<template>
  <div>
    <input
      ref="inputer"
      :accept="accept"
      :multiple="false"
      class="fileUp"
      type="file"
      name="file"
      @change="handleChange($event)"
    />
  </div>
</template>

<script>
import urlConfig from "@/apis/url-config";
import { getToken } from "@/utils/auth";
//Uploadcondition 用于判断个性化文件 //返回 false 就不会上传文件
//UploadErrorEvent 上传成功
//UploadErrorEvent 上传失败

export default {
  name: "Upload",
  props: {
    //@reject 默认值
    accept: String, //上传文件类型
    multiple: Boolean, //暂时没有用
    uploadcondition: {
      type: Function,
      default: null,
    },
  },
  data() {
    return {};
  },
  methods: {
    handleChange(event) {
      let that = this;
      let inputDOM1 = this.$refs.inputer;
      const files = inputDOM1.files;
      if (files.length === 0) return;
      //   that.$emit("UploadfilesEvent", files[0]);
      if (!this.uploadcondition(files[0])) {
        that.$refs.inputer.value = "";
        return false;
      }
      const file = files[0];
      let form = new FormData();
      form.append("image", file);
      form.append("token", getToken());
      axios
        .post(`${urlConfig.baseURL}admin/upload`, form)
        .then((res) => {
          if (res && res.data && res.status === 200 && res.data.data) {
            let data = res.data.data;
            //${urlConfig.baseURL}
            that.$emit("UploadSuccessEvent", {
              url: `${data[0]}`,
            });
          } else {
            that.$emit("UploadErrorEvent");
          }
        })
        .catch((error) => {
          that.$emit("UploadErrorEvent");
        });
    },
  },
};
</script>
<style lang="scss" scoped>
.fileUp {
  opacity: 0;
  width: 100%;
  height: 100%;
  outline: none;
  position: absolute;
  top:0;
  left:0;
  &:hover{
    cursor: pointer;
  }
}
</style>
