<script>
import AssetAction from '../../../components/assets/AssetAction.vue'

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

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    name: item.Name,
    value: item.Value,
    description: item.Description,
    help: item.Help,
    isActive: item.IsActive,
    lot: item.Lot,
    isDisposed: item.IsDisposed,
    isInPosession: item.IsInPosession,
    useLifeYears: item.UseLifeYears,
    assetDisposalDate: item.AssetDisposalDate,
    isOwned: item.IsOwned,
    locationComment: item.LocationComment,
    isDepreciated: item.IsDepreciated,
    lifeUseUnits: item.LifeUseUnits,
    processing: item.Processing,
    guaranteeDate: item.GuaranteeDate,
    useLifeMonths: item.UseLifeMonths,
    assetServiceDate: item.AssetServiceDate,
    useUnits: item.UseUnits,
    serNo: item.SerNo,
    isFullyDepreciated: item.IsFullyDepreciated,
    qty: item.Qty,
    lastMaintenanceDate: item.LastMaintenanceDate,
    nextMaintenenceDate: item.NextMaintenenceDate,
    lastMaintenanceUnit: item.LastMaintenanceUnit,
    nextMaintenenceUnit: item.NextMaintenenceUnit,
    lastMaintenanceNote: item.LastMaintenanceNote,
    assetCreateDate: item.A_Asset_CreateDate,
    assetRevalDate: item.A_Asset_RevalDate,
    qtyCurrent: item.A_QTY_Current,
    qtyOriginal: item.A_QTY_Original,
    processed: item.Processed,
    assetActivationDate: item.AssetActivationDate,
    inventoryNo: item.InventoryNo,
    assetType: item.A_AssetType,
    manufacturedYear: item.ManufacturedYear || 1900,
    user: item.AD_User_ID?.identifier || '',
    userId: item.AD_User_ID?.id || '',
    product: item.M_Product_ID?.identifier || '',
    productId: item.M_Product_ID?.id || '',
    location: item.C_Location_ID?.identifier || '',
    locationId: item.C_Location_ID?.id || '',
    assetGroup: item.A_Asset_Group_ID?.identifier || '',
    assetGroupId: item.A_Asset_Group_ID?.id || '',
    partner: item.C_BPartner_ID?.identifier || '',
    partnerId: item.C_BPartner_ID?.id || '',
    partnerLocation: item.C_BPartner_Location_ID?.identifier || '',
    partnerLocationId: item.C_BPartner_Location_ID?.id || '',
    attributeSetInstance: item.M_AttributeSetInstance_ID?.identifier || '',
    attributeSetInstanceId: item.M_AttributeSetInstance_ID?.id || '',
    project: item.C_Project_ID?.identifier || '',
    projectId: item.C_Project_ID?.id || '',
    parentAsset: item.A_Parent_Asset_ID?.identifier || '',
    parentAssetId: item.A_Parent_Asset_ID?.id || '',
    assetStatus: item.A_Asset_Status?.identifier || '',
    assetStatusId: item.A_Asset_Status?.id || '',
    assetAction: item.A_Asset_Action?.identifier || '',
    assetActionId: item.A_Asset_Action?.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: 'description',
    headerName: 'Description'
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  { 
    field: 'lot'
  },
  { 
    field: 'assetType',
    headerName: 'Asset Type'
  },
  { 
    headerName: 'Action',
    minWidth: 80,
    type: 'nonEditableColumn',
    cellRenderer: 'AssetAction'
  }
]);

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/assets/assets/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: event.data.id,
      name: event.data.name,
      description: event.data.description,
      isActive: event.data.isActive,
      value: event.data.value,
      help: event.data.help,
      lot: event.data.lot,
      isDisposed: event.data.isDisposed,
      isInPosession: event.data.isInPosession,
      useLifeYears: event.data.useLifeYears,
      assetDisposalDate: event.data.assetDisposalDate,
      isOwned: event.data.isOwned,
      locationComment: event.data.locationComment,
      isDepreciated: event.data.isDepreciated,
      lifeUseUnits: event.data.lifeUseUnits,
      processing: event.data.processing,
      guaranteeDate: event.data.guaranteeDate,
      useLifeMonths: event.data.useLifeMonths,
      assetServiceDate: event.data.assetServiceDate,
      useUnits: event.data.useUnits,
      serNo: event.data.serNo,
      //isFullyDepreciated: event.data.isFullyDepreciated,
      qty: event.data.qty,
      lastMaintenanceDate: event.data.lastMaintenanceDate,
      nextMaintenenceDate: event.data.nextMaintenenceDate,
      lastMaintenanceUnit: event.data.lastMaintenanceUnit,
      nextMaintenenceUnit: event.data.nextMaintenenceUnit,
      lastMaintenanceNote: event.data.lastMaintenanceNote,
      assetCreateDate: event.data.assetCreateDate,
      assetRevalDate: event.data.assetRevalDate,
      qtyCurrent: event.data.qtyCurrent,
      qtyOriginal: event.data.qtyOriginal,
      processed: event.data.processed,
      assetActivationDate: event.data.assetActivationDate,
      inventoryNo: event.data.inventoryNo,
      assetType: event.data.assetType,
      manufacturedYear: event.data.manufacturedYear || 1900,
    }
  })

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

const breadCrumb = computed(() => ([
  { link: '#', text: 'Assets', active: true}
]))

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

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

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

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    <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>
  </NuxtLayout>
</template>