<script setup>
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: '',
  documentNote: '',
  afterDelivery: false,
  netDays: 30,
  netDay: 0,
  graceDays: 0,
  isActive: true,
  isDefault: false,
  isValid: false,
  isDueFixed: false,
  fixMonthCutoff: 0,
  fixMonthDay: 0,
  fixMonthOffset: 0,
  isNextBusinessDay: false,
  discount: 2,
  discount2: 0,
  discountDays: 10,
  discountDays2: 0,
  paymentTermUsage: 'Both',
  paymentTermUsageId: 'B',
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/partners/payment-terms/'+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 || '',
      isActive: res?.IsActive ?? true,
      name: res?.Name || '',
      value: res?.Value || '',
      description: res?.Description || '',
      documentNote: res?.DocumentNote || '',
      afterDelivery: res?.AfterDelivery ?? false,
      netDays: res?.NetDays ?? 30,
      netDay: res?.NetDay ?? 0,
      graceDays: res?.GraceDays ?? 0,
      isDefault: res?.IsDefault ?? false,
      isValid: res?.IsValid ?? false,
      isDueFixed: res?.IsDueFixed ?? false,
      fixMonthCutoff: res?.FixMonthCutoff || 0,
      fixMonthDay: res?.FixMonthDay || 0,
      fixMonthOffset: res?.FixMonthOffset || 0,
      isNextBusinessDay: res?.IsNextBusinessDay ?? false,
      discount: res?.Discount || 2,
      discount2: res?.Discount2 || 0,
      discountDays: res?.DiscountDays || 10,
      discountDays2: res?.DiscountDays2 || 0,
      paymentTermUsage: res?.PaymentTermUsage?.identifier || '',
      paymentTermUsageId: res?.PaymentTermUsage?.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.isActive == (lastRecord.value?.IsActive ?? true) &&
    form.value.name == (lastRecord.value?.Name || '') &&
    form.value.value == (lastRecord.value?.Value || '') &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.documentNote == (lastRecord.value?.DocumentNote || '') &&
    form.value.afterDelivery == (lastRecord.value?.AfterDelivery ?? false) &&
    form.value.netDays == (lastRecord.value?.NetDays ?? 30) &&
    form.value.netDay == (lastRecord.value?.NetDay ?? 0) &&
    form.value.graceDays == (lastRecord.value?.GraceDays ?? 0) &&
    form.value.isDefault == (lastRecord.value?.IsDefault ?? false) &&
    form.value.isValid == (lastRecord.value?.IsValid ?? false) &&
    form.value.isDueFixed == (lastRecord.value?.IsDueFixed ?? false) &&
    form.value.fixMonthCutoff == (lastRecord.value?.FixMonthCutoff || 0) &&
    form.value.fixMonthDay == (lastRecord.value?.FixMonthDay || 0) &&
    form.value.fixMonthOffset == (lastRecord.value?.FixMonthOffset || 0) &&
    form.value.isNextBusinessDay == (lastRecord.value?.IsNextBusinessDay ?? false) &&
    form.value.discount == (lastRecord.value?.Discount || 2) &&
    form.value.discount2 == (lastRecord.value?.Discount2 || 0) &&
    form.value.discountDays == (lastRecord.value?.DiscountDays || 10) &&
    form.value.discountDays2 == (lastRecord.value?.DiscountDays2 || 0) &&
    form.value.paymentTermUsageId == (lastRecord.value?.PaymentTermUsage?.id || '')
  ) ? true : false
}

const duplicate = () => {
  router.push(`/partners/payment-terms/${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('/partners/payment-terms')
  }
}

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/partners/payment-terms/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,
      documentNote: form.value.documentNote,
      afterDelivery: form.value.afterDelivery,
      netDays: form.value.netDays,
      netDay: form.value.netDay,
      graceDays: form.value.graceDays,
      isActive: form.value.isActive,
      isDefault: form.value.isDefault,
      isValid: form.value.isValid,
      isDueFixed: form.value.isDueFixed,
      fixMonthCutoff: form.value.fixMonthCutoff,
      fixMonthDay: form.value.fixMonthDay,
      fixMonthOffset: form.value.fixMonthOffset,
      isNextBusinessDay: form.value.isNextBusinessDay,
      discount: form.value.discount,
      discount2: form.value.discount2,
      discountDays: form.value.discountDays,
      discountDays2: form.value.discountDays2,
      paymentTermUsageId: form.value.paymentTermUsageId,
    }
  })

  if(Number(res.status) === 200) {
    form.value.alert.processing = false
    activeSave.value = false
    if(saveType === 'preview') {
      router.push('/partners/payment-terms/'+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
    })
  }
}

const showAttachment = ref(false)

const breadCrumb = computed(() => ([
  { link: '/partners/partners', text: 'Partners'},
  { link: '/partners/payment-terms', text: 'Payment Terms'},
  { link: '#', text: 'Add Payment Term', active: true}
]))
</script>

<template>
  <Head>
    <Title>Add Payment Term</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.netDays === '' || form.graceDays === '' || form.discount === '' || form.discount2 === '' || form.discountDays === '' || form.discountDays2 === '' || form.paymentTermUsageId === '' || 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.netDays === '' || form.graceDays === '' || form.discount === '' || form.discount2 === '' || form.discountDays === '' || form.discountDays2 === '' || form.paymentTermUsageId === '' || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="showAttachment = true" class="button" :class="(form.name === '' || 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 class="editwrapper">
        <PartnersPaymentTermForm v-model="form" @save="save"/>
      </div>
      <div>
        <PartnersPaymentTermDetailRecord action="edit" :info="form" />
      </div>
      <div>
        <AttachmentModal v-model="showAttachment" target="C_PaymentTerm" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>