<template>
  <div class="edit-calculation-container">
    <div class="header-container">
      <h2 class="page-header">Edit calculation</h2>
      <div class="header-controls">
        <basic-button @click="close" :show-icon="false" :disabled="premiseEditStore.selectedLoading" variant="secondary"> {{ fromMassEdit ? 'Back' : 'Close' }}
        </basic-button>
        <basic-button v-if="!fromMassEdit"
                      :show-icon="true"
                      :disabled="premiseEditStore.selectedLoading || !premiseEditStore.isSingleSelect"
                      icon="Calculator"
                      variant="primary"
                      @click="startCalculation"
        >Calculate & close
        </basic-button>

      </div>
    </div>
    <Toast ref="toast" />

    <div v-if="premiseEditStore.selectedLoading" class="edit-calculation-spinner-container">
      <box class="edit-calculation-spinner">
        <spinner></spinner>
      </box>
    </div>
    <div v-else-if="!premiseEditStore.isSingleSelect" class="edit-calculation-spinner-container">
      <box class="edit-calculation-spinner">No calculation found.</box>
    </div>
    <div v-else>

      <h3 class="sub-header">Master data</h3>
      <div class="master-data-container">
        <box class="master-data-item master-data-stretched-item">
          <supplier-view :supplier-address="premise.supplier.address"
                         :supplier-name="premise.supplier.name"
                         :supplier-coordinates="premise.supplier.location"
                         :iso-code="premise.supplier.country.iso_code"
                         @update-supplier="updateSupplier"
                         ></supplier-view>
        </box>
        <box class="master-data-item master-data-stretched-item master-data-packaging">
          <packaging-edit v-model:length="premise.handling_unit.length"
                          v-model:width="premise.handling_unit.width"
                          v-model:height="premise.handling_unit.height"
                          v-model:weight="premise.handling_unit.weight"
                          v-model:weight-unit="premise.handling_unit.weight_unit"
                          v-model:dimension-unit="premise.handling_unit.dimension_unit"
                          v-model:unit-count="premise.handling_unit.content_unit_count"
                          v-model:stackable="premise.is_stackable"
                          v-model:mixable="premise.is_mixable"
                          @save="save"></packaging-edit>
        </box>
        <box class="master-data-item">
          <material-edit :part-number="premise.material.part_number"
                         :description="premise.material.name"
                         :id="premise.material.id"
                         v-model:hs-code="premise.hs_code"
                         v-model:tariff-rate="premise.tariff_rate"
                         @update-material="updateMaterial"
                         @save="save"></material-edit>
        </box>
        <box class="master-data-item">
          <price-edit v-model:include-fca-fee="premise.is_fca_enabled"
                      v-model:over-sea-share="premise.oversea_share"
                      v-model:price="premise.material_cost"
                      @save="save"></price-edit>
        </box>

      </div>

      <h3 class="sub-header">Destinations & routes</h3>
      <destination-list-view></destination-list-view>

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

<script>

import BasicButton from "@/components/UI/BasicButton.vue";
import SupplierView from "@/components/layout/edit/SupplierView.vue";
import Box from "@/components/UI/Box.vue";
import MaterialEdit from "@/components/layout/edit/MaterialEdit.vue";
import PackagingEdit from "@/components/layout/edit/PackagingEdit.vue";
import PriceEdit from "@/components/layout/edit/PriceEdit.vue";
import DestinationListView from "@/components/layout/edit/DestinationListView.vue";
import {mapStores} from "pinia";
import {usePremiseEditStore} from "@/store/premiseEdit.js";
import Spinner from "@/components/UI/Spinner.vue";
import NotificationBar from "@/components/UI/NotificationBar.vue";
import Modal from "@/components/UI/Modal.vue";
import TraceView from "@/components/layout/TraceView.vue";
import IconButton from "@/components/UI/IconButton.vue";
import Toast from "@/components/UI/Toast.vue";
import {UrlSafeBase64} from "@/common.js";

export default {
  name: "SingleEdit",
  components: {
    Toast,
    IconButton,
    TraceView,
    Modal,
    NotificationBar,
    Spinner,
    DestinationListView,
    PriceEdit,
    PackagingEdit,
    MaterialEdit,
    Box,
    SupplierView,
    BasicButton
  },
  data() {
    return {
      traceModal: false,
      bulkEditQuery: null,
      id: null,
    }
  },
  computed: {
    ...mapStores(usePremiseEditStore),
    premise() {
      return this.premiseEditStore.singleSelectedPremise;
    },
    fromMassEdit() {
      return this.bulkEditQuery !== null;
    }
  },
  methods: {
    startCalculation() {
      this.premiseEditStore.startCalculation();
    },
    close() {
      if(this.bulkEditQuery) {
        //TODO: deselect and save
        this.premiseEditStore.deselectPremise();
        this.$router.push({name: 'bulk', params: {ids: this.bulkEditQuery}});
      }
      else {
        //TODO: deselect and save
        this.$router.push({name: 'home'});
      }
    },
    async save(type) {
      let success = false;

      if(type === 'price') {
        success = await this.premiseEditStore.savePrice();
      } else if(type === 'material') {
        success = await this.premiseEditStore.saveMaterial();
      } else if(type === 'packaging') {
        success = await this.premiseEditStore.savePackaging();
      }

      console.log("save success: ", success);

      if(success) {
        this.$refs.toast.addToast({
          icon: 'floppy-disk',
          message: `Changes on ${type} saved.`,

          variant: 'primary',
          duration: 3000
        })
      }

    },
    updateMaterial(id, action) {
      console.log(id, action);
      this.premiseEditStore.setMaterial(id, action === 'updateMasterData');
    },
    updateSupplier(data) {
      this.premiseEditStore.setSupplier(data.nodeId, data.updateMasterData);
    },
    trace() {
      this.traceModal = true;
    }
  },
  created() {
    [this.id] = new UrlSafeBase64().decodeIds(this.$route.params.id);

    if(this.$route.params.ids) {
      this.bulkEditQuery = this.$route.params.ids;
      this.premiseEditStore.selectSinglePremise(this.id, new UrlSafeBase64().decodeIds(this.$route.params.ids));
    } else {
      this.premiseEditStore.loadAndSelectSinglePremise(this.id)
    }
  },

}
</script>

<style scoped>

.trace-link {
  cursor: pointer;
  text-decoration: underline;
}

.edit-calculation-spinner-container {
  display: flex;
  align-items: center;
  justify-content: center;
  flex: 1 1 30rem
}

.edit-calculation-spinner {
  font-size: 1.6rem;
  width: 24rem;
  height: 12rem;
  display: flex;
  justify-content: center;
  align-items: center;
}

.edit-calculation-container {
  display: flex;
  flex-direction: column;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1.6rem;
}

.header-controls {
  display: flex;
  gap: 1.6rem;
}

.master-data-container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: auto auto;
  gap: 1.6rem;
  margin: 2.4rem 0;
}

.master-data-stretched-item {
  grid-row: span 2 / span 2;
}

.master-data-packaging {
  grid-column-start: 3;
  grid-row-start: 1;
}

.master-data-item {

}

.destination-list-container {
  margin: 2.4rem 1.6rem;
}

</style>