<script>
import PaymentTermAction from '../../../components/partners/PaymentTermAction.vue'

export default {
  components: {
    PaymentTermAction
  }
}
</script>

<script setup>
const router = useRouter()
const tabs = useTabs()

definePageMeta({
  middleware: ['auth', 'org']
})

const isDeletable = ref(false)
const searchQuery = ref('')
const selectedRows = ref([])

const { data, pending, error, refresh } = await useFetch('/api/partners/payment-terms', {
  headers: useRequestHeaders(['cookie'])
})

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    name: item.Name,
    value: item.Value,
    description: item.Description,
    documentNote: item.DocumentNote,
    afterDelivery: item.AfterDelivery,
    netDays: item.NetDays,
    netDay: item?.NetDay || '',
    graceDays: item.GraceDays,
    isActive: item.IsActive,
    isDefault: item.IsDefault,
    isValid: item.IsValid,
    isDueFixed: item.IsDueFixed,
    fixMonthCutoff: item?.FixMonthCutoff || 0,
    fixMonthDay: item?.FixMonthDay || 0,
    fixMonthOffset: item?.FixMonthOffset || 0,
    isNextBusinessDay: item.IsNextBusinessDay,
    discount: item.Discount,
    discount2: item.Discount2,
    discountDays: item.DiscountDays,
    discountDays2: item.DiscountDays2,
    paymentTermUsage: item.PaymentTermUsage?.identifier || '',
    paymentTermUsageId: item.PaymentTermUsage?.id || '',
    organization: item.AD_Org_ID?.identifier || '',
    organizationId: item.AD_Org_ID?.id || ''
  }
}) || []);

const forcingLogout = async () => {
  await $fetch('/api/idempiere-auth/logout', {
    method: 'POST',
    headers: useRequestHeaders(['cookie'])
  })

  tabs.value = [{link: '/', text: 'Home', active: true}]
  localStorage.setItem('tabs', JSON.stringify(tabs.value))

  console.info('Session expired and it will auto redirected toward login page.')
  location.href = '/signin'
}
const alert = ref({
  status: data.value?.status || 200,
  message: data.value?.message || ''
});
onBeforeMount(() => {
  if(Number(data.value?.status || 200) === 401) {
    forcingLogout()
  }
})
watch(data, () => {
  alert.value.status = data.value?.status || 200
  alert.value.message = data.value?.message || ''
  if(Number(data.value?.status || 200) === 401) {
    forcingLogout()
  }
})

const checkboxSelection = (params) => {
  return params.api.getRowGroupColumns().length === 0;
};
const headerCheckboxSelection = (params) => {
  return params.api.getRowGroupColumns().length === 0;
};

const colDefs = ref([
  { 
    width: 50,
    checkboxSelection: checkboxSelection,
    headerCheckboxSelection: headerCheckboxSelection
  },
  { 
    field: 'id',
    //hide: true,
    sort: 'desc'
  },
  { 
    field: 'organization',
    type: 'nonEditableColumn' 
  },
  { field: 'name' },
  { 
    field: 'value',
    headerName: 'Search Key'
  },
  { 
    field: 'afterDelivery',
    headerName: 'After Delivery'
  },
  { 
    field: 'netDays',
    headerName: 'Net Days'
  },
  { 
    field: 'graceDays',
    headerName: 'Grace Days'
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  /*{ 
    field: "price",
    width: 130,
    valueFormatter: (params) => {
      return '£' + params.value.toLocaleString();
    }
  },*/
  { 
    field: 'isDefault',
    headerName: 'Default'
  },
  /*{ 
    field: 'isValid',
    headerName: 'Valid'
  },
  { 
    field: 'isDueFixed',
    headerName: 'Due Fixed'
  },
  { 
    field: 'isNextBusinessDay',
    headerName: 'Next Business Day'
  },
  { 
    field: 'discount',
    headerName: 'Discount'
  },
  { 
    field: 'discount2',
    headerName: 'Discount 2'
  },
  { 
    field: 'discountDays',
    headerName: 'Discount Days'
  },
  { 
    field: 'discountDays2',
    headerName: 'Discount Days 2'
  },*/
  { 
    field: 'paymentTermUsage',
    headerName: 'Payment Term Usage',
    type: 'nonEditableColumn'
  },
  {
    field: 'action',
    width: 100,
    pinned: 'right',
    cellRenderer: PaymentTermAction,
    type: 'nonEditableColumn'
  }
]);

const cellClick = (event, gridApi) => {
  selectedRows.value = gridApi.getSelectedRows()

  if(event.source === 'checkboxSelected') {
    isDeletable.value = false
    if(selectedRows.value.length >= 1) {
      isDeletable.value = true
    }
  }
}

const cellChange = async (event) => {
  const res = await $fetch('/api/partners/payment-terms/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: event.data.id,
      name: event.data.name,
      value: event.data.value,
      afterDelivery: event.data.afterDelivery,
      netDays: event.data.netDays,
      graceDays: event.data.graceDays,
      isActive: event.data.isActive,
      isDefault: event.data.isDefault,
      isValid: event.data.isValid,
      isDueFixed: event.data.isDueFixed,
      isNextBusinessDay: event.data.isNextBusinessDay,
      discount: event.data.discount,
      discount2: event.data.discount2,
      discountDays: event.data.discountDays,
      discountDays2: event.data.discountDays2,
      paymentTermUsageId: event.data.paymentTermUsageId
    }
  })

  if(Number(res.status) >= 400) {
    alert.value.status = res.status
    alert.value.message = res.message
  }
}

const breadCrumb = computed(() => ([
  { link: '/partners/partners', text: 'Partners'},
  { link: '/partners/payment-terms', text: 'Payment Terms', active: true}
]))

const create = () => {
  router.push('/partners/payment-terms/create')
}

const destroy = async () => {
  if(selectedRows.value.length >= 1) {
    isDeletable.value = false

    const res = await $fetch('/api/partners/payment-terms/destroy', {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie']),
      body: {
        ids: selectedRows.value.map(i => i.id)
      }
    })

    if(Number(res.status) >= 400) {
      alert.value.status = res.status
      alert.value.message = res.message
    }

    refresh()
  }
}
</script>

<template>
  <Head>
    <Title>Payment Terms</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    <div>
      <div class="banner datatable-wrapper">
        <HeaderAction :isDeletable="isDeletable" @create="create" @destroy="destroy" />
        <div>
          <div>
            <AlertBox :alert="alert" />
            <div class="mb-3">
              <AgGrid :entries="rowData" :columns="colDefs" @cellClick="cellClick" @cellChange="cellChange" />
            </div>
          </div>
        </div>
      </div>

    </div>

    <Teleport to="body">
      <PartnersPaymentTermQuickView />
    </Teleport>
  </NuxtLayout>
</template>