<script setup lang="ts">
import { ref, onMounted, toRaw } from 'vue'
import { useRoute } from "vue-router"
import { useToast } from 'vue-toast-notification'
import axios from 'axios'
import currency from "currency.js"

import Invoice from "./../classes/invoice"
import InvoiceItem from "./../classes/invoice_item"

import invoiceHeader from './../components/invoice_header.vue'
import itemSelector from './../components/item_selector.vue'
import invoiceItemsTable from './../components/invoice_items_table.vue'

const toast = useToast({
  position: 'top-right'
})

const route = useRoute()

const invoiceId = route.params.id
const invoice = ref(new Invoice())
const items = ref<any[]>([])

const invoiceIsLoading = ref(true)
const itemsTableIsLoading = ref(true)

const processItems = (items: InvoiceItem[]) => items.map((x: InvoiceItem) => {
  const quantity = currency(x.Quantity)
  const unitPrice = currency(x.UnitPrice)
  const gstPercentage = currency(x.GSTPercentage)
  const gstValue = unitPrice.multiply(gstPercentage).divide(100)
  const totalGSTValue = gstValue.multiply(quantity)
  const amountWithoutGST = unitPrice.multiply(quantity)

  return({
    ...x
    , Quantity: quantity
    , UnitPrice: unitPrice
    , GSTValue: gstValue
    , TotalGSTValue: totalGSTValue
    , AmountWithoutGST: amountWithoutGST
    , TotalAmount: amountWithoutGST.add(totalGSTValue)
  })
})
          //{{ currency(item.UnitPrice).add(currency(item.UnitPrice).multiply(currency(item.GSTPercentage)).divide(100)).multiply(currency(item.Quantity)) }}
          //  {{ currency(item.UnitPrice).multiply(currency(item.Quantity)) }}
          //  {{ currency(item.UnitPrice).multiply(currency(item.GSTPercentage)).divide(100).multiply(item.Quantity) }}

const getInvoice = async () => {
  invoiceIsLoading.value = true
  itemsTableIsLoading.value = true

  try {
    const r = await axios.get(`/invoice/${invoiceId}`)
    invoice.value = r.data.data
    items.value = processItems(r.data.data.Items)
  } catch (err) {
    toast.error('An unhandled exception occoured. Please check logs')
    console.error(err)
  }

  invoiceIsLoading.value = false
  itemsTableIsLoading.value = false
}

const refreshItems = async () => {
  //items.value = []
  itemsTableIsLoading.value = true

  try {
    const res = await axios.get(`/invoice/${invoiceId}/item`)
    if (res.status === 200) {
      items.value = processItems(res.data.data)
    }
  } catch (err) {
    toast.error('An unhandled exception occoured. Please check logs')
    console.error(err)
  }

  itemsTableIsLoading.value = false
}

onMounted(() => {
  getInvoice()
})
</script>

<template>
  <invoiceHeader
    :invoice="invoice" />
  <itemSelector
    :invoiceId="invoiceId"
    @added="refreshItems()"/>
  <invoiceItemsTable
    :items="items"
    :isLoading="itemsTableIsLoading"
    @refresh="refreshItems()" />
</template>
