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

const router = useRouter()
const route = useRoute()
const activeSave = useActiveSave()

const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')
const user = useCookie('logship_user')
const userId = useCookie('logship_user_id')

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

const form = ref({
  id: '',
  client: '',
  clientId: '',
  organization: organization.value?.Name || '',
  organizationId: organizationId.value || '',
  name: '',
  name2: '',
  value: '',
  salesVolume: 0,
  numberEmployees: 0,
  isActive: true,
  isSummary: false,
  isVendor: false,
  isCustomer: false,
  isProspect: false,
  soCreditLimit: 0,
  soCreditUsed: 0,
  acqusitionCost: 0,
  potentialLifeTimeValue: 0,
  actualLifeTimeValue: 0,
  shareOfCustomer: 0,
  isEmployee: false,
  isSalesRep: false,
  isOneTime: false,
  isTaxExempt: false,
  isDiscountPrinted: false,
  sendEMail: false,
  EMail: '',
  totalOpenBalance: 0,
  isPOTaxExempt: false,
  isManufacturer: false,
  is1099Vendor: false,
  firstSale: date.now('date'),
  poReference: '',
  referenceNo: '',
  rating: '',
  taxID: '',
  URL: '',
  NAICS: '',
  DUNS: '',
  documentCopies: 0,
  soDescription: '',
  flatDiscount: 0,
  shelfLifeMinPct: 0,
  dunningGrace: date.now('date'),
  isFulfillmentCustomer: false,
  isAccountLogShip: false,
  isAccountingWarehouseVolume: false,
  logshipmonthlyfee: 0,
  volumeqm3price: 0,
  accoutingwarehouserentstarts: '',
  fulfillmentOrderBaseprice: 0,
  fulfillmentOrderPickprice: 0,
  fulfillmentOrderQtyPickfree: 0,
  fulfillmentOrderBaseprice2: 0,
  fulfillmentOrderBaseprice3: 0,
  fulfillmentOrderReturnBaseprice: 0,
  fulfillmentOrderReturnPickprice: 0,
  deliveryRule: '',
  deliveryRuleId: '',
  deliveryViaRule: '',
  deliveryViaRuleId: '',
  invoiceSchedule: '',
  invoiceScheduleId: '',
  greeting: '',
  greetingId: '',
  printFormat: '',
  printFormatId: '',
  salesRep: user.value?.Name ?? '',
  salesRepId: user.value?.id ?? userId.value ?? '',
  invoiceRule: '',
  invoiceRuleId: '',
  deliveryRule: '',
  deliveryRuleId: '',
  paymentRule: '',
  paymentRuleId: '',
  paymentRulePO: '',
  paymentRulePOId: '',
  soCreditStatus: '',
  soCreditStatusId: '',
  partnerGroup: '',
  partnerGroupId: '',
  priceList: '',
  priceListId: '',
  poPriceList: '',
  poPriceListId: '',
  discountSchema: '',
  discountSchemaId: '',
  poDiscountSchema: '',
  poDiscountSchemaId: '',
  paymentTerm: '',
  paymentTermId: '',
  poPaymentTerm: '',
  poPaymentTermId: '',
  languageId: 'en_US',
  dunning: '',
  dunningId: '',
  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('/partners/partners')
  }
}

const save = async (record) => {
  form.value = record

  if(form.value.name !== '') {
    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/partners/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      name: form.value.name,
      name2: form.value.name2,
      isActive: form.value.isActive,
      value: form.value.value,
      salesVolume: form.value.salesVolume,
      numberEmployees: form.value.numberEmployees,
      isSummary: form.value.isSummary,
      isVendor: form.value.isVendor,
      isCustomer: form.value.isCustomer,
      isProspect: form.value.isProspect,
      soCreditLimit: form.value.soCreditLimit,
      soCreditUsed: form.value.soCreditUsed,
      acqusitionCost: form.value.acqusitionCost,
      potentialLifeTimeValue: form.value.potentialLifeTimeValue,
      actualLifeTimeValue: form.value.actualLifeTimeValue,
      shareOfCustomer: form.value.shareOfCustomer,
      isEmployee: form.value.isEmployee,
      isSalesRep: form.value.isSalesRep,
      isOneTime: form.value.isOneTime,
      isTaxExempt: form.value.isTaxExempt,
      isDiscountPrinted: form.value.isDiscountPrinted,
      sendEMail: form.value.sendEMail,
      EMail: form.value.EMail,
      totalOpenBalance: form.value.totalOpenBalance,
      isPOTaxExempt: form.value.isPOTaxExempt,
      isManufacturer: form.value.isManufacturer,
      is1099Vendor: form.value.is1099Vendor,
      firstSale: form.value.firstSale,
      poReference: form.value.poReference,
      referenceNo: form.value.referenceNo,
      rating: form.value.rating,
      taxID: form.value.taxID,
      URL: form.value.URL,
      NAICS: form.value.NAICS,
      DUNS: form.value.DUNS,
      documentCopies: form.value.documentCopies,
      soDescription: form.value.soDescription,
      flatDiscount: form.value.flatDiscount,
      shelfLifeMinPct: form.value.shelfLifeMinPct,
      dunningGrace: form.value.dunningGrace,
      deliveryViaRuleId: form.value.deliveryViaRuleId,
      invoiceScheduleId: form.value.invoiceScheduleId,
      greetingId: form.value.greetingId,
      printFormatId: form.value.printFormatId,
      salesRepId: form.value.salesRepId,
      invoiceRuleId: form.value.invoiceRuleId,
      deliveryRuleId: form.value.deliveryRuleId,
      paymentRuleId: form.value.paymentRuleId,
      paymentRulePOId: form.value.paymentRulePOId,
      soCreditStatusId: form.value.soCreditStatusId,
      partnerGroupId: form.value.partnerGroupId,
      priceListId: form.value.priceListId,
      poPriceListId: form.value.poPriceListId,
      discountSchemaId: form.value.discountSchemaId,
      poDiscountSchemaId: form.value.poDiscountSchemaId,
      paymentTermId: form.value.paymentTermId,
      poPaymentTermId: form.value.poPaymentTermId,
      languageId: form.value.languageId,
      dunning: form.value.dunning,
      dunningId: form.value.dunningId,
      isFulfillmentCustomer: form.value.isFulfillmentCustomer,
      isAccountLogShip: form.value.isAccountLogShip,
      isAccountingWarehouseVolume: form.value.isAccountingWarehouseVolume,
      logshipmonthlyfee: form.value.logshipmonthlyfee,
      volumeqm3price: form.value.volumeqm3price,
      accoutingwarehouserentstarts: form.value.accoutingwarehouserentstarts,
      fulfillmentOrderBaseprice: form.value.fulfillmentOrderBaseprice,
      fulfillmentOrderPickprice: form.value.fulfillmentOrderPickprice,
      fulfillmentOrderQtyPickfree: form.value.fulfillmentOrderQtyPickfree,
      fulfillmentOrderBaseprice2: form.value.fulfillmentOrderBaseprice2,
      fulfillmentOrderBaseprice3: form.value.fulfillmentOrderBaseprice3,
      fulfillmentOrderReturnBaseprice: form.value.fulfillmentOrderReturnBaseprice,
      fulfillmentOrderReturnPickprice: form.value.fulfillmentOrderReturnPickprice,
    }
  })

  if(Number(res.status) === 200) {
    if(saveType === 'preview') {
      router.push('/partners/partners/' + res.id + '/view')
    } else if(saveType === 'onlysave') {
      // Do nothing
      router.push('/partners/partners/'+res.id+'/edit')
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
    } else if(saveType === 'changes') {
      let newTabVal = 'partner'
      if(!route.query?.tab || route.query?.tab === 'partner') {
        newTabVal = 'customer'
      } else if(route.query?.tab === 'customer') {
        newTabVal = 'vendor'
      } else if(route.query?.tab === 'vendor') {
        newTabVal = 'preferences'
      } else if(route.query?.tab === 'preferences') {
        newTabVal = 'sales'
      }
      router.push('/partners/partners/'+res.id+'/edit?tab='+newTabVal)
    } else {
      back()
    }
  } else {
    //form.value.alert.status = res.status
    //form.value.alert.message = res.message
    toast({
      message: res.message || 'Save error',
      type: 'is-danger',
      duration: 2000
    })
  }
  form.value.alert.processing = false
  activeSave.value = false
}

const breadCrumbs = computed(() => ([
  { link: '#', text: 'Partners'},
  { link: '/partners/partners', text: 'Business Partners'},
  { link: '#', text: 'Add Business Partner', active: true}
]))

const tab = ref(route.query?.tab || 'partner')
const tabs = computed(() => {
  let newTabs = [
    { value: 'partner', text: 'Business Partner'},
    { value: 'preferences', text: 'Document Preferences'},
    { value: 'sales', text: 'Sales Info'}
  ]
  if(form.value.isCustomer) {
    newTabs.splice(1, 0, { value: 'customer', text: 'Customer Info'})
  } else {
    let customerIndex = newTabs.findIndex(item => item.value === 'customer')
    if(Number(customerIndex) === 1) {
      newTabs.splice(1, 1)
    }
  }
  if(form.value.isVendor) {
    if(newTabs.length <= 3) {
      newTabs.splice(1, 0, { value: 'vendor', text: 'Vendor Info'})
    } else {
      newTabs.splice(2, 0, { value: 'vendor', text: 'Vendor Info'})
    }
  } else {
    let vendorIndex = newTabs.findIndex(item => item.value === 'vendor')
    if(Number(vendorIndex) === 1) {
      newTabs.splice(1, 1)
    } else if(Number(vendorIndex) === 2) {
      newTabs.splice(2, 1)
    }
  }
  if(form.value.isFulfillmentCustomer) {
    if(newTabs.length <= 3) {
      newTabs.splice(1, 0, { value: 'fulfillment-customer', text: 'Fulfillment Customer'})
    } else if(newTabs.length == 4) {
      newTabs.splice(2, 0, { value: 'fulfillment-customer', text: 'Fulfillment Customer'})
    } else {
      newTabs.splice(3, 0, { value: 'fulfillment-customer', text: 'Fulfillment Customer'})
    }
  } else {
    let fulfillmentCustomerIndex = newTabs.findIndex(item => item.value === 'fulfillment-customer')
    if(Number(fulfillmentCustomerIndex) === 1) {
      newTabs.splice(1, 1)
    } else if(Number(fulfillmentCustomerIndex) === 2) {
      newTabs.splice(2, 1)
    } else if(Number(fulfillmentCustomerIndex) === 3) {
      newTabs.splice(3, 1)
    }
  }

  return newTabs
})
</script>

<template>
  <Head>
    <Title>Add Business Partner</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumbs" />
    
    <div class="bannercontrol">
      <div class="d-flex gap-10px">
        <button type="button" @click="submit('onlysave')" class="button" :class="(form.name === '' || form.EMail === '' || 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 class="d-flex justify-between mb-3">
        <InsideWindowTab v-model="tab" :tabs="tabs" />
      </div>
      <div>
        <PartnersPartnerForm v-model="form" v-model:tab="tab" @save="save"/>
      </div>
      <div class="opacity-0.6 pointerEvents-none">
        <PartnersPartnerDetailRecord action="create" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>