<template>
  <Modal ref="modal" close_only=1>
    <div v-if="job">
      <div v-if="job.status == 'created'" class="alert alert-info">
        任务准备中...
      </div>
      <div v-if="job.status == 'running'">
        <div class="alert alert-info">
          正在执行...
        </div>
        <CProgress class="my-3">
          <CProgressBar :value="percent" />
        </CProgress>
      </div>
      <div v-if="job.status == 'done'">
        <div class="alert alert-success">
          已完成
        </div>
        <div>
          <button v-if="job.output" class="btn btn-primary my-2" @click="download" id="download-btn">下载</button>
        </div>
      </div>
      <div v-if="job.status == 'error'">
        <div>
          执行失败
        </div>
        <div v-if="job.message" class="alert alert-danger">
          {{ job.message }}
        </div>
      </div>
    </div>
    <div v-else>
      正在读取...
    </div>
  </Modal>
</template>

<script>

export default {
  name: 'JobModal',
  props: [],
  components: {
  },
  data: function () {
    return {
      job: null,
      id: null,
    };
  },
  computed: {
    percent: function() {
      return Math.floor(this.job.progress);
    },
  },
  methods: {
    refresh: async function() {
      var r = await this.$root.api_get('/api/v1/job/' + this.id + '/');
      this.job = r.data;
      var st = this.job.status;
      if (st == 'running' || st == 'created') {
        setTimeout(this.refresh, 1000);
      }
    },
    show: function(id) {
      this.id = id;
      this.refresh();
      this.$refs.modal.show();
    },
    download: function() {
      window.open('/api/v1/job-output/?token=' + this.$root.token + '&id=' + this.id, '_blank');
    }
  },
  mounted() {
  },
}
</script>

<style scoped>
</style>

