<template>
  <div class="app-container">
    <el-alert title="字节码文件在线转换" type="success"></el-alert>
    <div style="margin: 10px 0px">
      <el-form>
        <el-form-item>
          <el-upload
            name="binfile"
            drag
            multiple
            ref="upload"
            action="null"
            :auto-upload="false"
            :http-request="handleUploadFile"
            :on-remove="handleUploadRemove"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">请选择evue文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item>
          <el-button @click="uploadFile">开始上传</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import { postByteCodeFile } from "@/api/app-store";

export default {
  name: "ByteCodeFile",
  data() {
    return {
      fileList: [],
    };
  },
  methods: {
    createFile(content, filename) {
      const a = document.createElement("a");
      const blob = new Blob([content]);
      const url = window.URL.createObjectURL(blob);
      a.href = url;
      a.download = filename;
      a.click();
      window.URL.revokeObjectURL(url);
    },
    handleUploaded(response) {
      if (response.code === 200) {
        this.downloadFile(response);
      } else {
        this.$message.warning(response.message);
      }
    },
    handleUploadFile(file) {
      this.fileList.push(file);
    },
    handleUploadRemove(file, fileList) {
      console.log(fileList);
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i].uid == file.uid) {
          this.fileList.splice(i, 1);
          break;
        }
      }
    },
    downloadFile(result) {
      const a = document.createElement("a");
      a.download = result.data.filename;
      a.href = result.data.url;
      a.target = "";
      a.click();
    },
    uploadFile() {
      this.$refs.upload.submit();
      let formData = new FormData();
      this.fileList.forEach((item) => {
        formData.append("binfile", item.file);
      });
      postByteCodeFile(formData)
        .then((res) => {
          if (res.code === 200) {
            this.downloadFile(res);
          } else {
            this.$message.warning(res.message);
          }
        })
        .catch((err) => {
          this.$message.error(err.message);
        });
    },
  },
  mounted() {},
  created() {},
};
</script>
<style lang="scss" scoped>
.app-container {
  & > div.page-wrapper {
    margin: 10px 0px;
  }
}
</style>
