<template>
  <el-upload
    class="upload-demo"
    ref="FileUpload"
    drag
    :file-list="fileList"
    action="#"
    :http-request="uploadFile"
    :headers="myHeaders"
    :on-success="onSuccess"
    :limit="2"
    :on-remove="onRemove"
    :on-error="onError"
    :on-progress="onProgress"
  >
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
    <div
      class="el-upload__tip"
      slot="tip"
      style="color: #f56c6c; font-weight: 600"
    >
      {{ placeholder }}
    </div>
  </el-upload>
</template>

<script>
import { getToken } from "@/utils/auth";
import { MessageBox, Message } from "element-ui";

export default {
  name: "FileUpload",
  props: {
    fileUrl: {
      type: String,
      default: "",
    },
    placeholder: {
      type: String,
      default: "请上传 文件，建议大小在2M以内",
    },
  },
  data() {
    return {
      baseImgUrl: process.env.VUE_APP_BASE_IMG_URL,
      uploadUrl: process.env.VUE_APP_BASE_UPLOAD_API,
      myHeaders: {
        token: getToken(),
      },
      fileList: [],
      fileUploadLoading: false,
      tempUrl: "",
    };
  },
  computed: {},
  watch: {
    fileUrl: {
      handler(newVal, oldVal) {
        if (newVal) {
          this.fileList = [
            {
              name: newVal,
              url: this.baseImgUrl + newVal,
            },
          ];
          this.tempUrl = newVal;
        }
      },
      deep: true,
    },
  },
  created() {
    if (this.fileUrl) {
      this.fileList = [
        {
          name: this.fileUrl,
          url: this.baseImgUrl + this.fileUrl,
        },
      ];
      this.tempUrl = this.fileUrl;
    }
  },
  methods: {
    uploadFile(file) {
      console.log(1111111111, file);

      var formData = new FormData();
      formData.append("file", file.file);
      formData.append("type", "local");
      formData.append("pid", "1422");

      console.log(2222222222222, formData);
      this.fileUploadLoading = false;

      $.ajax({
        // Axios.create({
        type: "POST",
        // method: "POST",
        data: formData,
        url: this.uploadUrl + "upload",
        dataType: "json",
        async: true,
        cache: false,
        contentType: false,
        processData: false,
        success: (res) => {
          if (res.code != 900) {
            this.$message({
              message: res.message,
              type: "error",
            });
            this.fileUploadLoading = false;
            return;
          }
          console.log(res.data);

          this.tempUrl = res.data.local;
          this.fileList = [
            {
              name: this.tempUrl,
              url: this.baseImgUrl + this.tempUrl,
            },
          ];
          file.url = this.baseImgUrl + this.tempUrl;
          this.fileUploadLoading = false;

          // if (file.data.key == "icon") {
          //   this.hideIconImg = true;
          //   this.editInfo.icon = this.imgUrl + res.data.local;
          //   this.iconList = [
          //     {
          //       name: file.file.name,
          //       url: this.imgUrl + res.data.local,
          //     },
          //   ];
          //   this.iconUploadLoading = false;
          // } else {
          //   this.hideInfoImg = true;
          //   this.editInfo.info = this.imgUrl + res.data.local;
          //   this.infoList = [
          //     {
          //       name: file.file.name,
          //       url: this.imgUrl + res.data.local,
          //     },
          //   ];
          //   this.infoUploadLoading = false;
          // }
        },
      });
    },


    onSuccess(res, file, fileList) {
      if (res.code !== 900) {
        if (res.code === 1001) {
          // to re-login
          MessageBox.confirm("登录态已过期，请重新登录", "是否登出", {
            confirmButtonText: "重新登录",
            cancelButtonText: "取消",
            type: "warning",
          }).then(() => {
            store.dispatch("user/resetToken").then(() => {
              location.reload();
            });
          });
        } else {
          Message({
            message: res.message || "Error",
            type: "error",
            duration: 5 * 1000,
          });
        }
        this.$refs.FileUpload.uploadFiles = [];
        this.fileUploadLoading = false;
        return;
      }
      this.fileUploadLoading = false;
      this.tempUrl = this.setStyle(file);
      this.fileList = [
        {
          name: this.tempUrl,
          url: this.baseImgUrl + this.tempUrl,
        },
      ];
      file.url = this.baseImgUrl + this.tempUrl;
    },
    onRemove(file, fileList) {
      this.$refs.FileUpload.uploadFiles = [];
      this.tempUrl = "";
    },
    onError(err, file, fileList) {
      console.log(err, file, fileList);
    },
    onProgress(event, file, fileList) {
      this.fileUploadLoading = true;
    },
    setStyle(file) {
      var dataArr = [];
      dataArr.push(file.response.data.local);
      return dataArr.toString();
    },
  },
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.upload-demo {
  .el-upload-list {
    width: 360px !important;
  }
}
</style>
