<template>
  <el-upload
    drag
    action="/apaas/static/file/upload"
    :data="{
      directory: 'sdk',
      uniqueCode: false,
    }"
    :file-list="fileList"
    :before-upload="beforeUpload"
    :on-success="uploadSuccess"
  >
    <i class="el-icon-upload"></i>
    <div class="el-upload__text">
      <p>将文件拖到此处，或<em>点击上传</em></p>
      <p class="upload_tip" v-if="tip" v-text="tip"></p>
    </div>
  </el-upload>
</template>

<script>
export default {
  model: {
    prop: "url",
    event: "change",
  },
  props: {
    url: {
      type: String,
      default: "",
    },
    tip: {
      type: String,
      default: "",
    },
  },
  computed: {
    fileList() {
      let list = [];

      if (this.url) {
        let path = this.url.split("/");

        list = [
          {
            name: path[path.length - 1],
            url: this.url,
          },
        ];
      }

      return list;
    },
  },
  methods: {
    getFileType(fileName) {
      let startIndex = fileName.lastIndexOf(".");

      if (startIndex != -1) {
        return fileName
          .substring(startIndex + 1, fileName.length)
          .toLowerCase();
      } else {
        return "";
      }
    },
    beforeUpload(file) {
      const filtType = this.getFileType(file.name);

      if (filtType === "rar" || filtType === "zip") {
        return true;
      } else {
        this.$message.error("仅支持rar和zip格式!");
        return false;
      }
    },
    uploadSuccess({ data }) {
      this.$emit("change", data);
    },
  },
};
</script>

<style scoped>
.upload_tip {
  font-size: 12px;
  line-height: 20px;
  color: #a9aec0;
}
</style>
