<template>
  <GenericManager
    :uri="resource_uri"
    object_name="扫码记录"
    :visible_fields="visible_fields"
    :list_fields="list_fields"
    :editable_fields="['labels']"
    no_delete=1
    no_create=1
    show_search=1
    :actions="actions"
    >
    <div>
      <a href="/scan-data-export" class="btn btn-sm btn-info" id="batch-export-btn">批量导出</a>
    </div>
  </GenericManager>
  <Modal ref="image_modal">
    <img :src="show_image_url" class="w-100" />
  </Modal>
</template>

<script>
export default {
  name: 'Templates',
  props: [],
  components: {
  },
  data: function () {
    return {
      resource_uri: "/api/v1/scan-data/",
      show_image_url: null,
      admin_actions: [
        {
          handler: this.handle_show_image,
          icon: 'image',
          title: '查看图像',
        },
        {
          handler: (row) => { this.toggle_label(row, "pos"); },
          icon: 'plus',
          title: '正样本',
          classes: "btn-success"
        },
        {
          handler: (row) => { this.toggle_label(row, "neg"); },
          icon: 'minus',
          title: '负样本',
          classes: "btn-danger"
        },
      ],
    };
  },
  computed: {
    list_fields: function() {
      var fs = ['id', 'succeeded', 'datetime', 'location', 'product__name', 'code'];
      if (this.$root.is_admin) {
        fs.push('labels');
        fs.push('phone_model');
      }
      return fs;
    },
    visible_fields: function() {
      var fs = ['succeeded', 'datetime', 'location', 'product__name', 'code', 'phone_model'];
      if (this.$root.is_admin) {
        fs.push('ip');
        fs.push('message');
        fs.push('client_log');
        fs.push('labels');
      }
      return fs
    },
    actions: function() {
      if (this.$root.is_admin) {
        return this.admin_actions;
      }
      return [];
    },
  },
  methods: {
    handle_show_image: function(row) {
      this.show_image_url = '/api/v1/oss-image/?token=' + this.$root.token + "&name=" + row.image;
      this.$refs.image_modal.show();
    },
    async toggle_label(row, label) {
      var labels = row.labels.trim().split(",").filter((x) => x.length);
      var oi = labels.indexOf(label);
      if (oi < 0) {
        labels.push(label);
      } else {
        labels.splice(oi, 1);
      }
      var newlabels = labels.join(",");
      console.log(newlabels);
      await this.$root.api_patch("/api/v1/scan-data/" + row.id + "/", {
        "labels": newlabels,
      });
      row.labels = newlabels;
    },
  },
  mounted() {
  },
}
</script>

<style scoped>
</style>

