<template>
  <te-file-list :files="files" @open="open" @upload="upload"></te-file-list>
</template>
<script>
export default {
  data() {
    return {
      files: [],
    };
  },
  watch: {
    $route() {
      this.$theia.menu.syncAddMenuItem = this.addItem;
      this.$theia.menu.labelChanged = this.labelChanged;
      this.loadFiles();
    },
  },
  created() {
    this.$theia.menu.syncAddMenuItem = this.addItem;
    this.$theia.menu.labelChanged = this.labelChanged;
    this.loadFiles();
  },
  methods: {
    open(file) {
      window.open(this.$theia.env.getApiHost() + "/preview/file/" + file.dpath);
    },
    labelChanged(v) {
      let item = this.$theia.menu.getSelectedMenuItem();
      let that = this;
      let opath = item.params;
      item.params = item.parent.name + "|" + v;
      let path = "/rename/" + opath + "/" + item.params;
      this.$theia.http.post(path, {}).then(() => {
        that.$router.push({
          path: item.path,
          query: { q: item.params },
        });
      });
    },
    addItem(item) {
      if (!item.icon) {
        item.icon = "fa fa-pencil-square-o";
      }
      item.params = item.parent.params + "|" + item.name;
      let that = this;
      this.$theia.http.post("/create/" + item.params, {}).then(() => {
        that.$router.push({
          path: item.path,
          query: { q: item.params },
        });
      });
    },
    upload(files) {
      if (files.length == 0) {
        return;
      }
      let that = this;
      for (let i = 0; i < files.length; i++) {
        let param = new FormData();
        param.append("path", that.$route.query.q);
        param.append("file", files[i], files[i].name);
        that.$theia.http.upload("/upload/file", param).then(() => {
          that.loadFiles();
        });
      }
    },
    loadFiles() {
      let that = this;
      this.$theia.http
        .post("/list/file", { dir: that.$route.query.q })
        .then((res) => {
          that.files = res;
        });
    },
  },
};
</script>
<style>
</style>