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

const router = useRouter()
const route = useRoute()
const url = useRequestURL()

const user = useCookie('logship_user')
const userId = useCookie('logship_user_id')

const tabs2 = useTabs()
const activeSave = useActiveSave()
const windowFrom = useWindowFrom()
const windowParam = useWindowParam()

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

const window = (from) => {
  let newParam = {}
  if(windowParam.value?.[from] && url.pathname.includes('windows/partners-partners-edit/')) {
    newParam = windowParam.value?.[from] || {}
  }
  return newParam
}

const lastRecord = ref({})
const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  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: '',
  description: '',
  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 summaries = ref(['c_order', 'c_invoice', 'm_inout'])
const summary = ref({
  c_order: {
    id: [130, 131, 132, 133, 134, 135],
    isSOTrx: true,
    records: []
  },
  c_invoice: {
    id: [116],
    isSOTrx: true,
    records: []
  },
  m_inout: {
    id: [120],
    isSOTrx: true,
    records: []
  }
})
const setSummaries = async () => {
  const resp = await $fetch('/api/partners/partners/'+route.params.id+'/summary', {
    headers: useRequestHeaders(['cookie'])
  })
  if(resp) {
    for(let smr of summaries.value) {
      if(resp[smr]) {
        if(smr === 'c_order') {
          summary.value[smr].records = resp[smr].filter(i => summary.value[smr].isSOTrx == i.IsSOTrx)
        } else {
          summary.value[smr].records = resp[smr].filter(i => summary.value[smr].isSOTrx == i.IsSOTrx)
        }
      }
    }
  }
}

const retrieve = async () => {
  const res = await $fetch('/api/partners/partners/'+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 || '',
      name2: res?.Name2 || '',
      value: res?.Value || '',
      salesVolume: res?.SalesVolume || 0,
      numberEmployees: res?.NumberEmployees || 0,
      isSummary: res?.IsSummary ?? false,
      isVendor: res?.IsVendor ?? false,
      isCustomer: res?.IsCustomer ?? false,
      isProspect: res?.IsProspect ?? false,
      soCreditLimit: res?.SoCreditLimit || 0,
      soCreditUsed: res?.SoCreditUsed || 0,
      acqusitionCost: res?.AcqusitionCost || 0,
      potentialLifeTimeValue: res?.PotentialLifeTimeValue || 0,
      actualLifeTimeValue: res?.ActualLifeTimeValue || 0,
      shareOfCustomer: res?.ShareOfCustomer || 0,
      isEmployee: res?.IsEmployee ?? false,
      isSalesRep: res?.IsSalesRep ?? false,
      isOneTime: res?.IsOneTime ?? false,
      isTaxExempt: res?.IsTaxExempt ?? false,
      isDiscountPrinted: res?.IsDiscountPrinted ?? false,
      sendEMail: res?.SendEMail ?? false,
      EMail: res?.EMail || '',
      totalOpenBalance: res?.TotalOpenBalance || 0,
      isPOTaxExempt: res?.IsPOTaxExempt ?? false,
      isManufacturer: res?.IsManufacturer ?? false,
      is1099Vendor: res?.Is1099Vendor ?? false,
      firstSale: res?.FirstSale || date.now('date'),
      poReference: res?.POReference || '',
      referenceNo: res?.ReferenceNo || '',
      rating: res?.Rating || '',
      taxID: res?.TaxID || '',
      URL: res?.URL || '',
      NAICS: res?.NAICS || '',
      DUNS: res?.DUNS || '',
      documentCopies: res?.DocumentCopies || 0,
      soDescription: res?.SODescription || '',
      description: res?.Description || '',
      flatDiscount: res?.FlatDiscount || 0,
      shelfLifeMinPct: res?.ShelfLifeMinPct || 0,
      dunningGrace: res?.DunningGrace || date.now('date'),
      isFulfillmentCustomer: res?.isFulfillmentCustomer ?? false,
      isAccountLogShip: res?.isAccountLogShip ?? false,
      isAccountingWarehouseVolume: res?.isAccountingWarehouseVolume ?? false,
      logshipmonthlyfee: res?.logshipmonthlyfee || 0,
      volumeqm3price: res?.volumeqm3price || 0,
      accoutingwarehouserentstarts: res?.accoutingwarehouserentstarts || '',
      fulfillmentOrderBaseprice: res?.fulfillment_order_baseprice ?? 0,
      fulfillmentOrderPickprice: res?.fulfillment_order_pickprice ?? 0,
      fulfillmentOrderQtyPickfree: res?.fulfillment_order_qty_pickfree ?? 0,
      fulfillmentOrderBaseprice2: res?.fulfillment_order_baseprice_2 ?? 0,
      fulfillmentOrderBaseprice3: res?.fulfillment_order_baseprice_3 ?? 0,
      fulfillmentOrderReturnBaseprice: res?.fulfillment_order_return_baseprice ?? 0,
      fulfillmentOrderReturnPickprice: res?.fulfillment_order_return_pickprice ?? 0,
      deliveryRule: res?.DeliveryRule?.identifier || '',
      deliveryRuleId: res?.DeliveryRule?.id || '',
      deliveryViaRule: res?.DeliveryViaRule?.identifier || '',
      deliveryViaRuleId: res?.DeliveryViaRule?.id || '',
      invoiceSchedule: res?.C_InvoiceSchedule_ID?.identifier || '',
      invoiceScheduleId: res?.C_InvoiceSchedule_ID?.id || '',
      greeting: res?.C_Greeting_ID?.identifier || '',
      greetingId: res?.C_Greeting_ID?.id || '',
      printFormat: res?.Invoice_PrintFormat_ID?.identifier || '',
      printFormatId: res?.Invoice_PrintFormat_ID?.id || '',
      salesRep: res?.SalesRep_ID?.identifier || '',
      salesRepId: res?.SalesRep_ID?.id || '',
      invoiceRule: res?.InvoiceRule?.identifier || '',
      invoiceRuleId: res?.InvoiceRule?.id || '',
      paymentRule: res?.PaymentRule?.identifier || '',
      paymentRuleId: res?.PaymentRule?.id || '',
      paymentRulePO: res?.PaymentRulePO?.identifier || '',
      paymentRulePOId: res?.PaymentRulePO?.id || '',
      soCreditStatus: res?.SOCreditStatus?.identifier || '',
      soCreditStatusId: res?.SOCreditStatus?.id || '',
      partnerGroup: res?.C_BP_Group_ID?.identifier || '',
      partnerGroupId: res?.C_BP_Group_ID?.id || '',
      priceList: res?.M_PriceList_ID?.identifier || '',
      priceListId: res?.M_PriceList_ID?.id || '',
      poPriceList: res?.PO_PriceList_ID?.identifier || '',
      poPriceListId: res?.PO_PriceList_ID?.id || '',
      discountSchema: res?.M_DiscountSchema_ID?.identifier || '',
      discountSchemaId: res?.M_DiscountSchema_ID?.id || '',
      poDiscountSchema: res?.PO_DiscountSchema_ID?.identifier || '',
      poDiscountSchemaId: res?.PO_DiscountSchema_ID?.id || '',
      paymentTerm: res?.C_PaymentTerm_ID?.identifier || '',
      paymentTermId: res?.C_PaymentTerm_ID?.id || '',
      poPaymentTerm: res?.PO_PaymentTerm_ID?.identifier || '',
      poPaymentTermId: res?.PO_PaymentTerm_ID?.id || '',
      languageId: res?.AD_Language?.id || res?.AD_Language?.identifier || 'en_US',
      dunning: res?.C_Dunning_ID?.identifier || '',
      dunningId: res?.C_Dunning_ID?.id || '',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }
    lastRecord.value = res
    setNoEdit()
    activeSave.value = false
  }

  await setSummaries()
}
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.name2 == (lastRecord.value?.Name2 || '') &&
    form.value.value == (lastRecord.value?.Value || '') &&
    form.value.salesVolume == (lastRecord.value?.SalesVolume || 0) &&
    form.value.numberEmployees == (lastRecord.value?.NumberEmployees || 0) &&
    form.value.isSummary == (lastRecord.value?.IsSummary ?? false) &&
    form.value.isVendor == (lastRecord.value?.IsVendor ?? false) &&
    form.value.isCustomer == (lastRecord.value?.IsCustomer ?? false) &&
    form.value.isProspect == (lastRecord.value?.IsProspect ?? false) &&
    form.value.soCreditLimit == (lastRecord.value?.SoCreditLimit || 0) &&
    form.value.soCreditUsed == (lastRecord.value?.SoCreditUsed || 0) &&
    form.value.acqusitionCost == (lastRecord.value?.AcqusitionCost || 0) &&
    form.value.potentialLifeTimeValue == (lastRecord.value?.PotentialLifeTimeValue || 0) &&
    form.value.actualLifeTimeValue == (lastRecord.value?.ActualLifeTimeValue || 0) &&
    form.value.shareOfCustomer == (lastRecord.value?.ShareOfCustomer || 0) &&
    form.value.isEmployee == (lastRecord.value?.IsEmployee ?? false) &&
    form.value.isSalesRep == (lastRecord.value?.IsSalesRep ?? false) &&
    form.value.isOneTime == (lastRecord.value?.IsOneTime ?? false) &&
    form.value.isTaxExempt == (lastRecord.value?.IsTaxExempt ?? false) &&
    form.value.isDiscountPrinted == (lastRecord.value?.IsDiscountPrinted ?? false) &&
    form.value.sendEMail == (lastRecord.value?.SendEMail ?? false) &&
    form.value.EMail == (lastRecord.value?.EMail || '') &&
    form.value.totalOpenBalance == (lastRecord.value?.TotalOpenBalance || 0) &&
    form.value.isPOTaxExempt == (lastRecord.value?.IsPOTaxExempt ?? false) &&
    form.value.isManufacturer == (lastRecord.value?.IsManufacturer ?? false) &&
    form.value.is1099Vendor == (lastRecord.value?.Is1099Vendor ?? false) &&
    form.value.firstSale == (lastRecord.value?.FirstSale || date.now('date')) &&
    form.value.poReference == (lastRecord.value?.POReference || '') &&
    form.value.referenceNo == (lastRecord.value?.ReferenceNo || '') &&
    form.value.rating == (lastRecord.value?.Rating || '') &&
    form.value.taxID == (lastRecord.value?.TaxID || '') &&
    form.value.URL == (lastRecord.value?.URL || '') &&
    form.value.NAICS == (lastRecord.value?.NAICS || '') &&
    form.value.DUNS == (lastRecord.value?.DUNS || '') &&
    form.value.documentCopies == (lastRecord.value?.DocumentCopies || 0) &&
    form.value.soDescription == (lastRecord.value?.SODescription || '') &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.flatDiscount == (lastRecord.value?.FlatDiscount || 0) &&
    form.value.shelfLifeMinPct == (lastRecord.value?.ShelfLifeMinPct || 0) &&
    form.value.dunningGrace == (lastRecord.value?.DunningGrace || date.now('date')) &&
    form.value.isFulfillmentCustomer == (lastRecord.value?.isFulfillmentCustomer ?? false) &&
    form.value.isAccountLogShip == (lastRecord.value?.isAccountLogShip ?? false) &&
    form.value.isAccountingWarehouseVolume == (lastRecord.value?.isAccountingWarehouseVolume ?? false) &&
    form.value.logshipmonthlyfee == (lastRecord.value?.logshipmonthlyfee || 0) &&
    form.value.volumeqm3price == (lastRecord.value?.volumeqm3price || 0) &&
    form.value.accoutingwarehouserentstarts == (lastRecord.value?.accoutingwarehouserentstarts || '') &&
    form.value.fulfillmentOrderBaseprice == (lastRecord.value?.fulfillment_order_baseprice ?? 0) &&
    form.value.fulfillmentOrderPickprice == (lastRecord.value?.fulfillment_order_pickprice ?? 0) &&
    form.value.fulfillmentOrderQtyPickfree == (lastRecord.value?.fulfillment_order_qty_pickfree ?? 0) &&
    form.value.fulfillmentOrderBaseprice2 == (lastRecord.value?.fulfillment_order_baseprice_2 ?? 0) &&
    form.value.fulfillmentOrderBaseprice3 == (lastRecord.value?.fulfillment_order_baseprice_3 ?? 0) &&
    form.value.fulfillmentOrderReturnBaseprice == (lastRecord.value?.fulfillment_order_return_baseprice ?? 0) &&
    form.value.fulfillmentOrderReturnPickprice == (lastRecord.value?.fulfillment_order_return_pickprice ?? 0) &&
    form.value.deliveryRuleId == (lastRecord.value?.DeliveryRule?.id || '') &&
    form.value.deliveryViaRuleId == (lastRecord.value?.DeliveryViaRule?.id || '') &&
    form.value.invoiceScheduleId == (lastRecord.value?.C_InvoiceSchedule_ID?.id || '') &&
    form.value.greetingId == (lastRecord.value?.C_Greeting_ID?.id || '') &&
    form.value.printFormatId == (lastRecord.value?.Invoice_PrintFormat_ID?.id || '') &&
    form.value.salesRepId == (lastRecord.value?.SalesRep_ID?.id || '') &&
    form.value.invoiceRuleId == (lastRecord.value?.InvoiceRule?.id || '') &&
    form.value.paymentRuleId == (lastRecord.value?.PaymentRule?.id || '') &&
    form.value.paymentRulePOId == (lastRecord.value?.PaymentRulePO?.id || '') &&
    form.value.soCreditStatusId == (lastRecord.value?.SOCreditStatus?.id || '') &&
    form.value.partnerGroupId == (lastRecord.value?.C_BP_Group_ID?.id || '') &&
    form.value.priceListId == (lastRecord.value?.M_PriceList_ID?.id || '') &&
    form.value.poPriceListId == (lastRecord.value?.PO_PriceList_ID?.id || '') &&
    form.value.discountSchemaId == (lastRecord.value?.M_DiscountSchema_ID?.id || '') &&
    form.value.poDiscountSchemaId == (lastRecord.value?.PO_DiscountSchema_ID?.id || '') &&
    form.value.paymentTermId == (lastRecord.value?.C_PaymentTerm_ID?.id || '') &&
    form.value.poPaymentTermId == (lastRecord.value?.PO_PaymentTerm_ID?.id || '') &&
    form.value.languageId == (lastRecord.value?.AD_Language?.id || lastRecord.value?.AD_Language?.identifier || 'en_US') &&
    form.value.dunningId == (lastRecord.value?.C_Dunning_ID?.id || '')
  ) ? true : false
}

const duplicate = () => {
  router.push(`/partners/partners/${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 {
    let newUrl = '/partners/partners'
    if(windowParam.value?.[windowFrom.value]?.path) {
      newUrl = windowParam.value[windowFrom.value].path
    }
    router.push(newUrl)
    if(windowParam.value?.[windowFrom.value]?.path) {
      windowFrom.value = ''
      windowParam.value = {}
    }
  }
}

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/partners/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      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,
      description: form.value.description,
      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) {
    windowFrom.value = ''
    windowParam.value = {}

    if(saveType === 'preview') {
      router.push('/partners/partners/'+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
    toast({
      message: res.message || 'Save error',
      type: 'is-danger',
      duration: 2000
    })
  }
  form.value.alert.processing = false
  activeSave.value = false
}

const showAttachment = ref(false)

const breadCrumb = computed(() => ([
  { link: '#', text: 'Partners'},
  { link: '/partners/partners', text: 'Business Partners'},
  { link: '#', text: 'Edit 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
})

const goTo = (toPath, pathName) => {
  if(activeSave.value) {
    toast({
      message: 'Save button is active, please submit the data before leaving!',
      type: 'is-warning',
      duration: 2000
    })
  } else {
    windowFrom.value = 'partners'
    if(windowParam.value) {
      windowParam.value['partners'] = {
        path: url.pathname,
        data: form.value
      }
    } else {
      windowParam.value = {
        partners: {
          path: url.pathname,
          data: form.value
        }
      }
    }
    
    tabs2.value.map(item => {
      item.active = false
      return item
    })
    if(tabs2.value.filter(i => i.link === toPath).length >= 1) {
      const tabIndex = tabs2.value.findIndex(i => i.link === toPath)
      tabs2.value[tabIndex].active = true
      router.push(toPath)
    } else {
      tabs2.value.push({link: toPath, text: pathName, active: true})
      localStorage.setItem('tabs', JSON.stringify(tabs2.value))
      router.push(toPath)
    }
    //location.href = toPath
  }
}
</script>

<template>
  <Head>
    <Title>Edit Business Partner</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.EMail === '' || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''"><i class="ti ti-device-floppy"></i></button>
        <template v-if="form.id !== ''">
          <button type="button" @click="submit" class="button" :class="(form.name === '' || form.EMail === '' || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''"> <i class="ti ti-device-floppy"></i>+<i class="ti ti-logout"></i></button>
          <button type="button" @click="showAttachment = true" class="button" :class="(form.name === '' || form.EMail === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''"><i class="ti ti-paperclip"></i></button>
          <button type="button" @click="duplicate" class="button" :class="(!noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''"><i class="ti ti-copy"></i></button>
          <button type="button" @click="goTo('/windows/sales-orders-create', 'Create Order')" class="button" :class="(form.name === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">+ Sales Order</button>
<!--          <button type="button" @click="goTo('/windows/sales-invoices-create', 'Create Invoice')" class="button" :class="(form.name === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Sales Invoice</button>-->
<!--          <button type="button" @click="goTo('/windows/sales-shipments-create', 'Create Shipment')" class="button" :class="(form.name === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Shipment</button>-->
          <button type="button" @click="goTo('/windows/requests-requests-create', 'Create Request')" class="button" :class="(form.name === '' || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">+ Request</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="d-flex justify-between mb-3">
        <InsideWindowTab v-model="tab" :tabs="tabs" />
      </div>
      <div class="editwrapper">
        <div class="columns is-desktop">
          <div class="column is-three-quarters">
            <PartnersPartnerForm v-model="form" v-model:tab="tab" @save="save"/>
          </div>
          <div class="column is-one-quarter">
            <h3 class="fw-bold mb-2">Sales Orders</h3>
            <p v-for="(sur, inx) in summary.c_order.records" :key="inx">
              <span @click="goTo('/windows/sales-orders-edit/'+sur.id, 'Edit Order')" class="cursor-pointer">{{ sur.DocumentNo }} - {{ sur.DateAcct }} - {{ sur.GrandTotal }}</span>
            </p>
            <h3 class="fw-bold mt-2 mb-2">Sales Invoices</h3>
            <p v-for="(sur, inx) in summary.c_invoice.records" :key="inx">
              <span @click="goTo('/windows/sales-invoices-edit/'+sur.id, 'Edit Invoice')" class="cursor-pointer">{{ sur.DocumentNo }} - {{ sur.DateAcct }} - {{ sur.GrandTotal }}</span>
            </p>
            <h3 class="fw-bold mt-2 mb-2">Shipments</h3>
            <p v-for="(sur, inx) in summary.m_inout.records" :key="inx">
              <span @click="goTo('/windows/sales-shipments-edit/'+sur.id, 'Edit Shipment')" class="cursor-pointer">{{ sur.DocumentNo }} - {{ sur.DateAcct }} - {{ sur.IsCommissioned ? 'Yes' : 'No' }}</span>
            </p>
          </div>
        </div>
      </div>
      <div>
        <PartnersPartnerDetailRecord action="edit" :info="form" :zoom="window('sales-orders-zoom')?.data || {}" />
      </div>
      <div>
        <AttachmentModal v-model="showAttachment" target="C_BPartner" :info="form" />
      </div>
    </div>
  </NuxtLayout>
</template>