<script>
import PartnerGroupAction from '../../../components/partners/PartnerGroupAction.vue'

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

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    name: item.Name,
    value: item.Value,
    isActive: item.IsActive,
    isDefault: item.IsDefault,
    isConfidentialInfo: item.IsConfidentialInfo,
    creditWatchPercent: item.CreditWatchPercent,
    priceMatchTolerance: item.PriceMatchTolerance,
    printColor: item.AD_PrintColor_ID?.identifier || '',
    printColorId: item.AD_PrintColor_ID?.id || '',
    priorityBase: item.PriorityBase?.identifier || '',
    priorityBaseId: item.PriorityBase?.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 || '',
    dunning: item.C_Dunning_ID?.identifier || '',
    dunningId: item.C_Dunning_ID?.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: 50,
    checkboxSelection: checkboxSelection,
    headerCheckboxSelection: headerCheckboxSelection
  },
  { 
    field: 'id',
    //hide: true,
    sort: 'desc'
  },
  { 
    field: 'organization',
    type: 'nonEditableColumn' 
  },
  { field: 'name' },
  { 
    field: 'value', 
    headerName: 'Search Key'
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  /*{ 
    field: "price",
    width: 130,
    valueFormatter: (params) => {
      return '£' + params.value.toLocaleString();
    }
  },*/
  { 
    field: 'isDefault',
    headerName: 'Default'
  },
  { 
    field: 'isConfidentialInfo',
    headerName: 'Confidential Info'
  },
  { 
    field: 'creditWatchPercent',
    headerName: 'Credit Watch Percent'
  },
  { 
    field: 'PriceMatchTolerance',
    headerName: 'Price Match Tolerance'
  },
  /*{ 
    field: 'printColor',
    headerName: 'Print Color',
    type: 'nonEditableColumn' 
  },
  { 
    field: 'priorityBase',
    headerName: 'Priority Base',
    type: 'nonEditableColumn' 
  },
  { 
    field: 'priceList',
    headerName: 'Price List',
    type: 'nonEditableColumn' 
  },
  { 
    field: 'poPriceList',
    headerName: 'PO Price List',
    type: 'nonEditableColumn' 
  },
  { 
    field: 'discountSchema',
    headerName: 'Discount Schema',
    type: 'nonEditableColumn' 
  },
  { 
    field: 'poDiscountSchema',
    headerName: 'PO Discount Schema',
    type: 'nonEditableColumn' 
  },
  { 
    field: 'dunning',
    headerName: 'Dunning',
    type: 'nonEditableColumn' 
  },*/
  { 
    headerName: 'Action',
    minWidth: 80,
    type: 'nonEditableColumn',
    cellRenderer: PartnerGroupAction
  }
]);

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/partner-groups/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: event.data.id,
      name: event.data.name,
      isActive: event.data.isActive,
      value: event.data.value,
      isDefault: event.data.isDefault,
      isConfidentialInfo: event.data.isConfidentialInfo,
      creditWatchPercent: event.data.creditWatchPercent,
      priceMatchTolerance: event.data.priceMatchTolerance
    }
  })

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

const breadCrumb = computed(() => ([
  { link: '/partners', text: 'Partners'},
  { link: '/partners/partner-groups', text: 'Partner Groups', active: true}
]))

const create = () => {
  router.push('/partners/partner-groups/create')
}

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

    const res = await $fetch('/api/partners/partner-groups/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()
  }
}
</script>

<template>
  <Head>
    <Title>Partner Groups</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">
              <AgGrid :entries="rowData" :columns="colDefs" @cellClick="cellClick" @cellChange="cellChange" />
            </div>
          </div>
        </div>
      </div>

    </div>

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