<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 lastRecord = ref({})
const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  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: route.params.id,
      uid: res?.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: res?.Value || '',
      description: res?.Description || '',
      isActive: res?.IsActive ?? true,
      note: res?.Note || '',
      isSummary: res?.IsSummary ?? false,
      isCommitment: res?.IsCommitment ?? false,
      committedAmt: res?.CommittedAmt || 0,
      dateContract: res?.DateContract || date.now('date'),
      dateFinish: res?.DateFinish || date.now('date'),
      processed: res?.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: res?.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,
      }
    }
    lastRecord.value = res
    setNoEdit()
    activeSave.value = false
  }
}
onMounted(retrieve)

const noEdit = ref(true)
const setNoEdit = () => {
  noEdit.value = (
    form.value.organizationId == (lastRecord.value?.AD_Org_ID?.id || '') &&
    form.value.name == (lastRecord.value?.Name || '') &&
    form.value.value == (lastRecord.value?.Value || '') &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.isActive == (lastRecord.value?.IsActive ?? true) &&
    form.value.note == (lastRecord.value?.Note || '') &&
    form.value.isSummary == (lastRecord.value?.IsSummary ?? false) &&
    form.value.isCommitment == (lastRecord.value?.IsCommitment ?? false) &&
    form.value.committedAmt == (lastRecord.value?.CommittedAmt || 0) &&
    form.value.dateContract == (lastRecord.value?.DateContract || date.now('date')) &&
    form.value.dateFinish == (lastRecord.value?.DateFinish || date.now('date')) &&
    form.value.processed == (lastRecord.value?.Processed ?? false) &&
    form.value.plannedAmt == (lastRecord.value?.PlannedAmt || 0) &&
    form.value.plannedQty == (lastRecord.value?.PlannedQty || 0) &&
    form.value.plannedMarginAmt == (lastRecord.value?.PlannedMarginAmt || 0) &&
    form.value.invoicedAmt == (lastRecord.value?.InvoicedAmt || 0) &&
    form.value.invoicedQty == (lastRecord.value?.InvoicedQty || 0) &&
    form.value.projectBalanceAmt == (lastRecord.value?.ProjectBalanceAmt || 0) &&
    form.value.committedQty == (lastRecord.value?.CommittedQty || 0) &&
    form.value.isCommitCeiling == (lastRecord.value?.IsCommitCeiling ?? false) &&
    form.value.poReference == (lastRecord.value?.POReference || '') &&
    form.value.currencyId == (lastRecord.value?.C_Currency_ID?.id || '') &&
    form.value.partnerId == (lastRecord.value?.C_BPartner_ID?.id || '') &&
    form.value.partnerLocationId == (lastRecord.value?.C_BPartner_Location_ID?.id || '') &&
    form.value.salesRepId == (lastRecord.value?.SalesRep_ID?.id || '') &&
    form.value.priceListVersionId == (lastRecord.value?.M_PriceList_Version_ID?.id || '') &&
    form.value.campaignId == (lastRecord.value?.C_Campaign_ID?.id || '') &&
    form.value.userId == (lastRecord.value?.AD_User_ID?.id || '') &&
    form.value.warehouseId == (lastRecord.value?.M_Warehouse_ID?.id || '') &&
    form.value.projectCategoryId == (lastRecord.value?.ProjectCategory?.id || '') &&
    form.value.projInvoiceRuleId == (lastRecord.value?.ProjInvoiceRule?.id || '') &&
    form.value.projectLineLevelId == (lastRecord.value?.ProjectLineLevel?.id || '') &&
    form.value.partnerSRId == (lastRecord.value?.C_BPartnerSR_ID?.id || '') &&
    form.value.paymentTermId == (lastRecord.value?.C_PaymentTerm_ID?.id || '')
  ) ? true : false
}

const duplicate = () => {
  router.push(`/projects/projects/${route.params.id}/duplicate`)
}

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
  setNoEdit()
  if(!noEdit.value) {
    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/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      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') {
      location.reload()
    } else if(saveType === 'onlysave') {
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
      retrieve()
    } 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 showAttachment = ref(false)

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 === '')) || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</button>
        <template v-if="form.id !== ''">
          <button type="button" @click="submit" class="button" :class="(form.name === '' || (!form.isSummary && (form.projectLineLevelId === '' || form.currencyId === '' || form.plannedAmt === '' || form.plannedMarginAmt === '' || form.committedAmt === '' || form.plannedQty === '' || form.projInvoiceRuleId === '' || form.committedQty === '')) || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="showAttachment = true" 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' : ''">Attachment</button>
          <button type="button" @click="duplicate" class="button" :class="(!noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Duplicate</button>
        </template>
      </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>
        <AttachmentModal v-model="showAttachment" target="c_project" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>