<script setup>
import { date, array } from 'alga-js'
import { DatePicker } from 'tedir-calendar'
import { SelectBox } from 'tedir-select'
import { toast } from 'bulma-toast'

const route = useRoute()
const organizationId = useCookie('logship_organization_id')

const props = defineProps({
  action: String,
  info: Object
})

const entries = ref([])
const form = ref({
  id: '',
  client: props.info?.client || '',
  clientId: props.info?.clientId || '',
  organization: props.info?.organization || '',
  organizationId: props.info?.organizationId || organizationId.value || '',
  invoice: props.info?.documentNo || '',
  invoiceId: props.info?.id || '',
  isActive: true,
  tax: '',
  taxId: '',
  taxBaseAmt: 0,
  taxAmt: 0,
  processed: false,
  isTaxIncluded: false,
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

watch(() => props.info, () => {
  form.value.client = props.info?.client || ''
  form.value.clientId = props.info?.clientId || ''
  form.value.organization = props.info?.organization || ''
  form.value.organizationId = props.info?.organizationId || organizationId.value || ''
  form.value.invoice = props.info?.documentNo || ''
  form.value.invoiceId = props.info?.id || ''
})

const showDetailRecordModal = ref(false)
const closeDetailRecordModal = () => {
  showDetailRecordModal.value = false

  form.value = {
    id: '',
    client: props.info?.client || '',
    clientId: props.info?.clientId || '',
    organization: props.info?.organization || '',
    organizationId: props.info?.organizationId || organizationId.value || '',
    invoice: props.info?.documentNo || '',
    invoiceId: props.info?.id || '',
    isActive: true,
    tax: '',
    taxId: '',
    taxBaseAmt: 0,
    taxAmt: 0,
    processed: false,
    isTaxIncluded: false,
    alert: {
      status: '',
      message: '',
      processing: false,
    }
  }
}

const loading = ref({})
const getOptions = ref({})
const setOptions = async (url, key) => {
  loading.value[key] = true
  const res = await $fetch('/api/'+url, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    getOptions.value[key] = res
  }
  loading.value[key] = false
}

const retrieve = async () => {
  const newId = route.params?.id || props.info?.id || null
  if(newId) {
    const res = await $fetch('/api/invoices/'+newId+'/invoice-tax', {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      entries.value = res.records.map(item => {
        return {
          id: item?.id || '',
          client: item?.AD_Client_ID?.identifier || '',
          clientId: item?.AD_Client_ID?.id || '',
          organization: item?.AD_Org_ID?.identifier || '',
          organizationId: item?.AD_Org_ID?.id || '',
          invoice: item?.C_Invoice_ID?.identifier || '',
          invoiceId: item?.C_Invoice_ID?.id || '',
          isActive: item?.IsActive ?? true,
          tax: item?.C_Tax_ID?.identifier || '',
          taxId: item?.C_Tax_ID?.id || '',
          taxBaseAmt: item?.TaxBaseAmt || 0,
          taxAmt: item?.TaxAmt || 0,
          processed: item?.Processed ?? false,
          isTaxIncluded: item?.IsTaxIncluded ?? false,
          alert: {
            status: '',
            message: '',
            processing: false,
          }
        }
      })
    }
  }
}
onMounted(retrieve)

const destroy = async (entry, index) => {
  entries.value.splice(index, 1)

  if(entry.id) {
    await $fetch('/api/invoices/'+entry.id+'/order-line', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
  }
}

const save = async () => {
  if(form.value.id !== '') {
    const res = await $fetch('/api/invoices/'+route.params.id+'/invoice-tax', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: form.value.id,
        isActive: form.value.isActive,
        line: form.value.line,
        productId: form.value.productId,
        qtyEntered: form.value.qtyEntered,
        uomId: form.value.uomId,
        priceActual: form.value.priceActual,
        priceEntered: form.value.priceEntered,
        priceList: form.value.priceList,
        tax: form.value.tax,
        taxId: form.value.taxId,
        discount: form.value.discount,
        lineNetAmt: form.value.lineNetAmt,
        warehouseId: form.value.warehouseId,
        currencyId: form.value.currencyId,
        attributeSetInstanceId: form.value.attributeSetInstanceId,
        chargeId: form.value.chargeId,
        projectId: form.value.projectId,
        campaignId: form.value.campaignId,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record saved!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      //form.value.alert.status = res.status
      //form.value.alert.message = res.message
      form.value.alert.processing = false
      toast({
        message: res.message || 'Save error',
        type: 'is-danger',
        duration: 2000
      })
    }
  } else {
    const res = await $fetch('/api/invoices/'+route.params.id+'/invoice-tax', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        organizationId: form.value.organizationId || organizationId.value,
        orderId: route.params.id,
        isActive: form.value.isActive,
        line: form.value.line,
        productId: form.value.productId,
        qtyEntered: form.value.qtyEntered,
        uomId: form.value.uomId,
        priceActual: form.value.priceActual,
        priceEntered: form.value.priceEntered,
        priceList: form.value.priceList,
        tax: form.value.tax,
        taxId: form.value.taxId,
        discount: form.value.discount,
        lineNetAmt: form.value.lineNetAmt,
        warehouseId: form.value.warehouseId,
        currencyId: form.value.currencyId,
        attributeSetInstanceId: form.value.attributeSetInstanceId,
        chargeId: form.value.chargeId,
        projectId: form.value.projectId,
        campaignId: form.value.campaignId,
      }
    })
    if(Number(res.status) === 200) {
      closeDetailRecordModal()
      retrieve()
      toast({
        message: 'Record created!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      //form.value.alert.status = res.status
      //form.value.alert.message = res.message
      form.value.alert.processing = false
      toast({
        message: res.message || 'Save error',
        type: 'is-danger',
        duration: 2000
      })
    }
  }
}
</script>

<template>
  <div class="detailRecordResponsive">
    <div class="tableResponsive">
      <table class="table tableList tableFlush">
        <thead>
          <tr> 
            <th>Tax</th>
            <th>Tax Amount</th>
            <th>Tax base Amount</th>
            <th>Price includes Tax</th>
            <th>Processed</th>
            <th class="w-100px">Active</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="Number(entries.length) === 0">
            <td colspan="6" class="align-center">No detail record yet, please add a new one.</td>
          </tr>
          <tr v-for="(entry, index) in entries" :key="index">
            <td>{{ entry.tax }}</td>
            <td>{{ entry.taxAmt }}</td>
            <td>{{ entry.taxBaseAmt }}</td>
            <td>
              <div class="check">
                <input type="checkbox" v-model="entry.isTaxIncluded" class="checkInput" :id="'isTaxIncluded_'+index" :checked="entry.isTaxIncluded" disabled>
                <label class="checkLabel" :for="'isTaxIncluded_'+index">Tax Included</label>
              </div>
            </td>
            <td>
              <div class="check">
                <input type="checkbox" v-model="entry.processed" class="checkInput" :id="'processed_'+index" :checked="entry.processed" disabled>
                <label class="checkLabel" :for="'processed_'+index">Processed</label>
              </div>
            </td>
            <td>
              <div class="check">
                <input type="checkbox" v-model="entry.isActive" class="checkInput" :id="'isActive_'+index" :checked="entry.isActive" disabled>
                <label class="checkLabel" :for="'isActive_'+index">Active</label>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>