<script>
import OrderAction from '../../../components/sales/OrderAction.vue'
import OrderMasterDetail from '../../../components/sales/OrderMasterDetail.vue'
import AgCustomDocStatus from '../../../components/AgGrid/SalesOrder/AgCustomDocStatus.vue'
import AgCustomInfoColumn from '../../../components/AgGrid/SalesOrder/AgCustomInfoColumn.vue'
import AgCustomCurrency from '../../../components/AgGrid/SalesOrder/AgCustomCurrency.vue'
import AgCustomLink from '../../../components/AgGrid/SalesOrder/AgCustomLink.vue'
import AgCustomDateOrdered from '../../../components/AgGrid/SalesOrder/AgCustomDateOrdered.vue'
import AgCustomDateCreated from '../../../components/AgGrid/SalesOrder/AgCustomDateCreated.vue'
import AgCustomOrderSource from '../../../components/AgGrid/SalesOrder/AgCustomOrderSource.vue'
import AgMarketplaceLink from '../../../components/AgGrid/SalesOrder/AgMarketplaceLink.vue'
import AgQtyTotal from '../../../components/AgGrid/SalesOrder/AgQtyTotal.vue'
import AgCountry from '../../../components/AgGrid/SalesOrder/AgCountry.vue'
import AgAddress from '../../../components/AgGrid/SalesOrder/AgAddress.vue'
import AgAddressStreet from '../../../components/AgGrid/SalesOrder/AgAddressStreet.vue'
import AgAddressStreet2 from '../../../components/AgGrid/SalesOrder/AgAddressStreet2.vue'
import AgAddressZipCode from '../../../components/AgGrid/SalesOrder/AgAddressZipCode.vue'
import AgAddressCity from '../../../components/AgGrid/SalesOrder/AgAddressCity.vue'
import AgAddressIndicator from '../../../components/AgGrid/SalesOrder/AgAddressIndicator.vue'
import AgPriorityRule from '../../../components/AgGrid/SalesOrder/AgPriorityRule.vue'
import AgCustomTrackingNo from "~/components/AgGrid/SalesOrder/AgCustomTrackingNo.vue"
import AgAddressName from "~/components/AgGrid/SalesOrder/AgAddressName.vue"
import AgDocumentNoFilter from "~/components/AgGrid/SalesOrder/AgDocumentNoFilter.vue"
import AgExternalOrderIdFilter from "~/components/AgGrid/SalesOrder/AgExternalOrderIdFilter.vue"
import AgShipper from "~/components/AgGrid/SalesOrder/AgShipper.vue"
import AgCustomAttachment from "~/components/AgGrid/SalesOrder/AgCustomAttachment.vue"

import PaginationBox from '../../../components/PaginationBox.vue'
// import AgCustomShipStatus from "~/components/AgGrid/SalesOrder/AgCustomShipStatus.vue"

export default {
  components: {
    OrderAction,
    OrderMasterDetail,
    AgCustomDocStatus,
    AgCustomInfoColumn,
    AgCustomCurrency,
    AgCustomLink,
    AgCustomDateOrdered,
    AgCustomOrderSource,
    AgMarketplaceLink,
    AgQtyTotal,
    AgCountry,
    AgAddress,
    AgAddressIndicator,
    AgPriorityRule,
    AgCustomTrackingNo,
    AgAddressName,
    AgDocumentNoFilter,
    AgExternalOrderIdFilter,
    AgShipper,
    AgCustomAttachment
  }
}
</script>

<script setup>
import { array, date, string } from 'alga-js'
import { toast } from 'bulma-toast'

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

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 filterBySwitch = ref({
  withoutShipments: false,
  notShipped5Days: false,
  quickShip: false
})
const urlBySwitch = ref('orders/sales/so')

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)
  let filter = ''

  const filterDocumentNo = dataTableFilters.value?.['salesOrder']?.['documentNo'] ?? ''
  if(filterDocumentNo !== '') {
    filter += string.urlEncode(` AND contains(DocumentNo,'${filterDocumentNo}')`)
  } else {
    filter = filter.replace(string.urlEncode(` AND contains(DocumentNo,'${filterDocumentNo}')`), '')
  }

  const filterExternalOrderId = dataTableFilters.value?.['salesOrder']?.['externalOrderId'] ?? ''
  if(filterExternalOrderId !== '') {
    filter += string.urlEncode(` AND (contains(ExternalOrderId,'${filterExternalOrderId}') OR contains(externalOrderId,'${filterExternalOrderId}'))`)
  } else {
    filter = filter.replace(string.urlEncode(` AND (contains(ExternalOrderId,'${filterExternalOrderId}') OR contains(externalOrderId,'${filterExternalOrderId}'))`), '')
  }

  const res = await $fetch(`/api/${urlBySwitch.value}?limit=${limitPerPage.value}&offset=${offset}&filter=${filter}`, {
    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 ?? item.isActive,
        documentNo: item.DocumentNo ?? item.documentNo,
        description: item.Description ?? item.description,
        isApproved: item.IsApproved ?? item.isApproved,
        isCreditApproved: item.IsCreditApproved ?? item.isCreditApproved,
        isDelivered: item.IsDelivered ?? item.isDelivered,
        isInvoiced: item.IsInvoiced ?? item.isInvoiced,
        isPrinted: item.IsPrinted ?? item.isPrinted,
        isTransferred: item.IsTransferred ?? item.isTransferred,
        dateOrdered: item.DateOrdered ?? item.dateOrdered,
        datePromised: item.DatePromised ?? item.datePromised,
        dateAcct: item.DateAcct ?? item.dateAcct,
        created: item.Created ?? item.created,
        freightAmt: item.FreightAmt ?? item.freightAmt,
        totalLines: item.TotalLines ?? item.totalLines,
        grandTotal: item.GrandTotal ?? item.grandTotal,
        chargeAmt: item.ChargeAmt ?? item.chargeAmt,
        processed: item.Processed ?? item.processed,
        isSOTrx: item.IsSOTrx ?? item.isSOTrx,
        isDiscountPrinted: item.IsDiscountPrinted ?? item.isDiscountPrinted,
        isTaxIncluded: item.IsTaxIncluded ?? item.isTaxIncluded,
        isSelected: item.IsSelected ?? item.isSelected,
        sendEMail: item.SendEMail ?? item.sendEMail,
        isSelfService: item.IsSelfService ?? item.isSelfService,
        isDropShip: item.IsDropShip ?? item.isDropShip,
        processedOn: item.ProcessedOn ?? item.processedOn,
        isPayScheduleValid: item.IsPayScheduleValid ?? item.isPayScheduleValid,
        isPriviledgedRate: item.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 || '',
        partnerLocationName: item.C_BPartner_Location_ID?.Name || '',
        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 || '',
        client: item.AD_Client_ID?.identifier || '',
        clientId: item.AD_Client_ID?.id || '',
        orderSource: item.C_OrderSource_ID || {},
        orderSourceId: item.C_OrderSource_ID?.id  || '',
        orderSourceName: item.C_OrderSource_ID?.Name || '',
        externalorderId: item.ExternalOrderId || item.externalOrderId || '',
        shopware6_order_id: item.shopware6_order_id || '',
        shopify_order_id: item.shopify_order_id || '',
        amazon_order_id: item.amazon_order_id || '',
        plentyone_order_id: item.plentyone_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 || [],
        location: item.C_BPartner_Location_ID?.C_Location_ID || {},
        locationStreet: item.C_BPartner_Location_ID?.C_Location_ID?.Address1 || '',
        locationStreet2: item.C_BPartner_Location_ID?.C_Location_ID?.Address2 || '',
        name2: item.C_BPartner_Location_ID?.Name2 || '',
        locationZipCode: item.C_BPartner_Location_ID?.C_Location_ID?.Postal || '',
        locationCity: item.C_BPartner_Location_ID?.C_Location_ID?.City || '',
        minout: item.m_inout || [],
        shipperId: item.M_Shipper_ID?.id || '',
        shipper: item.M_Shipper_ID?.identifier || ''
      }
    })
    totalPages.value = array.pages(res?.['row-count'] ?? 0, limitPerPage.value)
  }
}
onBeforeMount(setRows)
watch(currentPage, setRows)
watch(dataTableFilters, setRows)
const handlePage = async (page) => {
  currentPage.value = page || 1
  await setRows()
}

const changeBySwitch = (withoutShipments, notShipped5Days, quickShip) => {
  filterBySwitch.value.withoutShipments = withoutShipments
  filterBySwitch.value.notShipped5Days = notShipped5Days
  filterBySwitch.value.quickShip = quickShip

  if(filterBySwitch.value.withoutShipments) {
    urlBySwitch.value = 'orders/sales/notfulfilled'
  } else if(filterBySwitch.value.notShipped5Days) {
    urlBySwitch.value = 'orders/sales/notfulfilled-5days'
  } else if(filterBySwitch.value.quickShip) {
    urlBySwitch.value = 'orders/sales/notfulfilled-fastlane'
  } else {
    urlBySwitch.value = 'orders/sales/so'
  }

  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 filterParams = {
  comparator: (filterLocalDateAtMidnight, cellValue) => {
    const dateAsString = cellValue;
    if (dateAsString == null) return -1;
    const dateParts = dateAsString.split("/");
    const cellDate = new Date(
        Number(dateParts[2]),
        Number(dateParts[1]) - 1,
        Number(dateParts[0]),
    );

    if (filterLocalDateAtMidnight.getTime() === cellDate.getTime()) {
      return 0;
    }

    if (cellDate < filterLocalDateAtMidnight) {
      return -1;
    }

    if (cellDate > filterLocalDateAtMidnight) {
      return 1;
    }
    return 0;
  },
}

const { getMenuType } = useRoleMenu()

// This will be set using the composable method
const defaultSideBarMenu = ref('Menu')

// Use the centralized role menu composable

// Use a computed property that will be reactive
const isFulCustomer = computed(() => getMenuType())

const colDefaultDefs = ref([
  // {
  //   maxWidth: 40,
  //   checkboxSelection: checkboxSelection,
  //   headerCheckboxSelection: headerCheckboxSelection
  // },
  {
    field: 'shipmentStatus',
    headerName: 'Status',
    minWidth: 118,
    maxWidth: 118,
    cellRenderer: AgCustomDocStatus,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'center'},
    // sort: 'desc',
    sortable: true,
    /*filter: "agTextColumnFilter",*/
  },
  {
    field: 'id',
    //hide: true,
    maxWidth: 30,
    cellRenderer: "agGroupCellRenderer",
    type: 'nonEditableColumn',
    /*filter: "agNumberColumnFilter",*/
    sort: 'desc',

  },
  {
    field: 'documentNo',
    headerName: '#',
    maxWidth: 90,
    type: 'nonEditableColumn',
    cellRenderer: AgCustomLink,
    cellStyle: {textAlign: 'center'},
    filter: AgDocumentNoFilter
  },
  {
    field: 'organization',
    headerName: 'Org',
    maxWidth: 150,
    resizable: true,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'center'},
    hide: computed(() => isFulCustomer.value === 'c'),
  },
  {
    field: 'orderSourceName',
    headerName: 'Quel.',
    resizable: true,
    maxWidth: 50,
    cellRenderer: AgCustomOrderSource,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'center'},
    // sort: 'desc',
    sortable: true,
    /*filter: "agTextColumnFilter",*/
  },
  {
    field: 'externalorderId',
    headerName: 'Extern',
    minWidth: 90,
    maxWidth: 90,
    resizable: true,
    type: 'nonEditableColumn',
    cellRenderer: AgMarketplaceLink,
    cellStyle: {textAlign: 'right'},
    filter: AgExternalOrderIdFilter,
  },
  // {
  //   field: 'dateOrdered',
  //   headerName: 'Bestellt',
  //   resizable: true,
  //   maxWidth: 50,
  //   cellRenderer: AgCustomDateOrdered,
  //   type: 'nonEditableColumn',
  //   /*filter: "agDateColumnFilter",
  //   filterParams: filterParams,
  //   floatingFilter: true,*/
  //   hide: computed(() => isFulCustomer.value === 'c')
  // },
  {
    field: 'dateAcct',
    headerName: 'imp',
    resizable: true,
    maxWidth: 65,
    cellRenderer: AgCustomDateCreated,
    type: 'nonEditableColumn',
    /*filter: "agDateColumnFilter",
    filterParams: filterParams,
    floatingFilter: true,*/
  },
  {
    headerName: 'Files',
    minWidth: 90,
    maxWidth: 200,
    type: 'nonEditableColumn',
    cellRenderer: AgCustomAttachment,
    cellStyle: {textAlign: 'center'}
  },
  {
    field: 'shipper',
    headerName: 'Versand',
    maxWidth: 70,
    cellRenderer: AgShipper,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'center'},
    /*sortable: false,
    filter: "agTextColumnFilter",*/
  },
  {
    field: 'partnerLocationName',
    headerName: 'Name',
    maxWidth: 170,
    resizable: true,
    type: 'editableColumn',
    cellRenderer: AgAddressName,
    /*filter: "agTextColumnFilter",
    floatingFilter: true,*/
  },
  {
    field: 'locationStreet2',
    headerName: 'Zusatz',
    type: 'editableColumn',
    cellRenderer: AgAddressStreet2,
    maxWidth: 120,
    /*floatingFilter: true,*/
    // hide: computed(() => isFulCustomer.value === 'c')
  },
  {
    field: 'locationZipCode',
    headerName: 'Postleitzahl',
    resizable: true,
    type: 'editableColumn',
    cellRenderer: AgAddressZipCode,
    maxWidth: 70,
    /*floatingFilter: true,*/
    // hide: computed(() => isFulCustomer.value === 'c')
  },
  {
    field: 'locationStreet',
    headerName: 'Straße',
    type: 'editableColumn',
    cellRenderer: AgAddressStreet,
    maxWidth: 200,
    /*floatingFilter: true,*/
    // hide: computed(() => isFulCustomer.value === 'c')
  },
  {
    field: 'locationCity',
    headerName: 'Stadt',
    type: 'editableColumn',
    cellRenderer: AgAddressCity,
    maxWidth: 130,
    /*floatingFilter: true,*/
    hide: computed(() => isFulCustomer.value === 'c')
  },
  {
    field: 'currency',
    headerName: '',
    maxWidth: 50,
    cellRenderer: AgCountry,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'center'},
    /*sortable: false,
    filter: "agTextColumnFilter",*/
  },
  // {
  //   field: 'name2',
  //   headerName: 'Name2',
  //   valueGetter: (params) => {
  //     return params.data.name2 !== params.data.partnerLocationName ? params.data.name2 : ''
  //   },
  //   hide: computed(() => isFulCustomer.value === 'c')
  // },

  // {
  //   headerName: 'Info',
  //   minWidth: 155,
  //   cellRenderer: AgCustomInfoColumn,
  //   type: 'nonEditableColumn',
  //   cellStyle: {textAlign: 'center'},
  //   maxWidth: 175,
  //   /*floatingFilter: true,*/
  //   hide: computed(() => isFulCustomer.value === 'c')
  // },
  {
    headerName: 'Tracking',
    minWidth: 140,
    type: 'nonEditableColumn',
    cellRenderer: AgCustomTrackingNo,
    cellStyle: {textAlign: 'center'},
    /*filter: "agTextColumnFilter",
    floatingFilter: true,*/
    // hide: computed(() => isFulCustomer.value === 'c')
  },
  {
    headerName: 'M',
    cellRenderer: AgQtyTotal,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'right'},
    maxWidth: 40,
    /*floatingFilter: true,*/
  },
  {
    field: 'grandTotal',
    headerName: 'Total',
    cellRenderer: AgCustomCurrency,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'right'},
    minWidth: 40,
    /*filter: "agNumberColumnFilter",
    floatingFilter: true,*/
    hide: computed(() => isFulCustomer.value === 'c')
  },
  {
    headerName: 'Action',
    width: 100,
    pinned: 'right',
    cellRenderer: OrderAction,
    type: 'nonEditableColumn',
  }
]);
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.partnerLocationName !== event.data.partnerLocation.Name) {
    if(!event.data.minout?.[0]?.TrackingNo) {
      const res = await $fetch(`/api/partners/partners/${event.data.partnerLocation.id}/locations`, {
        method: 'PUT',
        headers: useRequestHeaders(['cookie']),
        body: {
          id: event.data.partnerLocation.id,
          isActive: event.data.partnerLocation.IsActive,
          name: event.data.partnerLocationName,
          phone: event.data.partnerLocation.Phone,
          phone2: event.data.partnerLocation.Phone2,
          fax: event.data.partnerLocation.Fax,
          ISDN: event.data.partnerLocation.ISDN,
          isBillTo: event.data.partnerLocation.IsBillTo,
          isShipTo: event.data.partnerLocation.IsShipTo,
          isPayFrom: event.data.partnerLocation.IsPayFrom,
          isRemitTo: event.data.partnerLocation.IsRemitTo,
          isPreserveCustomName: event.data.partnerLocation.IsPreserveCustomName,
        }
      })
      if(res?.status == 200) {
        toast({
          message: 'Partner Location Name have been patched',
          type: 'is-success',
          duration: 2000
        })
      } else {
        toast({
          message: 'Failed in patching Partner Location Name',
          type: 'is-danger',
          duration: 2000
        })
        event.data.partnerLocationName = event.data.partnerLocation.Name
      }
    }
  } else if(event.data.locationStreet !== event.data.location?.Address1 || event.data.locationStreet2 !== event.data.location?.address2 || event.data.locationZipCode !== event.data.location?.Postal || event.data.locationCity !== event.data.location?.City) {
    if(!event.data.minout?.[0]?.TrackingNo) {
      const res = await $fetch('/api/settings/locations/ag-grid', {
        method: 'PUT',
        headers: useRequestHeaders(['cookie']),
        body: {
          id: event.data.location?.id || '-',
          address1: event.data.locationStreet,
          address2: event.data.locationStreet2,
          postal: event.data.locationZipCode,
          city: event.data.locationCity,
        }
      })
      if(res?.status == 200) {
        toast({
          message: 'Location Street, Zip Code and City have been patched',
          type: 'is-success',
          duration: 2000
        })
      } else {
        toast({
          message: 'Failed in patching location',
          type: 'is-danger',
          duration: 2000
        })
      }
    }
  } /*else {
    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/orders', text: '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/orders/create')
  //router.push('/sales/orders/add')
  openTab('/create/sales-order', 'Sales Order: New')
}

const newHandler = () => {
  router.push('/sales/orders')
}

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: 'dateAcct',
        headerName: 'Import',
        maxWidth: 90,
        cellRenderer: AgCustomDateCreated,
        type: 'nonEditableColumn',
        /*filter: "agDateColumnFilter",
        filterParams: filterParams,
        floatingFilter: true,*/
      },
      {
        field: 'shipmentStatus',
        headerName: 'Status',
        cellRenderer: AgCustomDocStatus,
        type: 'nonEditableColumn',
        maxWidth: 120,
        /*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: 'organization',
        headerName: 'Org',
        type: 'nonEditableColumn',
        cellStyle: {textAlign: 'center'},
        /*filter: "agTextColumnFilter",
        floatingFilter: false,*/
        hide: computed(() => isFulCustomer.value === 'c')
      },
      {
        field: 'partner',
        headerName: 'Kunde',
        type: 'nonEditableColumn',
        /*floatingFilter: true,
        suppressHeaderMenuButton: true,
        suppressHeaderFilterButton: true,
        suppressHeaderContextMenu: true*/
      }
    ]
  } else {
    colDefs.value = colDefaultDefs.value
  }
}

onMounted(() => {
  agGridMobileColumns()
  window.onresize = agGridMobileColumns;
  defaultSideBarMenu.value = getMenuType()

})
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
        }
      ]);
    }
  }*/
})

//Setting Cell Row Color based on conditions
const rowClassRules = ref({
  // 'greyRow': (params) => {
  //   let numDays = 1
  //   if(params.data?.docStatus == 'Voided')
  //
  //   return numDays
  // },
  // 'redRow': (params) => {
  //   let numDays = 0
  //   if(params.data?.created && params.data?.docStatus !== 'Voided') {
  //     numDays = date.daysInBetween(params.data.created, new Date())
  //   }
  //   return numDays > 4 && !params.data.minout?.[0]?.id
  // },
  // 'orangeRow': (params) => {
  //   let numDays = 0
  //   if(params?.data?.created) {
  //     numDays = date.daysInBetween(params.data.created, new Date())
  //   }
  //   return numDays > 2 && numDays <= 4 && !params.data.minout?.[0]?.id
  // },
  'tealRow': (params) => {
    let numStreet = false
    if(params.data?.locationStreet) {
      const match = params.data.locationStreet.match(/(\d+[a-zA-Z]*.*)$/)
      numStreet = match ? false : true
    }
    return numStreet
  },
  // 'greenRow': (params) => {
  //   let numDays = 0
  //   if(params.data.minout?.[0]?.TrackingNo) {
  //     return true
  //   }
  // },
})
let mql = window.matchMedia("(max-width: 960px)")
</script>

<template>
  <Head>
    <Title>Orders</Title>
  </Head>
  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    <div>
      <div class="banner datatable-wrapper aggridnopadding">
        <HeaderAction :isDeletable="isDeletable" @create="create" @destroy="destroy">
          <!--          <button type="button" @click="newHandler" class="button is-success">-->
          <!--            <span class="tf-icon ti ti-table ti-sm me-1 color-inherit pointerEvents-none"></span>-->
          <!--            New Table-->
          <!--          </button>-->
        </HeaderAction>
        <div>
          <div>
            <AlertBox :alert="alert" />
            <div v-if="!mql.matches" class="mb-5 mt-4">
              <div class="d-flex items-center gap-10px">
                <!--                <div class="d-flex items-center">-->
                <!--                  <span class="tf-icon ti ti-filter ti-sm me-1 cursor-pointer" title="Filter"></span>-->
                <!--                  <strong>Filter</strong>-->
                <!--                </div>-->
                <div v-if="defaultSideBarMenu !== 'c'" class="d-flex items-center">
                  <div class="switch">
                    <input type="checkbox" class="switchInput" id="withoutShipments" @change="changeBySwitch(!filterBySwitch.withoutShipments, false, false)" :checked="filterBySwitch.withoutShipments === true">
                    <label class="switchLabel" for="withoutShipments">Open</label>
                  </div>
                  <!--                  <div class="switch">-->
                  <!--                    <input type="checkbox" class="switchInput" id="notShipped5Days" @change="changeBySwitch(false, !filterBySwitch.notShipped5Days, false)" :checked="filterBySwitch.notShipped5Days === true">-->
                  <!--                    <label class="switchLabel" for="notShipped5Days">Not Fulfilled Orders Older 5 Days</label>-->
                  <!--                  </div>-->
                  <!--                  <div class="switch">-->
                  <!--                    <input type="checkbox" class="switchInput" id="quickShip" @change="changeBySwitch(false, false, !filterBySwitch.quickShip)" :checked="filterBySwitch.quickShip === true">-->
                  <!--                    <label class="switchLabel" for="quickShip">Not Fulfilled Orders with High Priority</label>-->
                  <!--                  </div>-->
                </div>
              </div>
            </div>
            <div class="mb-3">
              <AgGridCustom :entries="getRows" :columns="colDefs" :masterDetail="true" :masterDetailRenderer="masterDetailRenderer" :masterDetailParams="masterDetailParams" :columnMenu="columnMenu" @cellClick="cellClick" @cellChange="cellChange" :rowClassRules="rowClassRules" />
            </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 />
      <SalesShipmentGeneration />
    </Teleport>
  </NuxtLayout>
</template>

<style scoped>
main .container .banner.aggridnopadding {
  padding: 1px !important;
  padding-bottom: 15px !important;
}

</style>