<script setup>

const toast = useToast()
const dataStore = useDataStore()
const modal = useModal()
const props = defineProps({
  documentData: {
    type: Object,
    required: true
  },
  openShowModal: {
    type: Boolean,
    required: false,
  },
  returnEmit: {
    type: Boolean
  },

})

const emit = defineEmits(["updateNeeded"])

const folders = ref([])

const filetypes = ref([])
const documentboxes = ref([])

const setup = async () => {
  const data = await useEntities("folders").select()

  data.forEach(folder => {
    let name = folder.name

    const addParent = (item) => {
      name = `${item.name} > ${name}`

      if(item.parent){
        addParent(data.find(i => i.id === item.parent))
      } else {
        folders.value.push({
          id: folder.id,
          name: name,
        })
      }
    }

    if(folder.parent) {
      addParent(data.find(i => i.id === folder.parent))
    } else {
      folders.value.push({
        id: folder.id,
        name: folder.name,
      })
    }
  })

  filetypes.value = await useEntities("filetags").select()
  documentboxes.value = await useEntities("documentboxes").select()
}

setup()

const updateDocument = async () => {
  const {url, ...objData} = props.documentData
  delete objData.url
  delete objData.filetags

  /*console.log(objData)

  if(objData.project) objData.project = objData.project.id
  if(objData.customer) objData.customer = objData.customer.id
  if(objData.contract) objData.contract = objData.contract.id
  if(objData.vendor) objData.vendor = objData.vendor.id
  if(objData.plant) objData.plant = objData.plant.id
  if(objData.createddocument) objData.createddocument = objData.createddocument.id
  if(objData.vehicle) objData.vehicle = objData.vehicle.id
  if(objData.product) objData.product = objData.product.id
  if(objData.profile) objData.profile = objData.profile.id
  if(objData.check) objData.check = objData.check.id
  if(objData.inventoryitem) objData.inventoryitem = objData.inventoryitem.id
  if(objData.incominginvoice) objData.incominginvoice = objData.incominginvoice.id*/

  console.log(objData)

  const {data,error} = await useEntities("files").update(objData.id, objData)

  if(error) {
    console.log(error)

  } else {
    console.log(data)
    toast.add({title: "Datei aktualisiert"})
    modal.close()
    emit("updateNeeded")
    //openShowModal.value = false
  }
}

const archiveDocument = async () => {
  props.documentData.archived = true
  await updateDocument()

  modal.close()
  emit("update")
}

const resourceOptions = ref([
    {label: 'Projekt', value: 'project', optionAttr: "name"},
  {label: 'Kunde', value: 'customer', optionAttr: "name"},
  {label: 'Lieferant', value: 'vendor', optionAttr: "name"},
  {label: 'Fahrzeug', value: 'vehicle', optionAttr: "licensePlate"},
  {label: 'Objekt', value: 'plant', optionAttr: "name"},
  {label: 'Vertrag', value: 'contract', optionAttr: "name"},
  {label: 'Produkt', value: 'product', optionAttr: "name"}
])
const resourceToAssign = ref("project")
const itemOptions = ref([])
const idToAssign = ref(null)
const getItemsBySelectedResource = async () => {
  if(resourceToAssign.value === "project") {
    itemOptions.value = await useEntities("projects").select()
  } else if(resourceToAssign.value === "customer") {
    itemOptions.value = await useEntities("customers").select()
  } else if(resourceToAssign.value === "vendor") {
    itemOptions.value = await useEntities("vendors").select()
  } else if(resourceToAssign.value === "vehicle") {
    itemOptions.value = await useEntities("vehicles").select()
  } else if(resourceToAssign.value === "product") {
    itemOptions.value = await useEntities("products").select()
  } else if(resourceToAssign.value === "plant") {
    itemOptions.value = await useEntities("plants").select()
  } else if(resourceToAssign.value === "contract") {
    itemOptions.value = await useEntities("contracts").select()
  } else {
    itemOptions.value =  []
  }
}
getItemsBySelectedResource()

const updateDocumentAssignment = async () => {
  props.documentData[resourceToAssign.value] = idToAssign.value
  await updateDocument()
}

const folderToMoveTo = ref(null)
const moveFile = async () => {

  const res = await useEntities("files").update(props.documentData.id, {folder: folderToMoveTo.value})

  modal.close()
}



</script>

<template>
  <UModal fullscreen >
    <UCard :ui="{ body: { base: 'flex-1' }, ring: '', divide: 'divide-y divide-gray-100 dark:divide-gray-800' }" class="h-full">
      <template #header>
        <div class="flex flex-row justify-between">
          <div class="flex items-center gap-2">
            <UBadge
                v-for="tag in props.documentData.filetags"
            >
              {{tag.name}}
            </UBadge>
          </div>
          <UButton color="gray" variant="ghost" icon="i-heroicons-x-mark-20-solid" class="-my-1" @click="modal.close()" />
        </div>

      </template>
      <div class="flex flex-row">
        <div :class="useCapacitor().getIsNative() ? ['w-full'] : ['w-1/3']">
          <PDFViewer
              v-if="props.documentData.id && props.documentData.path.toLowerCase().includes('pdf')"
              :file-id="props.documentData.id" />

          <img
              class=" w-full"
              :src="props.documentData.url"
              alt=""
              v-else
          />
        </div>
        <div class="w-2/3 p-5" v-if="!useCapacitor().getIsNative()">
          <UButtonGroup>
            <ArchiveButton
                color="rose"
                variant="outline"
                type="files"
                @confirmed="archiveDocument"
            />

            <UButton
                :to="props.documentData.url"
                variant="outline"
                icon="i-heroicons-arrow-top-right-on-square"
                target="_blank"
            >
              Öffnen
            </UButton>
          </UButtonGroup>

          <UDivider>Zuweisungen</UDivider>
          <table class="w-full">
            <tr v-if="props.documentData.project">
              <td>Projekt</td>
              <td>
                <nuxt-link :to="`/standardEntity/projects/show/${props.documentData.project.id}`">{{props.documentData.project.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.customer">
              <td>Kunde</td>
              <td>
                <nuxt-link :to="`/standardEntity/customers/show/${props.documentData.customer.id}`">{{props.documentData.customer.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.vendor">
              <td>Lieferant</td>
              <td>
                <nuxt-link :to="`/standardEntity/vendors/show/${props.documentData.vendor.id}`">{{props.documentData.vendor.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.createddocument">
              <td>Ausgangsbeleg</td>
              <td>
                <nuxt-link :to="`/createDocument/show/${props.documentData.createddocument.id}`">{{props.documentData.createddocument.documentNumber}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.plant">
              <td>Objekt</td>
              <td>
                <nuxt-link :to="`/standardEntity/plants/show/${props.documentData.plant.id}`">{{props.documentData.plant.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.contract">
              <td>Vertrag</td>
              <td>
                <nuxt-link :to="`/standardEntity/contracts/show/${props.documentData.contract.id}`">{{props.documentData.contract.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.vehicle">
              <td>Fahrzeug</td>
              <td>
                <nuxt-link :to="`/standardEntity/vehicles/show/${props.documentData.vehicle.id}`">{{props.documentData.vehicle.licensePlate}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.product">
              <td>Artikel</td>
              <td>
                <nuxt-link :to="`/standardEntity/products/show/${props.documentData.product.id}`">{{props.documentData.product.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.inventoryitem">
              <td>Inventarartikel</td>
              <td>
                <nuxt-link :to="`/standardEntity/inventoryitem/show/${props.documentData.inventoryitem.id}`">{{props.documentData.inventoryitem.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.check">
              <td>Überprüfung</td>
              <td>
                <nuxt-link :to="`/standardEntity/checks/show/${props.documentData.check.id}`">{{props.documentData.check.name}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.profile">
              <td>Mitarbeiter</td>
              <td>
                <nuxt-link :to="`/profiles/show/${props.documentData.profile.id}`">{{props.documentData.profile.fullName}}</nuxt-link>
              </td>
            </tr>
            <tr v-if="props.documentData.incominginvoice">
              <td>Eingangsrechnung</td>
              <td>
                <nuxt-link :to="`/incomingInvoices/show/${props.documentData.incominginvoice.id}`">{{props.documentData.incominginvoice.reference}}</nuxt-link>
              </td>
            </tr>
          </table>

          <UDivider class="my-3">Datei zuweisen</UDivider>

          <UFormGroup
              label="Resource auswählen"
          >
            <USelectMenu
                :options="resourceOptions"
                v-model="resourceToAssign"
                value-attribute="value"
                option-attribute="label"
                @change="getItemsBySelectedResource"
            >

            </USelectMenu>
          </UFormGroup>
          <UFormGroup
              label="Eintrag auswählen:"
          >
            <USelectMenu
                :options="itemOptions"
                v-model="idToAssign"
                :option-attribute="resourceOptions.find(i => i.value === resourceToAssign)? resourceOptions.find(i => i.value === resourceToAssign).optionAttr : 'name'"
                value-attribute="id"
                @change="updateDocumentAssignment"
            ></USelectMenu>
          </UFormGroup>



          <UDivider class="my-5">Datei verschieben</UDivider>

          <InputGroup class="w-full">
            <USelectMenu
                class="flex-auto"
                v-model="folderToMoveTo"
                value-attribute="id"
                option-attribute="name"
                :options="folders"
            />
            <UButton
              @click="moveFile"
              variant="outline"
              :disabled="!folderToMoveTo"
            >Verschieben</UButton>
          </InputGroup>

          <UDivider class="my-5">Dateityp</UDivider>

          <InputGroup class="w-full">
            <USelectMenu
                class="flex-auto"
                v-model="props.documentData.type"
                value-attribute="id"
                option-attribute="name"
                :options="filetypes"
                @change="updateDocument"
            />
          </InputGroup>
          <UDivider class="my-5">Dokumentenbox</UDivider>

          <InputGroup class="w-full">
            <USelectMenu
                class="flex-auto"
                v-model="props.documentData.documentbox"
                value-attribute="id"
                option-attribute="key"
                :options="documentboxes"
                @change="updateDocument"
            />
          </InputGroup>

        </div>
      </div>
    </UCard>
  </UModal>
</template>

<style scoped>

.bigPreview {
  width: 100%;
  aspect-ratio: 1/ 1.414;
}

</style>