<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 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
    // AgCustomShipStatus
  }
}
</script>

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

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

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

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

const { data } = await useFetch('/api/partners/greetings', {
  headers: useRequestHeaders(['cookie'])
})

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 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 colDefaultDefs = ref([
  { 
    maxWidth: 40,
    checkboxSelection: checkboxSelection,
    headerCheckboxSelection: headerCheckboxSelection
  },
  { 
    field: 'id',
    //hide: true,
    sort: 'desc',
    maxWidth: 30,
    cellRenderer: "agGroupCellRenderer",
    filter: "agNumberColumnFilter",
    type: 'nonEditableColumn',
  },
  { 
    field: 'documentNo',
    headerName: '#',
    maxWidth: 90,
    type: 'nonEditableColumn',
    cellRenderer: AgCustomLink,
    cellStyle: {textAlign: 'center'},
    floatingFilter: true,
  },
  {
    field: 'orderSource',
    headerName: '#',
    maxWidth: 50,
    cellRenderer: AgCustomOrderSource,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'center'},
    sortable: true,
    filter: "agTextColumnFilter",
  },
  {
    field: 'externalorderId',
    headerName: 'Extern OrderID',
    maxWidth: 550,
    type: 'nonEditableColumn',
    cellRenderer: AgMarketplaceLink,
    cellStyle: {textAlign: 'center'},
    filter: "agNumberColumnFilter",
    floatingFilter: true,
  },
  // {
  //   field: 'shipStatus',
  //   headerName: 'Versand',
  //   cellRenderer: AgCustomShipStatus,
  //   type: 'nonEditableColumn',
  //   maxWidth: 100
  // },
  {
    field: 'organization',
    headerName: 'Org',
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'center'},
    filter: "agTextColumnFilter",
    floatingFilter: false,
  },
  {
    // field: 'dateOrdered',
    headerName: 'Bestellt',
    maxWidth: 90,
    cellRenderer: AgCustomDateOrdered,
    filter: "agDateColumnFilter",
    filterParams: filterParams,
    type: 'nonEditableColumn',
    floatingFilter: true,
  },
  {
    field: 'dateCreated',
    headerName: 'Importiert',
    maxWidth: 150,
    cellRenderer: AgCustomDateCreated,
    filter: "agDateColumnFilter",
    filterParams: filterParams,
    type: 'nonEditableColumn',
    floatingFilter: true,
  },

  {
    field: 'partnerLocationName',
    headerName: 'Name',
    type: 'editableColumn',
    filter: "agTextColumnFilter",
    cellRenderer: AgAddressName,
    maxWidth: 150,
    floatingFilter: true,
  },
  {
    field: 'currency',
    headerName: '',
    maxWidth: 50,
    cellRenderer: AgCountry,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'center'},
    sortable: false,
    filter: "agTextColumnFilter",
  },
  {
    field: 'locationStreet',
    headerName: 'Straße',
    type: 'editableColumn',
    cellRenderer: AgAddressStreet,
    maxWidth: 200,
    floatingFilter: true,
  },
  {
    field: 'locationStreet2',
    headerName: 'Zusatz',
    type: 'editableColumn',
    cellRenderer: AgAddressStreet2,
    maxWidth: 150,
    floatingFilter: true,
  },
  {
    field: 'locationZipCode',
    headerName: 'Postleitzahl',
    type: 'editableColumn',
    cellRenderer: AgAddressZipCode,
    maxWidth: 70,
    floatingFilter: true,
  },
  {
    field: 'locationCity',
    headerName: 'Stadt',
    type: 'editableColumn',
    cellRenderer: AgAddressCity,
    maxWidth: 130,
    floatingFilter: true,
  },
  // {
  //   field: 'billPartnerLocation',
  //   headerName: 'LR?',
  //   type: 'nonEditableColumn',
  //   cellRenderer: AgAddressIndicator,
  //   maxWidth: 50
  // },
  // {
  //   field: 'docStatus',
  //   headerName: 'Status',
  //   cellRenderer: AgCustomDocStatus,
  //   type: 'nonEditableColumn',
  //   maxWidth: 100
  // },
  // {
  //   field: 'priorityRuleId',
  //   headerName: 'Prio',
  //   type: 'nonEditableColumn',
  //   cellRenderer: AgPriorityRule,
  //   maxWidth: 55
  // },
  {
    headerName: 'Info',
    minWidth: 100,
    cellRenderer: AgCustomInfoColumn,
    type: 'nonEditableColumn',
    cellStyle: {textAlign: 'center'},
    maxWidth: 155,
    floatingFilter: true,
  },
  {
    headerName: 'Tracking',
    minWidth: 115,
    type: 'nonEditableColumn',
    cellRenderer: AgCustomTrackingNo,
    cellStyle: {textAlign: 'center'},
    filter: "agTextColumnFilter",
    floatingFilter: true,
  },
  {
    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: 80,
    filter: "agNumberColumnFilter",
    floatingFilter: true,

  },
  {
    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) {
    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) {
    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 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()
  }
}

const returnHandler = () => {
  openTab('/create/sales-order-return', 'Sales Order: Return')
}

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

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

const rowClassRules = ref({
  'redRow': (params) => {
    let numDays = 0
    if(params.data?.dateCreated) {
      numDays = date.daysInBetween(params.data.dateCreated, new Date())
    }
    return numDays > 4 && !params.data.minout?.[0]?.id
  },
  'orangeRow': (params) => {
    let numDays = 0
    if(params?.data?.dateCreated) {
      numDays = date.daysInBetween(params.data.dateCreated, 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
  },
})

const filterBySwitch = ref({
  withoutShipments: false,
  notShipped5Days: false,
  quickShip: false
})
const urlBySwitch = ref('orders/ag-grid/so')
const changeBySwitch = (withoutShipments, notShipped5Days, quickShip) => {
  filterBySwitch.value.withoutShipments = withoutShipments
  filterBySwitch.value.notShipped5Days = notShipped5Days
  filterBySwitch.value.quickShip = quickShip

  if(filterBySwitch.value.withoutShipments) {
    urlBySwitch.value = 'orders/ag-grid/notfulfilled'
  } else if(filterBySwitch.value.notShipped5Days) {
    urlBySwitch.value = 'orders/ag-grid/notfulfilled-5days'
  } else if(filterBySwitch.value.quickShip) {
    urlBySwitch.value = 'orders/ag-grid/notfulfilled-fastlane'
  } else {
    urlBySwitch.value = 'orders/ag-grid/so'
  }
}
</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">
          <button type="button" @click="returnHandler" class="button is-success">
            <span class="tf-icon ti ti-truck-return ti-sm me-1 color-inherit pointerEvents-none"></span>
            Quick Return
          </button>
          <button type="button" @click="oldHandler" class="button is-success">
            <span class="tf-icon ti ti-table ti-sm me-1 color-inherit pointerEvents-none"></span>
            Old Table
          </button>
        </HeaderAction>
        <div>
          <div>
            <AlertBox :alert="alert" />
            <div 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 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">Not Fulfilled Orders</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">
              <ClientOnly>
                <AgGridServer :columns="colDefs" :masterDetail="true" :masterDetailRenderer="masterDetailRenderer" :masterDetailParams="masterDetailParams" :columnMenu="columnMenu" @cellClick="cellClick" @cellChange="cellChange" :sourceEndpoint="urlBySwitch" :rowClassRules="rowClassRules" :filterBySwitch="filterBySwitch" />
              </ClientOnly>
            </div>
          </div>
        </div>
      </div>

    </div>

    <Teleport to="body">
      <PrintPreview modelName="orders" />
      <SalesOrderQuickView />
    </Teleport>
  </NuxtLayout>
</template>

<style scoped>
.tf-icon.ti.ti-circle-check.ti-md.cursor-pointer {
  font-size: 22px !important;
  --ag-advanced-filter-builder-indent-size: ;
  margin-top: -1px;
}
</style>