<script setup>
import { date } from 'alga-js'
const router = useRouter()

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

const form = ref({
  id: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  name: '',
  value: '',
  description: '',
  help: '',
  isActive: true,
  revision: '',
  validFrom: date.now('date'),
  product: '',
  productId: '',
  bomType: 'Current Active',
  bomTypeId: 'A',
  bomUse: 'Master',
  bomUseId: 'A',
  uom: '',
  uomId: '',
  attributeSetInstance: '',
  attributeSetInstanceId: '',
  processing: false,
  alert: {
    status: '',
    message: ''
  }
})

const back = () => {
  router.push('/manufacturings/product-bom')
}

const save = async (record, id = '', saveType = '') => {
  const res = await $fetch('/api/manufacturings/product-bom/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: record.organizationId,
      name: record.name,
      value: record.value,
      description: record.description,
      help: record.help,
      isActive: record.isActive,
      revision: record.revision,
      validFrom: record.validFrom,
      productId: record.productId,
      bomTypeId: record.bomTypeId,
      bomUseId: record.bomUseId,
      uomId: record.uomId,
      attributeSetInstanceId: record.attributeSetInstanceId,
    }
  })

  if(Number(res.status) === 200) {
    if(saveType === 'preview') {
      router.push('/manufacturings/product-bom/'+res.id+'/view')
    } else if(saveType === 'changes') {
      router.push('/manufacturings/product-bom/'+res.id+'/edit')
    } else {
      back()
    }
  } else {
    form.value.alert.status = res.status
    form.value.alert.message = res.message
    form.value.processing = false
    window.scrollTo(0, 0)
  }
}

const breadCrumb = computed(() => ([
  { link: '/manufacturings/product-bom', text: 'Bill of Materials and Formula'},
  { link: '#', text: 'Add Bill of Material and Formula', active: true}
]))
</script>

<template>
  <Head>
    <Title>Add Bill of Material and Formula</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    <div>
      <div class="banner">
        <div class="d-flex justify-between mb-3">
          <h4></h4>
          <div class="d-flex gap-0.75rem">
            <button type="button" @click="back" class="button">
              <span class="tf-icon ti ti-chevron-left ti-xs me-1"></span> Back
            </button>
          </div>
        </div>
        <div>
          <ManufacturingsProductBOMForm v-model="form" @save="save"/>
        </div>
      </div>

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