<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 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 retrieve = async () => {
  const res = await $fetch('/api/projects/projects/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: '',
      uid: '',
      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 || '',
      value: '',
      description: res?.Description || '',
      isActive: true,
      note: res?.Note || '',
      isSummary: res?.IsSummary ?? false,
      isCommitment: false,
      committedAmt: res?.CommittedAmt || 0,
      dateContract: date.now('date'),
      dateFinish: date.now('date'),
      processed: false,
      plannedAmt: res?.PlannedAmt || 0,
      plannedQty: res?.PlannedQty || 0,
      plannedMarginAmt: res?.PlannedMarginAmt || 0,
      invoicedAmt: res?.InvoicedAmt || 0,
      invoicedQty: res?.InvoicedQty || 0,
      projectBalanceAmt: res?.ProjectBalanceAmt || 0,
      committedQty: res?.CommittedQty || 0,
      isCommitCeiling: false,
      poReference: res?.POReference || '',
      currency: res?.C_Currency_ID?.identifier || '',
      currencyId: res?.C_Currency_ID?.id || '',
      partner: res?.C_BPartner_ID?.identifier || '',
      partnerId: res?.C_BPartner_ID?.id || '',
      partnerLocation: res?.C_BPartner_Location_ID?.identifier || '',
      partnerLocationId: res?.C_BPartner_Location_ID?.id || '',
      salesRep: res?.SalesRep_ID?.identifier || '',
      salesRepId: res?.SalesRep_ID?.id || '',
      priceListVersion: res?.M_PriceList_Version_ID?.identifier || '',
      priceListVersionId: res?.M_PriceList_Version_ID?.id || '',
      campaign: res?.C_Campaign_ID?.identifier || '',
      campaignId: res?.C_Campaign_ID?.id || '',
      user: res?.AD_User_ID?.identifier || '',
      userId: res?.AD_User_ID?.id || '',
      warehouse: res?.M_Warehouse_ID?.identifier || '',
      warehouseId: res?.M_Warehouse_ID?.id || '',
      projectCategory: res?.ProjectCategory?.identifier || '',
      projectCategoryId: res?.ProjectCategory?.id || '',
      projInvoiceRule: res?.ProjInvoiceRule?.identifier || '',
      projInvoiceRuleId: res?.ProjInvoiceRule?.id || '',
      projectLineLevel: res?.ProjectLineLevel?.identifier || '',
      projectLineLevelId: res?.ProjectLineLevel?.id || '',
      partnerSR: res?.C_BPartnerSR_ID?.identifier || '',
      partnerSRId: res?.C_BPartnerSR_ID?.id || '',
      paymentTerm: res?.C_PaymentTerm_ID?.identifier || '',
      paymentTermId: res?.C_PaymentTerm_ID?.id || '',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false,
      }
    }
    
    setActiveSave()
  }
}
onMounted(retrieve)

const setActiveSave = () => {
  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 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
  
  setActiveSave()
}

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>