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

const router = useRouter()
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 form = ref({
  id: '',
  uid: '',
  client: client.value?.Name || '',
  clientId: clientId.value || '',
  organization: organization.value?.Name || '',
  organizationId: organizationId.value || '',
  name: '',
  value: '',
  description: '',
  isActive: true,
  note: '',
  isSummary: false,
  isCommitment: false,
  committedAmt: 0,
  dateContract: date.now('date'),
  dateFinish: date.now('date'),
  processed: false,
  plannedAmt: 0,
  plannedQty: 0,
  plannedMarginAmt: 0,
  invoicedAmt: 0,
  invoicedQty: 0,
  projectBalanceAmt: 0,
  committedQty: 0,
  isCommitCeiling: false,
  poReference: '',
  currency: 'USD',
  currencyId: 100,
  partner: '',
  partnerId: '',
  partnerLocation: '',
  partnerLocationId: '',
  salesRep: '',
  salesRepId: '',
  priceListVersion: '',
  priceListVersionId: '',
  campaign: '',
  campaignId: '',
  user: '',
  userId: '',
  warehouse: '',
  warehouseId: '',
  projectCategory: '',
  projectCategoryId: '',
  projInvoiceRule: '',
  projInvoiceRuleId: '',
  projectLineLevel: 'Project',
  projectLineLevelId: 'P',
  partnerSR: '',
  partnerSRId: '',
  paymentTerm: '',
  paymentTermId: '',
  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('/projects/projects')
  }
}

const save = async (record) => {
  form.value = record
  
  if(form.value.name !== '' && (form.value.isSummary === true || (form.value.isSummary === false && (form.value.projectLineLevelId !== '' && form.value.currencyId !== '' && form.value.plannedAmt !== '' && form.value.plannedMarginAmt !== '' && form.value.committedAmt !== '' && form.value.plannedQty !== '' && form.value.projInvoiceRuleId !== '' && form.value.committedQty !== '')))) {
    activeSave.value = true
  } else {
    activeSave.value = false
  }
}

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

  const res = await $fetch('/api/projects/projects/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      name: form.value.name,
      value: form.value.value,
      description: form.value.description,
      isActive: form.value.isActive,
      note: form.value.note,
      isSummary: form.value.isSummary,
      isCommitment: form.value.isCommitment,
      committedAmt: form.value.committedAmt,
      dateContract: form.value.dateContract,
      dateFinish: form.value.dateFinish,
      processed: form.value.processed,
      plannedAmt: form.value.plannedAmt,
      plannedQty: form.value.plannedQty,
      plannedMarginAmt: form.value.plannedMarginAmt,
      invoicedAmt: form.value.invoicedAmt,
      invoicedQty: form.value.invoicedQty,
      projectBalanceAmt: form.value.projectBalanceAmt,
      committedQty: form.value.committedQty,
      isCommitCeiling: form.value.isCommitCeiling,
      poReference: form.value.poReference,
      currencyId: form.value.currencyId,
      partnerId: form.value.partnerId,
      partnerLocationId: form.value.partnerLocationId,
      salesRepId: form.value.salesRepId,
      priceListVersionId: form.value.priceListVersionId,
      campaignId: form.value.campaignId,
      userId: form.value.userId,
      warehouseId: form.value.warehouseId,
      projectCategoryId: form.value.projectCategoryId,
      projInvoiceRuleId: form.value.projInvoiceRuleId,
      projectLineLevelId: form.value.projectLineLevelId,
      partnerSRId: form.value.partnerSRId,
      paymentTermId: form.value.paymentTermId,
    }
  })

  if(Number(res.status) === 200) {
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      router.push('/projects/projects/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      router.push('/projects/projects/'+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: '/projects/projects', text: 'Projects'},
  { link: '#', text: 'Add Project', active: true}
]))
</script>

<template>
  <Head>
    <Title>Add Project</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.name === '' || (!form.isSummary && (form.projectLineLevelId === '' || form.currencyId === '' || form.plannedAmt === '' || form.plannedMarginAmt === '' || form.committedAmt === '' || form.plannedQty === '' || form.projInvoiceRuleId === '' || form.committedQty === '')) || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</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>
        <ProjectsProjectForm v-model="form" @save="save" />
      </div>
    </div>
  </NuxtLayout>
</template>