<script>
import InvoiceAction from '../../../components/procurements/InvoiceAction.vue'
import InvoiceMasterDetail from '../../../components/procurements/InvoiceMasterDetail.vue'
import AgDocStatus from '../../../components/AgGrid/Invoices/AgDocStatus.vue'
import AgCurrency from '../../../components/AgGrid/Invoices/AgCurrency.vue'
import AgLink from '../../../components/AgGrid/Invoices/AgLink.vue'
import AgDateInvoiced from '../../../components/AgGrid/Invoices/AgDateInvoiced.vue'

export default {
  components: {
    InvoiceAction,
    InvoiceMasterDetail,
    AgDocStatus,
    AgCurrency,
    AgLink,
    AgDateInvoiced
  }
}
</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/invoices/po', {
  headers: useRequestHeaders(['cookie'])
})

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    isActive: item.IsActive,
    documentNo: item.DocumentNo,
    description: item.Description,
    isApproved: item.IsApproved,
    isPaid: item.IsPaid,
    isPrinted: item.IsPrinted,
    isTransferred: item.IsTransferred,
    dateOrdered: item.DateOrdered,
    dateInvoiced: item.DateInvoiced,
    dateAcct: item.DateAcct,
    freightAmt: item.FreightAmt,
    totalLines: item.TotalLines,
    grandTotal: item.GrandTotal,
    chargeAmt: item.ChargeAmt,
    processed: item.Processed,
    isSOTrx: item.IsSOTrx,
    isDiscountPrinted: item.IsDiscountPrinted,
    isTaxIncluded: item.IsTaxIncluded,
    isSelected: item.IsSelected,
    sendEMail: item.SendEMail,
    isSelfService: item.IsSelfService,
    isDropShip: item.IsDropShip,
    processedOn: item.ProcessedOn,
    isPayScheduleValid: item.IsPayScheduleValid,
    isPriviledgedRate: item.IsPriviledgedRate,
    isInDispute: item.IsInDispute,
    isFixedAssetInvoice: item.IsFixedAssetInvoice,
    isOverrideCurrencyRate: item.IsOverrideCurrencyRate,
    docStatus: item.DocStatus?.identifier || '',
    docStatusId: item.DocStatus?.id || '',
    docType: item.C_DocType_ID?.identifier || '',
    docTypeId: item.C_DocType_ID?.id || '',
    docTypeTarget: item.C_DocTypeTarget_ID?.identifier || '',
    docTypeTargetId: item.C_DocTypeTarget_ID?.id || '',
    docBaseType: item.DocBaseType?.identifier || '',
    docBaseTypeId: item.DocBaseType?.id || '',
    salesRep: item.SalesRep_ID?.identifier || '',
    salesRepId: item.SalesRep_ID?.id || '',
    user: item.AD_User_ID?.identifier || '',
    userId: item.AD_User_ID?.id || '',
    paymentTerm: item.C_PaymentTerm_ID?.identifier || '',
    paymentTermId: item.C_PaymentTerm_ID?.id || '',
    currency: item.C_Currency_ID?.identifier || '',
    currencyId: item.C_Currency_ID?.id || '',
    invoiceRule: item.InvoiceRule?.identifier || '',
    invoiceRuleId: item.InvoiceRule?.id || '',
    deliveryViaRule: item.DeliveryViaRule?.identifier || '',
    deliveryViaRuleId: item.DeliveryViaRule?.id || '',
    deliveryRule: item.DeliveryRule?.identifier || '',
    deliveryRuleId: item.DeliveryRule?.id || '',
    priorityRule: item.PriorityRule?.identifier || '',
    priorityRuleId: item.PriorityRule?.id || '',
    freightCostRule: item.FreightCostRule?.identifier || '',
    freightCostRuleId: item.FreightCostRule?.id || '',
    paymentRule: item.PaymentRule?.identifier || '',
    paymentRuleId: item.PaymentRule?.id || '',
    warehouse: item.M_Warehouse_ID?.identifier || '',
    warehouseId: item.M_Warehouse_ID?.id || '',
    priceList: item.M_PriceList_ID?.identifier || '',
    priceListId: item.M_PriceList_ID?.id || '',
    partner: item.C_BPartner_ID?.identifier || '',
    partnerId: item.C_BPartner_ID?.id || '',
    partnerLocation: item.C_BPartner_Location_ID?.identifier || '',
    partnerLocationId: item.C_BPartner_Location_ID?.id || '',
    cashLine: item.C_CashLine_ID?.identifier || '',
    cashLineId: item.C_CashLine_ID?.id || '',
    order: item.C_Order_ID?.identifier || '',
    orderId: item.C_Order_ID?.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 colDefaultDefs = ref([
  { 
    maxWidth: 40,
    checkboxSelection: checkboxSelection,
    headerCheckboxSelection: headerCheckboxSelection
  },
  { 
    field: 'id',
    //hide: true,
    sort: 'desc',
    maxWidth: 30,
    cellRenderer: "agGroupCellRenderer"
  },
  { 
    field: 'documentNo',
    headerName: '#',
    maxWidth: 90,
    type: 'nonEditableColumn',
    cellRenderer: AgLink,
    cellStyle: {textAlign: 'center'},
  },
  {
    field: 'organization',
    headerName: 'Org',
    type: 'nonEditableColumn',
    maxWidth: 70,
    cellStyle: {textAlign: 'center'},
    //filter: true,
    //floatingFilter: true,
    //suppressHeaderMenuButton: true,
    //suppressHeaderFilterButton: true,
    //suppressHeaderContextMenu: true
  },
  {
    field: 'dateInvoiced',
    headerName: 'Invoiced',
    maxWidth: 100,
    cellRenderer: AgDateInvoiced,
    //filter: true,
    //floatingFilter: true,
    //suppressHeaderMenuButton: true,
    //suppressHeaderFilterButton: true,
    //suppressHeaderContextMenu: true
  },
  {
    field: 'partner',
    headerName: 'Partner',
    type: 'nonEditableColumn',
    //filter: true,
    //floatingFilter: true,
    //suppressHeaderMenuButton: true,
    //suppressHeaderFilterButton: true,
    //suppressHeaderContextMenu: true
  },
  {
    field: 'docStatus',
    headerName: 'Status',
    cellRenderer: AgDocStatus,
    type: 'nonEditableColumn',
    maxWidth: 80
  },
  {
    field: 'grandTotal',
    headerName: 'Total',
    cellRenderer: AgCurrency,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'right'},
    maxWidth: 130,
    //filter: true,
    //floatingFilter: true,
    //suppressHeaderMenuButton: true,
    //suppressHeaderFilterButton: true,
    //suppressHeaderContextMenu: true
  },
  {
    headerName: 'Action',
    width: 100,
    pinned: 'right',
    cellRenderer: InvoiceAction,
  }
]);
const colDefs = ref(colDefaultDefs.value)

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) => {
  if(event.data.docStatusId === 'CO') {
    alert.value.status = 500
    alert.value.message = 'Sorry, this document is in a completed status, so you cannot update it!'
    window.scrollTo(0, 0)
  } else {
    const res = await $fetch('/api/invoices/update', {
      method: 'PUT',
      headers: useRequestHeaders(['cookie']),
      body: {
        id: event.data.id,
        isActive: event.data.isActive,
        documentNo: event.data.documentNo,
        description: event.data.description,
        isApproved: event.data.isApproved,
        isPaid: event.data.isPaid,
        isPrinted: event.data.isPrinted,
        isTransferred: event.data.isTransferred,
        dateOrdered: event.data.dateOrdered,
        dateInvoiced: event.data.dateInvoiced,
        dateAcct: event.data.dateAcct,
        freightAmt: event.data.freightAmt,
        totalLines: event.data.totalLines,
        grandTotal: event.data.grandTotal,
        chargeAmt: event.data.chargeAmt,
        processed: event.data.processed,
        isSOTrx: event.data.isSOTrx,
        isDiscountPrinted: event.data.isDiscountPrinted,
        isTaxIncluded: event.data.isTaxIncluded,
        isSelected: event.data.isSelected,
        sendEMail: event.data.sendEMail,
        isSelfService: event.data.isSelfService,
        isDropShip: event.data.isDropShip,
        processedOn: event.data.processedOn,
        isPayScheduleValid: event.data.isPayScheduleValid,
        isPriviledgedRate: event.data.isPriviledgedRate,
        isInDispute: event.data.isInDispute,
        isFixedAssetInvoice: event.data.isFixedAssetInvoice,
        isOverrideCurrencyRate: event.data.isOverrideCurrencyRate,
      }
    })

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

const breadCrumb = computed(() => ([
  { link: '#', text: 'Procurements'},
  { link: '/procurements/invoices', text: 'Invoices', active: true}
]))

const create = () => {
  //router.push('/procurements/invoices/create')
  router.push('/procurements/invoices/add')
}

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

    const res = await $fetch('/api/invoices/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()
  }
}

const agGridMobileColumns = () => {
  let mql = window.matchMedia("(max-width: 960px)")
  if(mql.matches) {
    colDefs.value = [
      {
        maxWidth: 40,
        checkboxSelection: checkboxSelection,
        headerCheckboxSelection: headerCheckboxSelection
      },
      {
        field: 'id',
        //hide: true,
        sort: 'desc',
      },
      {
        field: 'docStatus',
        headerName: 'Status',
        cellRenderer: 'AgDocStatus',
        type: 'nonEditableColumn',
        minWidth: 70
      },
      {
        field: 'documentNo',
        headerName: '#',
        minWidth: 90,
        type: 'nonEditableColumn',
        cellRenderer: 'AgLink',
        cellStyle: {textAlign: 'center'}
      }
    ]
  } else {
    colDefs.value = colDefaultDefs.value
  }
}
onMounted(() => {
  agGridMobileColumns()
  window.onresize = agGridMobileColumns;
})
onUpdated(() => {
  agGridMobileColumns()
  window.onresize = agGridMobileColumns;
})

const columnMenu = ref(null)
const masterDetailRenderer = ref(null)
const masterDetailParams = ref(null)
onBeforeMount(() => {
  columnMenu.value = "new"
  masterDetailRenderer.value = InvoiceMasterDetail
  /*masterDetailParams.value = {
    detailGridOptions: {
      // detail grid columns
      columnDefs: [
        {field: 'docTypeTarget', headerName: 'Type'},
        {field: 'salesRep', headerName: 'Sales Rep'},
        {field: 'paymentTerm', headerName: 'Payment Term'},
        {field: 'currency', headerName: 'Currency'},
        {field: 'chargeAmt', headerName: 'Charge', maxWidth: 100},
        {field: 'freightAmt', headerName: 'Freight', maxWidth: 100},
        {field: 'totalLines', headerName: 'Lines', maxWidth: 100},
      ],
      defaultColDef: {
        flex: 1,
      },
    },
    getDetailRowData: params => {
      // supply array of object data to the detail grid
      params.successCallback([
        params.data,
        {
          docTypeTarget: 'Custom Type',
          salesRep: 'Custom Rep',
          paymentTerm: 'Custom Term',
          currency: 'IDR',
          chargeAmt: 0,
          freightAmt: 0,
          totalLines: 0
        }
      ]);
    }
  }*/
})
</script>

<template>
  <Head>
    <Title>Invoices</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" :masterDetail="true" :masterDetailRenderer="masterDetailRenderer" :masterDetailParams="masterDetailParams" :columnMenu="columnMenu" @cellClick="cellClick" @cellChange="cellChange" />
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <Teleport to="body">
      <PrintPreview modelName="invoices" />
      <ProcurementsInvoiceQuickView />
    </Teleport>
  </NuxtLayout>
</template>