<template>
  <div>
    <gz-data-table
      form-key="adm-report-templates"
      data-list-key="ReportDataList"
      :show-select="false"
      :single-select="false"
      :reload="reload"
      data-cy="reportTemplatesTable"
    >
    </gz-data-table>
    <v-file-input
      v-model="uploadFiles"
      dense
      :label="$sock.t('Import')"
      accept=".ayrt"
      prepend-icon="$sockiFileUpload"
      multiple
      chips
    ></v-file-input>
    <v-btn
      v-if="uploadFiles.length > 0"
      :loading="uploading"
      color="primary"
      text
      @click="upload"
      >{{ $sock.t("Upload") }}</v-btn
    >
  </div>
</template>

<script>
const FORM_KEY = "adm-report-templates";
export default {
  data() {
    return {
      uploadFiles: [],
      rights: window.$gz.role.defaultRightsObject(),
      reload: false,
      uploading: false
    };
  },
  async created() {
    this.rights = window.$gz.role.getRights(window.$gz.type.Report);
    window.$gz.eventBus.$on("menu-click", clickHandler);
    generateMenu(this);
  },
  beforeDestroy() {
    window.$gz.eventBus.$off("menu-click", clickHandler);
  },
  methods: {
    async upload() {
      //similar code in wiki-control
      const vm = this;
      const fileData = [];
      for (let i = 0; i < vm.uploadFiles.length; i++) {
        const f = vm.uploadFiles[i];
        fileData.push({ name: f.name, lastModified: f.lastModified });
      }
      const at = {
        files: vm.uploadFiles,
        fileData: JSON.stringify(fileData)
      };
      try {
        vm.uploading = true;
        const res = await window.$gz.api.upload("report/upload", at);
        if (res.error) {
          window.$gz.errorHandler.handleFormError(res.error);
        } else {
          vm.uploadFiles = [];

          this.reload = !this.reload;
        }
      } catch (error) {
        window.$gz.errorHandler.handleFormError(error);
      } finally {
        vm.uploading = false;
      }
    }
  }
};

/////////////////////////////
//
//
function clickHandler(menuItem) {
  if (!menuItem) {
    return;
  }
  const m = window.$gz.menu.parseMenuItem(menuItem);
  if (m.owner == FORM_KEY && !m.disabled) {
    switch (m.key) {
      default:
        window.$gz.eventBus.$emit(
          "notify-warning",
          FORM_KEY + "::context click: [" + m.key + "]"
        );
    }
  }
}

//////////////////////
//
//
function generateMenu() {
  const menuOptions = {
    isMain: true,
    icon: "$sockiDraftingCompass",
    title: "ReportList",
    helpUrl: "adm-report-templates",
    menuItems: [],
    formData: {
      sockType: window.$gz.type.Report
    }
  };

  window.$gz.eventBus.$emit("menu-change", menuOptions);
}
</script>
