<script>
import ProductionAction from '../../../components/manufacturings/ProductionAction.vue'

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

const rowData = computed(() => data.value?.records?.map(item => {
  return {
    id: item.id,
    uid: item.uid,
    name: item.Name,
    description: item.Description,
    isActive: item.IsActive,
    movementDate: item.MovementDate,
    processed: item.Processed,
    processedOn: item.ProcessedOn,
    documentNo: item.DocumentNo,
    productionQty: item.ProductionQty,
    datePromised: item.DatePromised,
    isComplete: item.IsComplete,
    isUseProductionPlan: item.IsUseProductionPlan,
    product: item.M_Product_ID?.identifier || '',
    productId: item.M_Product_ID?.id || '',
    isCreated: item.IsCreated?.identifier || '',
    isCreatedId: item.IsCreated?.id || '',
    project: item.C_Project_ID?.identifier || '',
    projectId: item.C_Project_ID?.id || '',
    campaign: item.C_Campaign_ID?.identifier || '',
    campaignId: item.C_Campaign_ID?.id || '',
    locator: item.M_Locator_ID?.identifier || '',
    locatorId: item.M_Locator_ID?.id || '',
    docStatus: item.DocStatus?.identifier || '',
    docStatusId: item.DocStatus?.id || '',
    docType: item.C_DocType_ID?.identifier || '',
    docTypeId: item.C_DocType_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: 'documentNo',
    headerName: 'Document Number'
  },
  { 
    field: 'description',
    headerName: 'Description'
  },
  { 
    field: 'isActive',
    headerName: 'Active'
  },
  { 
    field: 'movementDate',
    headerName: 'Movement Date'
  },
  { 
    field: 'datePromised',
    headerName: 'Promised Date'
  },
  { 
    headerName: 'Action',
    minWidth: 80,
    type: 'nonEditableColumn',
    cellRenderer: 'ProductionAction'
  }
]);

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/manufacturings/productions/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: event.data.id,
      name: event.data.name,
      description: event.data.description,
      isActive: event.data.isActive,
      movementDate: event.data.movementDate,
      processed: event.data.processed,
      processedOn: event.data.processedOn,
      documentNo: event.data.documentNo,
      productionQty: event.data.productionQty,
      datePromised: event.data.datePromised,
      isComplete: event.data.isComplete,
      isUseProductionPlan: event.data.isUseProductionPlan,
    }
  })

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

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

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

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

    const res = await $fetch('/api/manufacturings/productions/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>Productions</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>