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

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

const form = ref({
  id: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  name: '',
  description: '',
  isActive: true,
  movementDate: date.now('date'),
  processed: false,
  processedOn: 0,
  documentNo: '',
  productionQty: 0,
  datePromised: date.now('date'),
  isComplete: false,
  isUseProductionPlan: false,
  product: '',
  productId: '',
  isCreated: 'No',
  isCreatedId: 'N',
  project: '',
  projectId: '',
  campaign: '',
  campaignId: '',
  locator: '',
  locatorId: '',
  docStatus: 'Draft',
  docStatusId: 'DR',
  docType: '',
  docTypeId: '',
  processing: false,
  alert: {
    status: '',
    message: ''
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/manufacturings/productions/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: route.params.id,
      client: res?.AD_Client_ID?.identifier || '',
      clientId: res?.AD_Client_ID?.id || '',
      organization: res?.AD_Org_ID?.identifier || '',
      organizationId: res?.AD_Org_ID?.id || '',
      name: res?.Name || '',
      description: res?.Description || '',
      isActive: res?.IsActive ?? true,
      movementDate: res?.MovementDate || date.now('date'),
      processed: res?.Processed ?? false,
      processedOn: res?.ProcessedOn || 0,
      documentNo: res?.DocumentNo || '',
      productionQty: res?.ProductionQty || 0,
      datePromised: res?.DatePromised || date.now('date'),
      isComplete: res?.IsComplete || false,
      isUseProductionPlan: res?.IsUseProductionPlan || false,
      product: res?.M_Product_ID?.identifier || '',
      productId: res?.M_Product_ID?.id || '',
      isCreated: res?.IsCreated?.identifier || 'No',
      isCreatedId: res?.IsCreated?.id || 'N',
      project: res?.C_Project_ID?.identifier || '',
      projectId: res?.C_Project_ID?.id || '',
      campaign: res?.C_Campaign_ID?.identifier || '',
      campaignId: res?.C_Campaign_ID?.id || '',
      locator: res?.M_Locator_ID?.identifier || '',
      locatorId: res?.M_Locator_ID?.id || '',
      docStatus: res?.DocStatus?.identifier || 'Draft',
      docStatusId: res?.DocStatus?.id || 'DR',
      docType: res?.C_DocType_ID?.identifier || '',
      docTypeId: res?.C_DocType_ID?.id || '',
      processing: false,
      alert: {
        status: '',
        message: ''
      }
    }
  }
}
onMounted(retrieve)

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

const save = async (record, id = '', saveType = '') => {
  const res = await $fetch('/api/manufacturings/productions/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: record.id,
      organizationId: record.organizationId,
      name: record.name,
      description: record.description,
      isActive: record.isActive,
      movementDate: record.movementDate,
      processed: record.processed,
      processedOn: record.processedOn,
      documentNo: record.documentNo,
      productionQty: record.productionQty,
      datePromised: record.datePromised,
      isComplete: record.isComplete,
      isUseProductionPlan: record.isUseProductionPlan,
      productId: record.productId,
      isCreatedId: record.isCreatedId,
      projectId: record.projectId,
      campaignId: record.campaignId,
      locatorId: record.locatorId,
      docStatusId: record.docStatusId,
      docTypeId: record.docTypeId,
    }
  })

  if(Number(res.status) === 200) {
    if(saveType === 'preview') {
      router.push('/manufacturings/productions/'+res.id+'/view')
    } else if(saveType === 'changes') {
      form.value.processing = false
      location.reload()
    } 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/productions', text: 'Productions'},
  { link: '#', text: 'Edit Production', active: true}
]))
</script>

<template>
  <Head>
    <Title>Edit Production</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>
          <ManufacturingsProductionForm v-model="form" @save="save"/>
        </div>
      </div>

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