<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/settings/currencies', {
  headers: useRequestHeaders(['cookie'])
})

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    isActive: item.IsActive,
    iso_code: item.ISO_Code,
    stdPrecision: item.StdPrecision,
    description: item.Description,
    costingPrecision: item.CostingPrecision,
    emuRate: item.EMURate,
    curSymbol: item.CurSymbol,
    isEuro: item.IsEuro,
    isEMUMember: item.IsEMUMember,
    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: 'iso_code',
    headerName: 'ISO Code' 
  },
  { 
    field: 'curSymbol', 
    headerName: 'Symbol'
  },
  { 
    field: 'description',
    headerName: 'Description'
  },
  { 
    field: 'stdPrecision',
    headerName: 'Standard Precision'
  },
  { 
    field: 'costingPrecision',
    headerName: 'Costing Precision'
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  { 
    field: 'isEuro',
    headerName: 'Euro'
  },
  { 
    field: 'isEMUMember',
    headerName: 'EMU Member'
  },
  { 
    field: 'emuRate',
    headerName: 'EMU Rate'
  },
  /*{ 
    field: "price",
    width: 130,
    valueFormatter: (params) => {
      return '£' + params.value.toLocaleString();
    }
  },*/
]);

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/settings/currencies/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: event.data.id,
      isActive: event.data.isActive,
      iso_code: event.data.iso_code,
      stdPrecision: event.data.stdPrecision,
      description: event.data.description,
      costingPrecision: event.data.costingPrecision,
      emuRate: event.data.emuRate,
      curSymbol: event.data.curSymbol,
      isEuro: event.data.isEuro,
      isEMUMember: event.data.isEMUMember
    }
  })

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

const breadCrumb = computed(() => ([
  { link: '#', text: 'Settings'},
  { link: '/settings/currencies', text: 'Currencies', active: true}
]))

const create = () => {
  router.push('/settings/currencies/create')
}

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

    const res = await $fetch('/api/settings/currencies/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>Currencies</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    <div>
      <div class="banner datatable-wrapper">
        <div class="d-flex justify-between mb-3">
          <h4></h4>
          <div class="d-flex gap-0.75rem">
            <button type="button" @click="destroy" class="button danger-light" :class="!isDeletable ? 'pointerEvents-none opacity-0.6 filter-grayscale(1)' : ''">
              <span class="tf-icon ti ti-trash ti-xs me-1 color-inherit"></span> Delete Selected
            </button>
            <button type="button" @click="create" class="button primary-light">
              <span class="tf-icon ti ti-plus ti-xs me-1 color-inherit"></span> Add Currency
            </button>
          </div>
        </div>
        <div>
          <div>
            <div v-if="Number(alert.status) >= 400" class="mb-3">
              <div class="alert alert-danger">
                <div class="alertContent">
                  <h3 class="alertTitle">{{ alert.status }}</h3>
                  <p class="alertText">{{ alert.message }}</p>
                </div>
              </div>
            </div>
            <div class="mb-3">
              <AgGrid :entries="rowData" :columns="colDefs" @cellClick="cellClick" @cellChange="cellChange" />
            </div>
          </div>
        </div>
      </div>

    </div>
  </NuxtLayout>
</template>