<template>
  <div>
    <div>
      <CButton @click="backup" color="success">备份</CButton>
    </div>
    <hr>
    <div>
      <input class="form-control w-50" type="file" ref="restorefile" />
      <CButton :disabled="restoring" @click="restore" color="warning">恢复</CButton>
      <div v-if="restoring" class="alert alert-info">
        正在恢复
      </div>
      <div v-if="restore_succeeded" class="alert alert-success">
        恢复成功
      </div>
      <div v-if="restore_failed" class="alert alert-danger">
        恢复失败
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'BackupRestore',
  props: [],
  components: {
  },
  data: function () {
    return {
      restoring: false,
      restore_succeeded: false,
      restore_failed: false,
    };
  },
  computed: {
  },
  methods: {
    backup: function() {
      window.open('/api/v1/backup/?token=' + this.$root.token, '_blank');
    },
    restore: async function() {
      var fs = this.$refs.restorefile.files;
      if (!fs.length) return;
      var f = fs[0];
      this.restoring = true;
      this.restore_succeeded = false;
      this.restore_failed = false;
      try {
        let fd = new FormData();
        fd.append('file', f);
        await this.$root.api_post("/api/v1/restore/", fd);
        this.restore_succeeded = true;
      } catch {
        this.restore_failed = true;
      } finally {
        this.restoring = false;
      }
    },
  },
  mounted() {
  },
}
</script>

<style scoped>
button {
  margin: 1rem 0;
}
</style>

