<template>
  <h2>生成序列码</h2>
  <hr>
  <CAlert color="danger" v-if="errmsg">
    {{ errmsg }}
  </CAlert>
  <div v-if="generating">
    <label>
      正在生成
      {{ gen_cur }} / {{ ncode }}
    </label>
    <CProgress class="mb-3">
      <CProgressBar :value="gen_percent" />
    </CProgress>
    <button class="btn btn-primary" @click="gen_cancel=true">取消</button>
  </div>
  <div v-else class="options">
    <div>
      <label>序列码数量</label>
      <input class="form-control" type="number" v-model="ncode"/>
    </div>
    <div>
      <button class="btn btn-primary" @click="gen">生成</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'GenCode',
  props: ['product_id', 'batch_id'],
  components: {
  },
  data: function () {
    return {
      ncode: 100,
      generating: false,
      gen_cur: 0,
      gen_percent: 0,
      gen_cancel: false,
      errmsg: null,
    };
  },
  computed: {
  },
  methods: {
    gen: async function() {
      if (this.ncode <= 0 || this.ncode > 100000000) {
        this.errmsg = '序列吗数量无效，请输入 1 - 100000000 的整数';
        return;
      }
      try {
        this.generating = true;
        this.gen_percent = 0;
        this.gen_cancel = false;
        this.errmsg = null;
        await this.do_gen();
        this.generating = false;
        this.$router.go(-1);
      } catch (e) {
        this.generating = false;
        this.errmsg = '生成失败';
      }
    },
    do_gen: async function() {
      var done = 0;
      this.gen_cur = 0;
      while (done < this.ncode && !this.gen_cancel) {
        var r = await this.$root.api_post("/api/v1/gen-code/", {
          'batch_id': this.batch_id,
          'num': this.ncode - done,
        });
        done += r.data.created;
        this.gen_cur = done;
        this.gen_percent = Math.floor(100 * done / this.ncode);
      }
    },
  },
  mounted() {
  },
}
</script>

<style scoped>
div.options > div {
  margin-top: 1rem;
}
</style>

