<template>
  <div>
    <div class="bulk-operations-container">


      <box variant="border" class="bulk-operations-box-container">
        <div class="bulk-operations-sub-container">

          <div class="bulk-operation-header">Export</div>
          <div class="bulk-operation-caption">type</div>
          <div class="bulk-operation-data">
            <radio-option name="export-type" value="templates" v-model="exportType">empty template</radio-option>
            <radio-option name="export-type" value="download" v-model="exportType">full data export</radio-option>
          </div>
          <div class="bulk-operation-caption">dataset</div>
          <div class="bulk-operation-data">
            <radio-option v-if="canModify('nodes')" name="export-dataset" value="NODE" v-model="exportDataset">nodes
            </radio-option>
            <radio-option v-if="canModify('rates')" name="export-dataset" value="COUNTRY_MATRIX"
                          v-model="exportDataset">kilometer rates
            </radio-option>
            <radio-option v-if="canModify('rates')" name="export-dataset" value="CONTAINER_RATE"
                          v-model="exportDataset">container rates
            </radio-option>
            <radio-option v-if="canModify('materials')" name="export-dataset" value="MATERIAL" v-model="exportDataset">
              materials
            </radio-option>
            <radio-option v-if="canModify('packaging')" name="export-dataset" value="PACKAGING" v-model="exportDataset">
              packaging
            </radio-option>
          </div>

          <div v-if="canModify('rates')" class="bulk-operation-caption">validity period</div>
          <div v-if="canModify('rates')" class="bulk-operation-data">
            <div class="period-select-container">
              <dropdown :options="periods"
                        emptyText="No property set available"
                        class="period-select"
                        placeholder="Select a property set"
                        v-model="selectedPeriod"
                        :disabled="!showValidityPeriod"
              ></dropdown>
            </div>
          </div>

          <div class="bulk-operation-action-footer">
            <basic-button @click="downloadFile" icon="download">Export</basic-button>
          </div>
        </div>
      </box>

      <box variant="border" class="bulk-operations-box-container">
        <div class="bulk-operations-sub-container">

          <div class="bulk-operation-header">Import</div>
          <div class="bulk-operation-caption">dataset</div>
          <div class="bulk-operation-data">
            <radio-option v-if="canModify('nodes')" name="import-dataset" value="NODE" v-model="importDataset">nodes
            </radio-option>
            <radio-option v-if="canModify('rates')" name="import-dataset" value="COUNTRY_MATRIX"
                          v-model="importDataset">kilometer rates
            </radio-option>
            <radio-option v-if="canModify('rates')" name="import-dataset" value="CONTAINER_RATE"
                          v-model="importDataset">container rates
            </radio-option>
            <radio-option v-if="canModify('materials')" name="import-dataset" value="MATERIAL" v-model="importDataset">
              materials
            </radio-option>
            <radio-option v-if="canModify('packaging')" name="import-dataset" value="PACKAGING" v-model="importDataset">
              packaging
            </radio-option>
          </div>

          <div class="bulk-operation-caption">file</div>
          <div class="bulk-operation-data">
            <div class="file-input-container">
              <label for="upload" class="file-button-label">
                Choose file
              </label>
              <input @change="inputFile" class="file-select-button" type="file" id="upload" name="upload"
                     accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"/>
            </div>

            <div id="selectedFile" class="selected-file" v-if="selectedFileName">{{ selectedFileName }}</div>

          </div>
          <div class="bulk-operation-action-footer">
            <basic-button @click="uploadFile" icon="upload" :disabled="!selectedFile">Import</basic-button>
          </div>
        </div>
      </box>

      <div class="bulk-operation-box-status-container">
        <div class="bulk-operation-status">
          <div class="bulk-operation-header">History</div>
          <div v-if="this.bulkOperationStore.getBulkOperations.length === 0" class="empty-container">No recent bulk
            operations
          </div>
          <bulk-operation v-else v-for="bulk in this.bulkOperationStore.getBulkOperations" :key="bulk.id"
                          :operation="bulk" @download="fetchFile"></bulk-operation>
        </div>
      </div>

    </div>
  </div>
</template>

<script>

import Box from "@/components/UI/Box.vue";
import BasicButton from "@/components/UI/BasicButton.vue";
import RadioOption from "@/components/UI/RadioOption.vue";
import performRequest, {performUpload, performDownload} from "@/backend.js";
import {config} from "@/config.js";
import Dropdown from "@/components/UI/Dropdown.vue";
import {mapStores} from "pinia";
import {useValidityPeriodStore} from "@/store/validityPeriod.js";
import {useBulkOperationStore} from "@/store/bulkOperation.js";
import BulkOperation from "@/components/layout/bulkoperation/BulkOperation.vue";
import logger from "@/logger.js";
import {useActiveUserStore} from "@/store/activeuser.js";
import {buildDate} from "@/common.js";

export default {
  name: "BulkOperations",
  components: {BulkOperation, Dropdown, RadioOption, BasicButton, Box},
  data() {
    return {
      exportType: "templates",
      exportDataset: "NODE",
      importDataset: "NODE",
      selectedFileName: null,
      selectedFile: null,
      fileBlob: null, // Blob im RAM gespeichert
      uploading: false,
      processId: null,
    }
  },
  props: {
    isSelected: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    async isSelected(newVal) {
      if (newVal === true && this.activeUserStore.allowRates)
        await this.validityPeriodStore.loadPeriods();
      await this.bulkOperationStore.manageStatus();
    }
  },
  computed: {
    ...mapStores(useValidityPeriodStore, useBulkOperationStore, useActiveUserStore),
    showValidityPeriod() {
      return this.exportType === "download" && (this.exportDataset === "COUNTRY_MATRIX" || this.exportDataset === "CONTAINER_RATE");
    },
    currentPeriod() {
      return this.validityPeriodStore.getCurrentPeriodId;
    },
    selectedPeriod: {
      get() {
        return this.validityPeriodStore.getSelectedPeriod
      },
      async set(value) {
        this.validityPeriodStore.setSelectedPeriod(value);
      }
    },
    periods() {
      const periods = [];

      const vp = this.validityPeriodStore.getPeriods;

      if ((vp ?? null) === null) {
        return null;
      }

      for (const p of vp) {
        const value = (p.state === "DRAFT") ? "DRAFT" : (p.state === "VALID") ? "CURRENT" : `${this.buildDate(p.start_date)} - ${this.buildDate(p.end_date)} ${p.state === "INVALID" ? "(INVALID)" : ""}`;
        const period = {id: p.id, value: value};


        periods.push(period);
      }

      return periods;
    }
  },
  methods: {
    canModify(role) {
      switch (role) {
        case "nodes":
          return this.activeUserStore.isSuper;
        case "rates":
          return this.activeUserStore.isSuper || this.activeUserStore.isFreight;
        case "materials":
          return this.activeUserStore.isSuper || this.activeUserStore.isMaterial;
        case "packaging":
          return this.activeUserStore.isSuper || this.activeUserStore.isPackaging;
      }
    },
    buildDate(date) {
      return buildDate(date, true);
    },
    async fetchFile(id) {
      logger.info(`Fetching file ${id}`);
      this.bulkOperationStore.downloadBulkFile(id);
    },
    async downloadFile() {
      if (this.exportType === "templates") {
        const fileName = `lcc_export_${this.exportType.toLowerCase()}_${this.exportDataset.toLowerCase()}.xlsx`;
        const url = `${config.backendUrl}/bulk/templates/${this.exportDataset}/`
        await performDownload(url, fileName);
      } else {
        const isCurrent = this.selectedPeriod === this.currentPeriod;
        await this.bulkOperationStore.scheduleDownload(this.exportDataset, isCurrent ? null : this.selectedPeriod);
      }
    },
    async inputFile(event) {
      const file = event.target.files[0];

      if (file) {
        try {
          // Datei sofort in den RAM laden als Blob
          this.fileBlob = await this.readFileAsBlob(file);

          // File-Objekt mit dem Blob erstellen, das den originalen Namen und Typ behält
          this.selectedFile = new File([this.fileBlob], file.name, {type: file.type});
          this.selectedFileName = file.name;

          logger.info(`File loaded into memory: ${file.name} (${(file.size / 1024).toFixed(2)} KB)`);
        } catch (error) {
          logger.error('Error reading file:', error);
          this.selectedFile = null;
          this.selectedFileName = null;
          this.fileBlob = null;
        }
      } else {
        this.selectedFile = null;
        this.selectedFileName = null;
        this.fileBlob = null;
      }

      // Input zurücksetzen, damit dieselbe Datei erneut ausgewählt werden kann
      event.target.value = '';
    },
    readFileAsBlob(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onload = (e) => {
          // ArrayBuffer in Blob konvertieren
          const blob = new Blob([e.target.result], {type: file.type});
          resolve(blob);
        };

        reader.onerror = (error) => {
          reject(error);
        };

        // Datei als ArrayBuffer lesen
        reader.readAsArrayBuffer(file);
      });
    },
    async uploadFile() {
      if (!this.selectedFile)
        return;

      const file = this.selectedFile;
      this.selectedFile = null;
      this.selectedFileName = null;
      await this.bulkOperationStore.scheduleUpload(this.importDataset, file);
    }
  }
}
</script>


<style scoped>

.empty-container {
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 1.6rem;
  flex: 1;
}

.bulk-operation-status {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: flex-start;
  gap: 1.2rem;
  flex: 1;
}

.bulk-operations-container {
  margin: 2.4rem;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
}

.bulk-operation-box-status-container {
  grid-column: 1 / -1;
}

.bulk-operations-box-container {
  flex: 1;
}

.bulk-operations-sub-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 1rem;
  row-gap: 3.2rem;
  width: 100%;
}

.bulk-operation-header {
  font-weight: 500;
  font-size: 1.4rem;
  grid-column: 1 / -1;
}

.bulk-operation-action-footer {
  grid-column: 1 / -1;
  justify-self: end;
  align-self: end;
}

.bulk-operation-caption {
  font-size: 1.2rem;
  color: #6B869C;
  font-weight: 400;
}

.bulk-operation-data {
  display: flex;
  flex-direction: column;
  gap: 1.2rem;
  align-items: flex-start;
  font-size: 1.2rem;
}


/* File input styling */
.file-input-container {
  position: relative;
  display: inline-block;
}

.file-select-button {
  position: absolute;
  opacity: 0;
  width: 100%;
  height: 100%;
  cursor: pointer;
}

.file-button-label {
  display: inline-flex;
  align-items: center;
  gap: 1.2rem;
  padding: 0.6rem 1.2rem;
  border: 0.2rem solid transparent;
  border-radius: 0.8rem;
  font-size: 1.4rem;
  cursor: pointer;
  transition: all 0.3s ease-in-out;
  outline: none;
  user-select: none;
  font-family: 'Poppins', sans-serif;
  font-weight: 500;
  background-color: #002F54;
  color: #ffffff;
}

.file-button-label:hover {
  background-color: #ffffff;
  color: #002F54;
  border-color: #002F54;
  font-weight: 500;
}

/* Icon for file upload */
.upload-icon {
  width: 1.6rem;
  height: 1.6rem;
  fill: currentColor;
}

/* Selected file display */
.selected-file {
  margin-top: 1rem;
  padding: 1rem;
  background-color: #c3cfdf;
  border-radius: 0.8rem;
  font-size: 1.2rem;
  color: #002F54;
}

.period-select-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  margin-bottom: 1rem;
  gap: 1.6rem;
  font-size: 1.4rem;
  min-width: 30rem;
}

</style>