<script>
import OrderAction from '../../../components/sales/FulfillmentOrderAction.vue'
import OrderMasterDetail from '../../../components/sales/OrderMasterDetail.vue'
import AgCustomDocStatus from '../../../components/AgGrid/FulfillmentOrder/AgCustomDocStatus.vue'
import AgCustomInfoColumn from '../../../components/AgGrid/FulfillmentOrder/AgCustomInfoColumn.vue'
import AgCustomCurrency from '../../../components/AgGrid/FulfillmentOrder/AgCustomCurrency.vue'
import AgCustomLink from '../../../components/AgGrid/FulfillmentOrder/AgCustomLink.vue'
import AgCustomDateOrdered from '../../../components/AgGrid/FulfillmentOrder/AgCustomDateOrdered.vue'
import AgCustomOrderSource from '../../../components/AgGrid/FulfillmentOrder/AgCustomOrderSource.vue'
import AgMarketplaceLink from '../../../components/AgGrid/FulfillmentOrder/AgMarketplaceLink.vue'
import AgQtyTotal from '../../../components/AgGrid/FulfillmentOrder/AgQtyTotal.vue'
import AgCountry from '../../../components/AgGrid/FulfillmentOrder/AgCountry.vue'
import AgAddress from '../../../components/AgGrid/FulfillmentOrder/AgAddress.vue'
import AgAddressIndicator from '../../../components/AgGrid/FulfillmentOrder/AgAddressIndicator.vue'
import AgPriorityRule from '../../../components/AgGrid/FulfillmentOrder/AgPriorityRule.vue'

export default {
  components: {
    OrderAction,
    OrderMasterDetail,
    AgCustomDocStatus,
    AgCustomInfoColumn,
    AgCustomCurrency,
    AgCustomLink,
    AgCustomDateOrdered,
    AgCustomOrderSource,
    AgMarketplaceLink,
    AgQtyTotal,
    AgCountry,
    AgAddress,
    AgAddressIndicator,
    AgPriorityRule
  }
}
</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 { data: countries } = await useFetch('/api/settings/countries', {
  headers: useRequestHeaders(['cookie'])
})

const getRows = ref([])
const setRows = async () => {
  const offset = array.pageStart(currentPage.value, limitPerPage.value)
  const res = await $fetch(`/api/orders/fulfillment?limit=${limitPerPage.value}&offset=${offset}`, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    getRows.value = res?.records?.map(item => {
      return {
        marketplaceKey: item?.C_OrderSource_ID?.Marketplace.identifier || '',
        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 || {},
        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 || {},
        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 || '',
        orderSource: item.C_OrderSource_ID?.identifier || '',
        orderSourceId: item.C_OrderSource_ID?.id  || '',
        orderSourceName: item.C_OrderSource_ID?.Name || '',
        externalorderId: item.ExternalOrderId  || '',
        shopware6_order_id: item.shopware6_order_id || '',
        orderLines: item.c_orderline || [],
        country: item.C_BPartner_Location_ID?.C_Location_ID?.C_Country_ID?.identifier || '',
        countryId: item.C_BPartner_Location_ID?.C_Location_ID?.C_Country_ID?.id || '',
        countries: countries.value?.records || [],
      }
    })
    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: countries.value?.status || 200,
  message: countries.value?.message || ''
});
onBeforeMount(() => {
  if(Number(countries.value?.status || 200) === 401) {
    forcingLogout()
  }
})
watch(countries, () => {
  alert.value.status = countries.value?.status || 200
  alert.value.message = countries.value?.message || ''
  if(Number(countries.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,
    maxWidth: 30,
    cellRenderer: "agGroupCellRenderer"
  },
  { 
    field: 'documentNo',
    headerName: '#',
    maxWidth: 90,
    type: 'nonEditableColumn',
    cellRenderer: AgCustomLink,
    cellStyle: {textAlign: 'center'},
  },
  {
    field: 'orderSourceName',
    headerName: '#',
    maxWidth: 50,
    cellRenderer: AgCustomOrderSource,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'center'},
    sort: 'desc',
    sortable: true,
  },
  {
    field: 'externalorderId',
    headerName: '#',
    maxWidth: 90,
    type: 'nonEditableColumn',
    cellRenderer: AgMarketplaceLink,
    cellStyle: {textAlign: 'center'},
  },
  {
    field: 'organization',
    headerName: 'Org',
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'center'},
  },
  {
    field: 'currency',
    headerName: 'Cty',
    maxWidth: 50,
    cellRenderer: AgCountry,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'center'},
  },
  {
    field: 'dateOrdered',
    headerName: 'Ordered',
    maxWidth: 100,
    cellRenderer: AgCustomDateOrdered,
  },
  {
    field: 'partner',
    headerName: 'Partner',
    type: 'nonEditableColumn',
  },
  {
    field: 'partnerLocation',
    headerName: 'Address',
    type: 'nonEditableColumn',
    cellRenderer: AgAddress
  },
  {
    field: 'billPartnerLocation',
    headerName: 'Ship/Bill',
    type: 'nonEditableColumn',
    cellRenderer: AgAddressIndicator,
    maxWidth: 100
  },
  {
    field: 'docStatus',
    headerName: 'Status',
    cellRenderer: AgCustomDocStatus,
    type: 'nonEditableColumn',
    maxWidth: 100
  },
  {
    field: 'priorityRuleId',
    headerName: 'Priority',
    type: 'nonEditableColumn',
    cellRenderer: AgPriorityRule,
    maxWidth: 100
  },
  {
    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: 'Sales'},
  { link: '/sales/fulfillment-orders', text: 'Fulfillment Orders', active: true}
]))

const openTab = (toPath, pathName, oldPath = null) => {
  let comparePath = toPath
  if(oldPath) {
    comparePath = oldPath
  }
  tabs.value.map(item => {
    item.active = false
    return item
  })
  if(tabs.value.filter(i => i.link === comparePath).length >= 1) {
    const tabIndex = tabs.value.findIndex(i => i.link === comparePath)
    tabs.value[tabIndex].active = true
    if(oldPath) {
      tabs.value[tabIndex].link = toPath
      tabs.value[tabIndex].text = pathName
    }
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  } else {
    tabs.value.push({link: toPath, text: pathName, active: true})
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  }
  //location.href = toPath
}

const create = () => {
  //router.push('/sales/fulfillment-orders/create')
  //router.push('/sales/fulfillment-orders/add')
  openTab('/create/sales-fulfillment-order', 'Fulfillment Order: New')
}

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: 'documentNo',
        headerName: '#',
        maxWidth: 60,
        type: 'nonEditableColumn',
        cellRenderer: AgCustomLink,
        cellStyle: {textAlign: 'center'},
        suppressHeaderMenuButton: true,
        suppressHeaderFilterButton: true,
        suppressHeaderContextMenu: true
      },
      {
        field: 'orderSource',
        headerName: '#',
        maxWidth: 45,
        cellRenderer: AgCustomOrderSource,
        type: 'nonEditableColumn',
        cellStyle: {textAlign: 'center'},
        sortable: false,
        filter: false,
        suppressHeaderMenuButton: true,
        suppressHeaderFilterButton: true,
        suppressHeaderContextMenu: true
      },
      {
        field: 'dateOrdered',
        headerName: 'Ordered',
        maxWidth: 80,
        cellRenderer: AgCustomDateOrdered,
        filter: false,
        floatingFilter: true,
        suppressHeaderMenuButton: true,
        suppressHeaderFilterButton: true,
        suppressHeaderContextMenu: true
      },
      {
        field: 'partner',
        headerName: 'Partner',
        maxWidth: 100,
        type: 'nonEditableColumn',
        floatingFilter: true,
        suppressHeaderMenuButton: true,
        suppressHeaderFilterButton: true,
        suppressHeaderContextMenu: true
      },
      {
        field: 'docStatus',
        headerName: 'Status',
        maxWidth: 65,
        cellRenderer: AgCustomDocStatus,
        type: 'nonEditableColumn',
        suppressHeaderMenuButton: true,
        suppressHeaderFilterButton: true,
        suppressHeaderContextMenu: true
      }
    ]
  } 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" />
      <SalesOrderQuickView />
    </Teleport>
  </NuxtLayout>
</template>

