<script>
import OrderAction from '../../../components/procurements/OrderAction.vue'
import OrderMasterDetail from '../../../components/sales/OrderMasterDetail.vue'
import AgCustomDocStatus from '../../../components/AgGrid/PurchaseOrder/AgCustomDocStatus.vue'
// import AgCustomInfoColumn from '../../../components/AgGrid/PurchaseOrder/AgCustomInfoColumn.vue'
import AgCustomCurrency from '../../../components/AgGrid/PurchaseOrder/AgCustomCurrency.vue'
import AgCustomLink from '../../../components/AgGrid/PurchaseOrder/AgCustomLink.vue'
import AgCustomDateOrdered from '../../../components/AgGrid/PurchaseOrder/AgCustomDateOrdered.vue'
import AgCustomOrderSource from '../../../components/AgGrid/PurchaseOrder/AgCustomOrderSource.vue'
import AgQtyTotal from '../../../components/AgGrid/PurchaseOrder/AgQtyTotal.vue'

export default {
  components: {
    OrderAction,
    OrderMasterDetail,
    AgCustomDocStatus,
    // AgCustomInfoColumn,
    AgCustomCurrency,
    AgCustomLink,
    AgCustomDateOrdered,
    AgCustomOrderSource,
    AgQtyTotal
  }
}
</script>

<script setup>
import { array } from 'alga-js'

const router = useRouter()
const tabs = useTabs()

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

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

const currentPage = ref(1)
const limitPerPage = ref(100)
const totalPages = ref(1)

const getRows = ref([])
const setRows = async () => {
  const offset = array.pageStart(currentPage.value, limitPerPage.value)
  const res = await $fetch(`/api/orders/po?limit=${limitPerPage.value}&offset=${offset}`, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    getRows.value = res?.records?.map(item => {
      return {
        id: item.id,
        uid: item.uid,
        isActive: item.IsActive,
        documentNo: item.DocumentNo,
        description: item.Description,
        isApproved: item.IsApproved,
        isCreditApproved: item.IsCreditApproved,
        isDelivered: item.IsDelivered,
        isInvoiced: item.IsInvoiced,
        isPrinted: item.IsPrinted,
        isTransferred: item.IsTransferred,
        dateOrdered: item.DateOrdered,
        datePromised: item.DatePromised,
        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,
        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 || '',
        salesRep: item.SalesRep_ID?.identifier || '',
        salesRepId: item.SalesRep_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 || '',
        user: item.AD_User_ID?.identifier || '',
        userId: item.AD_User_ID?.id || '',
        cashLine: item.C_CashLine_ID?.identifier || '',
        cashLineId: item.C_CashLine_ID?.id || '',
        billPartner: item.Bill_BPartner_ID?.identifier || '',
        billPartnerId: item.Bill_BPartner_ID?.id || '',
        billPartnerLocation: item.Bill_Location_ID?.identifier || '',
        billPartnerLocationId: item.Bill_Location_ID?.id || '',
        billUser: item.Bill_User_ID?.identifier || '',
        billUserId: item.Bill_User_ID?.id || '',
        organization: item.AD_Org_ID?.identifier || '',
        organizationId: item.AD_Org_ID?.id || '',
        orderLines: item.c_orderline || [],
        POReference:  item.POReference || ''
      }
    })
    totalPages.value = array.pages(res?.['row-count'] ?? 0, limitPerPage.value)
  }
}
onBeforeMount(setRows)
watch(currentPage, setRows)
const handlePage = async (page) => {
  currentPage.value = page || 1
  await setRows()
}

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: getRows.value?.status || 200,
  message: getRows.value?.message || ''
});
onBeforeMount(() => {
  if(Number(getRows.value?.status || 200) === 401) {
    forcingLogout()
  }
})
watch(getRows, () => {
  alert.value.status = getRows.value?.status || 200
  alert.value.message = getRows.value?.message || ''
  if(Number(getRows.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([
  { 
    width: 50,
    checkboxSelection: checkboxSelection,
    headerCheckboxSelection: headerCheckboxSelection
  },
  // {
  //   field: 'id',
  //   //hide: true,
  //   sort: 'desc',
  //   maxWidth: 30,
  //   cellRenderer: "agGroupCellRenderer"
  // },
  {
    field: 'documentNo',
    headerName: '#',
    maxWidth: 90,
    type: 'nonEditableColumn',
    cellRenderer: AgCustomLink,
    cellStyle: {textAlign: 'center'},
  },
  {
    field: 'POReference',
    headerName: 'Reference',
    maxWidth: 150,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'center'},
  },
  // {
  //   field: 'orderSource',
  //   headerName: '#',
  //   maxWidth: 70,
  //   cellRenderer: AgCustomOrderSource,
  //   type: 'nonEditableColumn',
  //   cellStyle: {textAlign: 'center'},
  //   sortable: true,
  //   filter: true
  // },
  {
    field: 'organization',
    headerName: 'Org',
    type: 'nonEditableColumn',
    maxWidth: 70,
    cellStyle: {textAlign: 'center'},
  },
  {
    field: 'dateOrdered',
    headerName: 'Bestelldatum',
    maxWidth: 100,
    cellRenderer: AgCustomDateOrdered,
  },
  {
    field: 'datePromised',
    headerName: 'Lieferdatum',
    maxWidth: 100,
    cellRenderer: AgCustomDateOrdered,
  },
  {
    field: 'partner',
    headerName: 'Partner',
    type: 'nonEditableColumn',
  },
  // {
  //   field: 'billPartner',
  //   headerName: 'Bill Partner',
  //   type: 'nonEditableColumn',
  //   filter: true,
  //   floatingFilter: true,
  //   suppressHeaderMenuButton: true,
  //   suppressHeaderFilterButton: true,
  //   suppressHeaderContextMenu: true
  // },
  {
    field: 'docStatus',
    headerName: 'Status',
    cellRenderer: AgCustomDocStatus,
    type: 'nonEditableColumn',
    maxWidth: 80
  },
  // {
  //   headerName: 'Info',
  //   minWidth: 200,
  //   cellRenderer: AgCustomInfoColumn,
  //   type: 'nonEditableColumn',
  //   cellStyle: {textAlign: 'center'}
  // },
  {
    headerName: 'QTY Total',
    cellRenderer: AgQtyTotal,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'right'},
    maxWidth: 130,
  },
  {
    field: 'grandTotal',
    headerName: 'Total',
    cellRenderer: AgCustomCurrency,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'right'},
    minWidth: 130,
  },
  {
    headerName: 'Action',
    width: 100,
    pinned: 'right',
    cellRenderer: OrderAction,
  }
]);
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/orders/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,
        isCreditApproved: event.data.isCreditApproved,
        isDelivered: event.data.isDelivered,
        isInvoiced: event.data.isInvoiced,
        isPrinted: event.data.isPrinted,
        isTransferred: event.data.isTransferred,
        dateOrdered: event.data.dateOrdered,
        datePromised: event.data.datePromised,
        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,
      }
    })

    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/orders', text: 'Orders', active: true}
]))

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

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

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

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: 'AgCustomDocStatus',
        type: 'nonEditableColumn',
        minWidth: 70
      },
      {
        field: 'orderSource',
        headerName: '#',
        minWidth: 80,
        cellRenderer: 'AgCustomOrderSource',
        type: 'nonEditableColumn',
        cellStyle: {textAlign: 'center'}
      },
      {
        field: 'documentNo',
        headerName: '#',
        minWidth: 90,
        type: 'nonEditableColumn',
        cellRenderer: 'AgCustomLink',
        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 = OrderMasterDetail
  /*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>Orders</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">
              <AgGridCustom :entries="getRows" :columns="colDefs" :masterDetail="true" :masterDetailRenderer="masterDetailRenderer" :masterDetailParams="masterDetailParams" :columnMenu="columnMenu" @cellClick="cellClick" @cellChange="cellChange" />
            </div>
            <div class="d-flex justify-between">
              <div></div>
              <PaginationBox v-model="currentPage" :pages="totalPages" type="sparse" @handler="handlePage" />
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <Teleport to="body">
      <PrintPreview modelName="orders" />
      <ProcurementsOrderQuickView />
    </Teleport>
  </NuxtLayout>
</template>