<script>
import PartnerAction from '../../../components/partners/PartnerAction.vue'
import AgCustomLinkValue from '../../../components/AgGrid/Partners/AgCustomLinkValue.vue'


export default {
  components: {
    PartnerAction,
    AgCustomLinkValue
  }
}
</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/partners/partners', {
  headers: useRequestHeaders(['cookie'])
})

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    name: item.Name,
    email: item.EMail,
    value: item.Value,
    isActive: item.IsActive,
    salesVolume: item.SalesVolume,
    numberEmployees: item.NumberEmployees,
    isSummary: item.IsSummary,
    isVendor: item.IsVendor,
    isCustomer: item.IsCustomer,
    isProspect: item.IsProspect,
    soCreditLimit: item.SO_CreditLimit,
    soCreditUsed: item.SO_CreditUsed,
    acqusitionCost: item.AcqusitionCost,
    potentialLifeTimeValue: item.PotentialLifeTimeValue,
    actualLifeTimeValue: item.ActualLifeTimeValue,
    shareOfCustomer: item.ShareOfCustomer,
    isEmployee: item.IsEmployee,
    isSalesRep: item.IsSalesRep,
    isOneTime: item.IsOneTime,
    isTaxExempt: item.IsTaxExempt,
    isDiscountPrinted: item.IsDiscountPrinted,
    sendEMail: item.SendEMail,
    totalOpenBalance: item.TotalOpenBalance,
    isPOTaxExempt: item.IsPOTaxExempt,
    isManufacturer: item.IsManufacturer,
    is1099Vendor: item.Is1099Vendor,
    invoiceRule: item.InvoiceRule?.identifier || '',
    invoiceRuleId: item.InvoiceRule?.id || '',
    deliveryRule: item.DeliveryRule?.identifier || '',
    deliveryRuleId: item.DeliveryRule?.id || '',
    paymentRule: item.PaymentRule?.identifier || '',
    paymentRuleId: item.PaymentRule?.id || '',
    paymentRulePO: item.PaymentRulePO?.identifier || '',
    paymentRulePOId: item.PaymentRulePO?.id || '',
    soCreditStatus: item.SOCreditStatus?.identifier || '',
    soCreditStatusId: item.SOCreditStatus?.id || '',
    partnerGroup: item.C_BP_Group_ID?.identifier || '',
    partnerGroupId: item.C_BP_Group_ID?.id || '',
    priceList: item.M_PriceList_ID?.identifier || '',
    priceListId: item.M_PriceList_ID?.id || '',
    poPriceList: item.PO_PriceList_ID?.identifier || '',
    poPriceListId: item.PO_PriceList_ID?.id || '',
    discountSchema: item.M_DiscountSchema_ID?.identifier || '',
    discountSchemaId: item.M_DiscountSchema_ID?.id || '',
    poDiscountSchema: item.PO_DiscountSchema_ID?.identifier || '',
    poDiscountSchemaId: item.PO_DiscountSchema_ID?.id || '',
    paymentTerm: item.C_PaymentTerm_ID?.identifier || '',
    paymentTermId: item.C_PaymentTerm_ID?.id || '',
    poPaymentTerm: item.PO_PaymentTerm_ID?.identifier || '',
    poPaymentTermId: item.PO_PaymentTerm_ID?.id || '',
    language: item.AD_Language?.identifier || '',
    languageId: item.AD_Language?.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 colDefs = ref([
  {
    width: 20,
    checkboxSelection: checkboxSelection,
    headerCheckboxSelection: headerCheckboxSelection
  },
  {
    field: 'id',
    //hide: true,
    sort: 'desc'
  },
  { 
    field: 'name',
    cellRenderer: AgCustomLinkValue,
    minWidth: 200,
    filter: true,
    floatingFilter: true,
    suppressHeaderMenuButton: true,
    suppressHeaderFilterButton: true,
    suppressHeaderContextMenu: true
  },
  { 
    field: 'email',
    minWidth: 200,
    filter: true,
    floatingFilter: true,
    suppressHeaderMenuButton: true,
    suppressHeaderFilterButton: true,
    suppressHeaderContextMenu: true
  },
  {
    headerName: 'Org',
    field: 'organization',
    type: 'nonEditableColumn',
    filter: true,
    floatingFilter: true,
    suppressHeaderMenuButton: true,
    suppressHeaderFilterButton: true,
    suppressHeaderContextMenu: true
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  { 
    field: 'isVendor',
    headerName: 'Vendor'
  },
  { 
    field: 'isCustomer',
    headerName: 'Customer'
  },
  {
    field: 'isEmployee',
    headerName: 'Employee'
  },
  {
    field: 'isSalesRep',
    headerName: 'Sales Representative'
  },
  { 
    field: 'totalOpenBalance',
    headerName: 'Total Open Balance'
  },
  {
    field: 'action',
    width: 100,
    pinned: 'right',
    cellRenderer: PartnerAction,
    type: 'nonEditableColumn'
  }
]);

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) => {
  const res = await $fetch('/api/partners/partners/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: event.data.id,
      name: event.data.name,
      EMail: event.data.email,
      isActive: event.data.isActive,
      value: event.data.value,
      description: event.data.description,
      salesVolume: event.data.salesVolume,
      numberEmployees: event.data.numberEmployees,
      isSummary: event.data.isSummary,
      isVendor: event.data.isVendor,
      isCustomer: event.data.isCustomer,
      isProspect: event.data.isProspect,
      soCreditLimit: event.data.soCreditLimit,
      soCreditUsed: event.data.soCreditUsed,
      acqusitionCost: event.data.acqusitionCost,
      potentialLifeTimeValue: event.data.potentialLifeTimeValue,
      actualLifeTimeValue: event.data.actualLifeTimeValue,
      shareOfCustomer: event.data.shareOfCustomer,
      isEmployee: event.data.isEmployee,
      isSalesRep: event.data.isSalesRep,
      isOneTime: event.data.isOneTime,
      isTaxExempt: event.data.isTaxExempt,
      isDiscountPrinted: event.data.isDiscountPrinted,
      sendEMail: event.data.sendEMail,
      totalOpenBalance: event.data.totalOpenBalance,
      isPOTaxExempt: event.data.isPOTaxExempt,
      isManufacturer: event.data.isManufacturer,
      is1099Vendor: event.data.is1099Vendor,
    }
  })

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

const breadCrumb = computed(() => ([
  { link: '#', text: 'Partners'},
  { link: '/partners/partners', text: 'Business Partners', active: true}
]))

/*const replaceActiveTabUrl = (url) => {
  const tabIndex = tabs.value.findIndex(i => i.link === '/partners/partners')
  tabs.value[tabIndex].link = url
  localStorage.setItem('tabs', JSON.stringify(tabs.value))
  router.push(url)
}*/

const create = () => {
  router.push('/partners/partners/create')
  //replaceActiveTabUrl('/partners/partners/create')
}

const add = () => {
  router.push('/partners/partners/add')
  //replaceActiveTabUrl('/partners/partners/add')
}

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

    const res = await $fetch('/api/partners/partners/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 filter = ref({
  phone: ''
})
const filteredData = ref([])
const showFilteredPicker = ref(false)
const filterByPhone = async () => {
  showFilteredPicker.value = false

  if(filter.value.phone !== '') {
    const res = await $fetch('/api/partners/phonesearch/'+filter.value.phone, {
      headers: useRequestHeaders(['cookie'])
    })
    if(res?.records) {
      if(Number(res.records.length) === 1) {
        router.push('/partners/partners/'+res.records[0].C_BPartner_ID.id+'/edit')
      } else {
        filteredData.value = res.records
        showFilteredPicker.value = true
      }
    }
  }
}
const editByFilteredPhone = (item) => {
  router.push('/partners/partners/'+item.C_BPartner_ID.id+'/edit')
  showFilteredPicker.value = false
}
</script>

<template>
  <Head>
    <Title>Business Partners</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    <div class="banner datatable-wrapper">
      <HeaderAction :isDeletable="isDeletable" @create="create" @destroy="destroy">
        <button type="button" @click="add" class="button is-success">
          <span class="tf-icon ti ti-pencil-plus ti-sm me-1 color-inherit"></span>
          Quick Add
        </button>
      </HeaderAction>
      <div class="d-flex justify-between mt-4 mb-5 gap-1.5rem">
        <div class="flexGrow-1">
          <div class="picker" :class="{active: showFilteredPicker}">
            <div class="pickerBackdrop" @click.self="showFilteredPicker = false"></div>
            <div class="pickerWrap">
              <input v-model="filter.phone" type="search" class="input w-100pct" placeholder="Search Partner by entering Phone Number here" @keyup.enter="filterByPhone" />
              <div class="pickerContent w-100pct" style="margin-top: 5px;">
                <div class="pickerBody" style="box-shadow: 0 3px 8px rgba(0,0,0,.24);">
                  <div v-if="filteredData.length >= 1" class="list flush">
                    <div v-for="(filteredItem, index) in filteredData" :key="index" @click.self="editByFilteredPhone(filteredItem)" class="listItem p-1 cursor-pointer">{{ filteredItem.C_BPartner_ID.identifier }}</div>
                  </div>
                  <div v-else>
                    No business partner found for {{ filter.phone }}
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div>
          <button type="button" class="button" @click="filterByPhone">
            <span class="tf-icon ti ti-trash ti-xs color-inherit mr-2"></span>
            Search
          </button>
        </div>
      </div>
      <div>
        <div>
          <AlertBox :alert="alert" />
          <div class="mb-3">
            <AgGrid :entries="rowData" :columns="colDefs" @cellClick="cellClick" @cellChange="cellChange" />
          </div>
        </div>
      </div>
    </div>

    <Teleport to="body">
      <PartnersPartnerQuickView />
    </Teleport>
  </NuxtLayout>
</template>