<script setup>
import axios from "axios";
import ZebraBrowserPrintWrapper from "zebra-browser-print-wrapper"
definePageMeta({
  middleware: "auth"
})

const dataStore = useDataStore()
const route = useRoute()
const router = useRouter()
const toast = useToast()
const id = ref(route.params.id ? route.params.id : null )

const browserPrint = ZebraBrowserPrintWrapper();

let currentItem = ref(null)

//Working
const mode = ref(route.params.mode || "show")
const itemInfo = ref({
  spaceNumber: ""
})
const spaceTypes = ["Regalplatz", "Kiste", "Palettenplatz", "Sonstiges"]
const spaceProducts = ref([])
const spaceMovements = ref([])

//Functions
const setupPage = async () => {
  console.log("Called Setup")
  if(mode.value === "show" || mode.value === "edit"){
    currentItem.value = await dataStore.getSpaceById(Number(useRoute().params.id))

    spaceMovements.value = await dataStore.getMovementsBySpace(currentItem.value.id)
    spaceProducts.value = []
    spaceMovements.value.forEach(movement => {
      if(spaceProducts.value.filter(product => product.id === movement.productId).length === 0) spaceProducts.value.push(dataStore.getProductById(movement.productId))
    })
  }

  if(mode.value === "edit") itemInfo.value = currentItem.value


}

const cancelEditorCreate = () => {
  if(currentItem.value) {
    router.push(`/spaces/show/${currentItem.value.id}`)
  } else {
    router.push(`/spaces/`)
  }
}

function getSpaceProductCount(productId) {
  let productMovements = spaceMovements.value.filter(movement => movement.productId === productId)
  let count = 0;
  productMovements.forEach(movement => count += movement.quantity)

  return count
}

const printSpaceLabel = async () => {
  axios
      .post(`http://${dataStore.ownTenant.value.labelPrinterIp}/pstprnt`, `^XA^FO10,20^BCN,100^FD${currentItem.value.spaceNumber}^XZ` )
      .then(console.log)
      .catch(console.log)
}


setupPage()
</script>

<template>
  <UDashboardNavbar :title="currentItem ? currentItem.name : (mode === 'create' ? 'Lagerplatz erstellen' : 'Lagerplatz bearbeiten')">
    <template #right>
      <UButton
          v-if="mode === 'edit'"
          @click="dataStore.updateItem('spaces',itemInfo)"
      >
        Speichern
      </UButton>
      <UButton
          v-else-if="mode === 'create'"
          @click="dataStore.createNewItem('spaces',itemInfo)"
      >
        Erstellen
      </UButton>
      <UButton
          @click="cancelEditorCreate"
          color="red"
          class="ml-2"
          v-if="mode === 'edit' || mode === 'create'"
      >
        Abbrechen
      </UButton>
      <UButton
          v-if="mode === 'show'"
          @click="  router.push(`/inventory/spaces/edit/${currentItem.id}`)"
      >
        Bearbeiten
      </UButton>
    </template>
  </UDashboardNavbar>
  <UTabs
    :items="[{label: 'Informationen'},{label: 'Logbuch'},{label: 'Bestand'}]"
    v-if="currentItem && mode == 'show'"
    class="p-5"
  >
    <template #item="{item}">
      <UCard class="mt-5">
        <div v-if="item.label === 'Informationen'">
          <div class="truncate">
            <span>Beschreibung: {{currentItem.description}}</span>
          </div>


        </div>
        <div v-else-if="item.label === 'Logbuch'">

        </div>
        <div v-else-if="item.label === 'Bestand'">
          <div v-if="spaceProducts.length > 0">
            <p class="mt-5">Artikel in diesem Lagerplatz</p>

            <table>
              <tr>
                <th class="text-left">Artikel</th>
                <th>Anzahl</th>
                <th>Einheit</th>
              </tr>
              <tr v-for="product in spaceProducts">
                <td>{{product.name}}</td>
                <td>{{getSpaceProductCount(product.id)}}</td>
                <td>{{dataStore.units.find(unit => unit.id === product.unit).name}}</td>
              </tr>

            </table>
          </div>
          <p v-else>Es befinden sich keine Artikel in diesem Lagerplatz</p>
        </div>
      </UCard>
    </template>
  </UTabs>
  <UForm
      v-else-if="mode === 'edit' || mode === 'create'"
      class="p-5"
  >
    <UFormGroup
        label="Typ:"
    >
      <USelectMenu
          :options="spaceTypes"
          v-model="itemInfo.type"
      >

      </USelectMenu>
    </UFormGroup>
    <UFormGroup
        label="Beschreibung.:"
    >
      <UTextarea
          v-model="itemInfo.description"
      />
    </UFormGroup>
  </UForm>
</template>

<style scoped>

</style>