<script setup>
import { date } from 'alga-js'
import { toast } from 'bulma-toast'

const router = useRouter()
const route = useRoute()
const activeSave = useActiveSave()

definePageMeta({
  middleware: ['auth', 'org']
})

const client = useCookie('logship_client')
const clientId = useCookie('logship_client_id')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')
const warehouse = useCookie('logship_warehouse')
const warehouseId = useCookie('logship_warehouse_id')

const form = ref({
  id: '',
  uid: '',
  client: client.value?.Name || '',
  clientId: clientId.value || '',
  organization: organization.value?.Name || '',
  organizationId: organizationId.value || '',
  warehouse: warehouse.value?.Name || '',
  warehouseId: warehouseId.value || '',
  documentNo: '',
  movementDate: date.now('date'),
  approvalAmt: 0,
  description: '',
  isActive: true,
  isApproved: false,
  docType: '',
  docTypeId: '',
  project: '',
  projectId: '',
  campaign: '',
  campaignId: '',
  docStatus: 'Draft',
  docStatusId: 'DR',
  processed: false,
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const back = () => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    router.push('/materials/stock-takes')
  }
}

const save = async (record) => {
  form.value = record

  if(form.value.warehouseId !== '' && form.value.movementDate !== '' && form.value.docTypeId !== '') {
    activeSave.value = true
  } else {
    activeSave.value = false
  }
}

const submit = async (saveType = '') => {
  form.value.alert.processing = true
  activeSave.value = true

  const res = await $fetch('/api/materials/stock-takes/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      documentNo: form.value.documentNo,
      movementDate: form.value.movementDate,
      approvalAmt: form.value.approvalAmt,
      description: form.value.description,
      isActive: form.value.isActive,
      isApproved: form.value.isApproved,
      warehouseId: form.value.warehouseId,
      docTypeId: form.value.docTypeId,
      projectId: form.value.projectId,
      campaignId: form.value.campaignId,
      docStatusId: form.value.docStatusId,
      processed: form.value.processed,
      processing: form.value.processing,
    }
  })

  if(Number(res.status) === 200) {
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      router.push('/materials/stock-takes/' + res.id + '/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      router.push('/materials/stock-takes/'+res.id+'/edit')
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
    } else {
      back()
    }
  } else {
    //form.value.alert.status = res.status
    //form.value.alert.message = res.message
    form.value.alert.processing = false
    activeSave.value = false
    toast({
      message: res.message || 'Save error',
      type: 'is-danger',
      duration: 2000
    })
    //window.scrollTo(0, 0)
  }
}

const breadCrumb = computed(() => ([
  { link: '#', text: 'Materials'},
  { link: '/materials/stock-takes', text: 'Stock Takes'},
  { link: '#', text: 'Add Stock Take', active: true}
]))

const tab = ref(route.query?.tab || 'inventory')
const tabs = computed(() => ([
  { value: 'inventory', text: 'Physical Inventory'},
  { value: 'reference', text: 'Reference'},
  { value: 'status', text: 'Status'}
]))

const openOtherTab = () => {
  if(tab.value === 'inventory') {
    tab.value = 'reference'
  } else if(tab.value === 'reference') {
    tab.value = 'status'
  }
}
</script>

<template>
  <Head>
    <Title>Add Stock Take</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />

    <div class="bannercontrol">
      <div class="d-flex gap-10px">
        <button type="button" @click="submit('onlysave')" class="button" :class="(form.warehouseId === '' || form.movementDate === '' || form.docTypeId === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</button>
        <button v-if="tab !== 'status'" type="button" @click="openOtherTab" class="button">Next</button>
      </div>
      <div>
        <div class="d-flex gap-10px">
          <button v-if="activeSave" type="button" @click="activeSave = false; back();" class="button">
            <span class="tf-icon ti ti-square-x ti-xs me-1 color-inherit"></span> Abort
          </button>
          <button type="button" @click="back" class="button">
            <span class="tf-icon ti ti-chevron-left ti-xs me-1 color-inherit"></span> Back
          </button>
        </div>
      </div>
    </div>

    <div class="banner">
      <div class="d-flex justify-between mb-3">
        <InsideWindowTab v-model="tab" :tabs="tabs" />
      </div>
      <div>
        <MaterialsStockTakeForm v-model="form" v-model:tab="tab" @save="save"/>
      </div>
      <div class="opacity-0.6 pointerEvents-none">
        <MaterialsStockTakeDetailRecord action="create" :info="form" tab="count_line" />
      </div>
    </div>
  </NuxtLayout>
</template>