<template>
  <div>
    <h2>特征提取系统 - 导入图像</h2>
    <hr>
    <div class="fade-in">
      <a href="https://fkv5y6aq69.feishu.cn/docx/PHtAdSIGWo8VM9xIC2vcE9AOnEe" target="_blank">
        操作说明
      </a>
      <div class="my-2">
        <label>导入批次命名</label>
        <input class="form-control" type="text" v-model="batch_name" />
      </div>
      <div v-if="loading">
        正在获取USB设备列表...
        <CSpinner class="d-block" />
      </div>
      <div v-else class="my-2">
        <div class="input-group">
          <select class="form-control" v-model="selected_usb_dev">
            <option v-for="us, i in usb_storages" :key="i" :value="us.devname">
            [{{ us.devname }}] {{us.uuid}} {{ us.model }} {{ us.serial }}
            {{ Math.round(us.size / 1024 / 1024 / 1024) }}GB
            </option>
          </select>
          <button class="btn btn-secondary" @click="reload_usb">
            <font-awesome-icon icon="refresh" class="me-1"/>
            刷新
          </button>
        </div>
        <div v-if="selected_usb_files.length" class="my-2">
          待导入的文件夹：
          <CBadge v-for="sf,i in selected_usb_files" :key="i" color="info" class="me-2">{{sf}}</CBadge>
        </div>
        <div class="alert alert-primary" v-if="job_estimation || estimating">
          <p>任务预览</p>
          <CSpinner v-if="estimating" />
          <div v-else>
            总文件个数：{{ job_estimation.total_file_count }}<br>
            总文件大小：{{ job_estimation.total_file_mb }}MB<br>
            预计完成时间：{{ job_estimation.estimate_minutes }}分钟
          </div>
        </div>
        <div class="my-2">
          <button class="btn btn-success opration me-2" @click="show_usb_selector">选择文件夹</button>
          <button class="btn btn-primary me-2" :disabled="!can_start" @click="start_import(false)">开始导入</button>
          <button class="btn btn-info me-2" :disabled="selected_usb_files.length != 1" @click="start_import(true)">从ZIP导入</button>
          <button class="btn btn-secondary" :disabled="estimating || !can_start" @click="estimate_job">
            估计时间
          </button>
        </div>
      </div>
    </div>
    <FileSelector ref="usb_selector" multiple=1 :fsdriver="usb_fs" @ok="usb_ok">
    </FileSelector>
  </div>
</template>

<script>
import FileSelector from '@/components/file-selector.vue';

export default {
  name: 'ImportView',
  props: [],
  components: {
    FileSelector
  },
  data: function () {
    return {
      showhelp: false,
      loading: true,
      usb_storages: [],
      selected_usb_dev: null,
      selected_usb_files: [],
      batch_name: this.gen_batch_name(),
      task_preview: {},
      usb_fs: {
        list: this.usb_list,
      },
      job_estimation: null,
      estimating: false,
    };
  },
  computed: {
    can_start() {
      return this.batch_name.length > 0 && this.selected_usb_files.length > 0;
    },
  },
  methods: {
    gen_batch_name() {
      return this.time_slug() + '文件夹';
    },
    async estimate_job() {
      this.estimating = true;
      var total_files = 0;
      var total_bytes = 0;
      for (var path of this.selected_usb_files) {
        var r = await this.$root.estor_call("GetDirStat", {
          devname: this.selected_usb_dev,
          subdir: path,
        });
        var ds = r.data.data;
        total_files += ds.nfiles;
        total_bytes += ds.size;
      }

      var nfiles_per_second = 10;
      var bytes_per_second = 10 * 1024 * 1024;
      var et = Math.max(total_files / nfiles_per_second, total_bytes / bytes_per_second);
      this.job_estimation = {
        total_file_count: total_files,
        total_file_mb: Math.ceil(total_bytes / 1024 / 1024),
        estimate_minutes: Math.ceil(et / 60),
      };
      this.estimating = false;
    },
    async usb_list(path) {
      if (path.startsWith("/")) {
        path = path.substr(1);
      }
      var r = await this.$root.estor_call("ListExtFiles", {
        devname: this.selected_usb_dev,
        subdir: path,
      });
      return r.data.data;
    },
    time_slug() {
      var t = new Date();
      return t.toLocaleString("zh-CN").replaceAll(/[ :/]/g, "-");
    },
    async start_import(unzip) {
      var batch_dir = this.batch_dir(this.batch_name);
      await this.set_batch_state(this.batch_name, {
        'status': 'new',
      });
      var r = await this.$root.estor_call("CreateJob", {
        name: "导入-" + this.batch_name,
        spec: {
          type: "Import",
          args: {
            space: this.$root.estor_space,
            ext_devname: this.selected_usb_dev,
            files: this.selected_usb_files,
            dest_prefix: batch_dir + "/import/",
            recursive: true,
            concurrency: 16,
            unzip,
          },
        },
      });
      console.log(r.data.data);
      await this.set_batch_state(this.batch_name, {
        status: 'importing',
        job: r.data.data,
      });
      this.$router.push("/estor/jobs");
    },
    show_usb_selector: function(){
      this.$refs.usb_selector.show();
    },
    usb_ok: function(selection){
      this.selected_usb_files = selection
    },
    async reload_usb() {
      this.loading = true;
      await this.$root.estor_call("ScanDisks");
      var r = await this.$root.estor_call("ListExtDisks");
      this.usb_storages = r.data.data;
      if (this.usb_storages.length) {
        this.selected_usb_dev = this.usb_storages[0].devname;
        this.usb_list("/");
      }
      this.loading = false;
    },
  },
  mounted() {
    this.reload_usb();
  },
}
</script>

<style scoped>
</style>
