<template>
  <el-upload
    ref="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: "",
    },
  },
  data() {
    return {
      preUrl: "",
    };
  },
  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") {
        this.preUrl = this.url;
        return true;
      } else {
        this.$message.error("仅支持rar和zip格式!");
        return false;
      }
    },
    uploadSuccess({ data }) {
      this.$emit("change", data);

      // 替换文件后要把旧文件删除掉
      if (this.preUrl) {
        this.$http
          .delete("/apaas/static/file/delete", {
            params: {
              url: this.preUrl,
            },
          })
          .then(({ data }) => {
            if (data.success === 1) {
              this.preUrl = "";
            }
          });
      }
    },
  },
};
</script>

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