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

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

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

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

//const clients = useCookie('logship_clients')
const client = useCookie('logship_client')
const clientId = useCookie('logship_client_id')
//const organizations = useCookie('logship_organizations')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')
//const warehouses = useCookie('logship_warehouses')
const warehouse = useCookie('logship_warehouse')
const warehouseId = useCookie('logship_warehouse_id')
const user = useCookie('logship_user')

const { data: preferences } = await useFetch('/api/preferences/143', {
  headers: useRequestHeaders(['cookie'])
})

const preference = (attribute) => {
  let newPreference = preferences.value[attribute] || {}
  if(newPreference?.id == '-1') {
    newPreference.id = ''
  }
  return newPreference
}

const orderParam = ref({})
const window = (from) => {
  if(windowParam.value?.[from] && url.pathname.endsWith('windows/sales-orders-create')) {
    orderParam.value = windowParam.value?.[from] || {}
  }
  
  return orderParam.value
}

const form = ref({
  id: '',
  uid: '',
  client: client.value?.Name || '',
  clientId: clientId.value || '',
  organization: organization.value?.Name || '',
  organizationId: organizationId.value || '',
  warehouse: warehouse.value?.Name || '',
  warehouseId: warehouseId.value || '',
  isActive: true,
  documentNo: '',
  poReference: '',
  description: '',
  isApproved: false,
  isCreditApproved: false,
  isDelivered: false,
  isInvoiced: false,
  isPrinted: false,
  isTransferred: false,
  dateOrdered: date.now('date'),
  datePromised: date.now('date'),
  dateAcct: date.now('date'),
  freightAmt: 0,
  totalLines: 0,
  grandTotal: 0,
  chargeAmt: 0,
  processed: false,
  isSOTrx: true,
  isDiscountPrinted: false,
  isTaxIncluded: false,
  isSelected: false,
  sendEMail: false,
  isSelfService: false,
  isDropShip: preference('IsDropShip') ?? false,
  processedOn: 0,
  isPayScheduleValid: false,
  isPriviledgedRate: false,
  docStatus: 'Draft',
  docStatusId: 'DR',
  docType: 0,
  docTypeId: 0,
  docTypeTarget: preference('C_DocTypeTarget_ID')?.identifier || '',
  docTypeTargetId: preference('C_DocTypeTarget_ID')?.id || '',
  salesRep: user.value?.Name || preference('SalesRep_ID')?.identifier || '',
  salesRepId: user.value?.id || preference('SalesRep_ID')?.id || '',
  paymentTerm: preference('C_PaymentTerm_ID')?.identifier || '',
  paymentTermId: preference('C_PaymentTerm_ID')?.id || '',
  currency: 'EUR',
  currencyId: '102',
  invoiceRule: '',
  invoiceRuleId: '',
  deliveryViaRule: preference('DeliveryViaRule')?.identifier || '',
  deliveryViaRuleId: preference('DeliveryViaRule')?.id || '',
  deliveryRule: '',
  deliveryRuleId: '',
  priorityRule: preference('PriorityRule')?.identifier || '',
  priorityRuleId: preference('PriorityRule')?.id || '',
  freightCostRule: '',
  freightCostRuleId: '',
  paymentRule: '',
  paymentRuleId: preference('PaymentRule')?.id || '',
  priceList: preference('M_PriceList_ID')?.identifier || '',
  priceListId: preference('M_PriceList_ID')?.id || '',
  partner: window('partners')?.data?.name || preference('C_BPartner_ID')?.identifier || '',
  partnerId: window('partners')?.data?.id || preference('C_BPartner_ID')?.id || '',
  partnerLocation: preference('C_BPartner_Location_ID')?.identifier || '',
  partnerLocationId: preference('C_BPartner_Location_ID')?.id || '',
  partnerLocationStreet: '',
  partnerLocationZip: '',
  partnerLocationCity: '',
  partnerLocationCountry: '',
  cashLine: '',
  cashLineId: '',
  billPartner: window('partners')?.data?.name || preference('Bill_BPartner_ID')?.identifier || '',
  billPartnerId: window('partners')?.data?.id || preference('Bill_BPartner_ID')?.id || '',
  billPartnerLocation: preference('Bill_Location_ID')?.identifier || '',
  billPartnerLocationId: preference('Bill_Location_ID')?.id || '',
  project: preference('C_Project_ID')?.identifier || '',
  projectId: preference('C_Project_ID')?.id || '',
  campaign: preference('C_Campaign_ID')?.identifier || '',
  campaignId: preference('C_Campaign_ID')?.id || '',
  shipper: preference('M_Shipper_ID')?.identifier || '',
  shipperId: preference('M_Shipper_ID')?.id || '',
  freightCategory: preference('M_FreightCategory_ID')?.identifier || '',
  freightCategoryId:  preference('M_FreightCategory_ID')?.id || '',
  user: '',
  userId:  '',
  billUser: '',
  billUserId:  '',
  promotionCode: '',
  dropShipPartner: window('partners')?.data?.name || preference('DropShip_BPartner_ID')?.identifier || '',
  dropShipPartnerId: window('partners')?.data?.id || preference('DropShip_BPartner_ID')?.id || '',
  dropShipPartnerLocation: preference('DropShip_Location_ID')?.identifier || '',
  dropShipPartnerLocationId: preference('DropShip_Location_ID')?.id || '',
  dropShipUser: '',
  dropShipUserId:  '',
  conversionType: preference('C_ConversionType_ID')?.identifier || '',
  conversionTypeId: preference('C_ConversionType_ID')?.id || '',
  orderSource: preference('C_OrderSource_ID')?.identifier || '',
  orderSourceId: preference('C_OrderSource_ID')?.id || '',
  shopware6OrderId: '',
  shopifyOrderId: '',
  xentralOrderId: '',
  amazonOrderId: '',
  plentyOneOrderId: '',
  externalOrderId: '',
  inouts: [],
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const openTab = (toPath, pathName, oldPath = null) => {
  let comparePath = toPath
  if(oldPath) {
    comparePath = oldPath
  }
  tabs.value.map(item => {
    item.active = false
    return item
  })
  if(tabs.value.filter(i => i.link === comparePath).length >= 1) {
    const tabIndex = tabs.value.findIndex(i => i.link === comparePath)
    tabs.value[tabIndex].active = true
    if(oldPath) {
      tabs.value[tabIndex].link = toPath
      tabs.value[tabIndex].text = pathName
    }
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  } else {
    tabs.value.push({link: toPath, text: pathName, active: true})
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  }
  //location.href = toPath
}

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(window('partners')?.path || '/sales/orders')
    let newUrl = '/sales/orders'
    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
  
  if(form.value.paymentRuleId !== '' && form.value.paymentTermId !== '' && form.value.dateOrdered !== '' && form.value.datePromised !== '' && form.value.partnerId !== '' && form.value.partnerLocationId !== '' && form.value.warehouseId !== '' && form.value.deliveryViaRuleId !== '' && form.value.deliveryRuleId !== '' && form.value.priorityRuleId !== '' && form.value.priceListId !== '' && form.value.currencyId !== '' && form.value.salesRepId !== '' && form.value.docStatusId !== 'CO' && (form.value.isDropShip === false || (form.value.isDropShip === true && (form.value.dropShipPartnerId !== '' && form.value.dropShipPartnerLocationId !== '')))) {
    activeSave.value = true
  } else {
    activeSave.value = false
  }
}

const submit = async (saveType = '') => {
  form.value.alert.processing = true
  activeSave.value = true

  const res = await $fetch('/api/orders/store', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      organizationId: form.value.organizationId,
      isActive: form.value.isActive,
      documentNo: form.value.documentNo,
      poReference: form.value.poReference,
      description: form.value.description,
      isApproved: form.value.isApproved,
      isCreditApproved: form.value.isCreditApproved,
      isDelivered: form.value.isDelivered,
      isInvoiced: form.value.isInvoiced,
      isPrinted: form.value.isPrinted,
      isTransferred: form.value.isTransferred,
      dateOrdered: form.value.dateOrdered,
      datePromised: form.value.datePromised,
      dateAcct: form.value.dateAcct,
      freightAmt: form.value.freightAmt,
      totalLines: form.value.totalLines,
      grandTotal: form.value.grandTotal,
      chargeAmt: form.value.chargeAmt,
      processed: form.value.processed,
      isSOTrx: true,
      isDiscountPrinted: form.value.isDiscountPrinted,
      isTaxIncluded: form.value.isTaxIncluded,
      isSelected: form.value.isSelected,
      sendEMail: form.value.sendEMail,
      isSelfService: form.value.isSelfService,
      isDropShip: form.value.isDropShip,
      processedOn: form.value.processedOn,
      isPayScheduleValid: form.value.isPayScheduleValid,
      isPriviledgedRate: form.value.isPriviledgedRate,
      docStatusId: form.value.docStatusId,
      docTypeId: form.value.docTypeId,
      docTypeTargetId: form.value.docTypeTargetId,
      salesRepId: form.value.salesRepId,
      paymentTermId: form.value.paymentTermId,
      currencyId: form.value.currencyId,
      invoiceRuleId: form.value.invoiceRuleId,
      deliveryViaRuleId: form.value.deliveryViaRuleId,
      deliveryRuleId: form.value.deliveryRuleId,
      priorityRuleId: form.value.priorityRuleId,
      freightCostRuleId: form.value.freightCostRuleId,
      paymentRuleId: form.value.paymentRuleId,
      warehouseId: form.value.warehouseId,
      priceListId: form.value.priceListId,
      partnerId: form.value.partnerId,
      partnerLocationId: form.value.partnerLocationId,
      cashLineId: form.value.cashLineId,
      billPartnerId: form.value.billPartnerId,
      billPartnerLocationId: form.value.billPartnerLocationId,
      projectId: form.value.projectId,
      campaignId: form.value.campaignId,
      shipperId: form.value.shipperId,
      freightCategoryId: form.value.freightCategoryId,
      userId: form.value.userId,
      billUserId: form.value.billUserId,
      dropShipPartnerId: form.value.dropShipPartnerId,
      dropShipPartnerLocationId: form.value.dropShipPartnerLocationId,
      dropShipUserId:  form.value.dropShipUserId,
      conversionTypeId:  form.value.conversionTypeId,
      orderSourceId:  form.value.orderSourceId,
      promotionCode: form.value.promotionCode,
      shopware6OrderId: form.value.shopware6OrderId,
      shopifyOrderId: form.value.shopifyOrderId,
      xentralOrderId: form.value.xentralOrderId,
      externalOrderId: form.value.externalOrderId,
      amazonOrderId: form.value.amazonOrderId,
      plentyOneOrderId: form.value.plentyOneOrderId,
    }
  })

  if(Number(res.status) === 200) {
    windowFrom.value = ''
    windowParam.value = {}
    form.value.alert.processing = false
    activeSave.value = false
    
    if(saveType === 'preview') {
      //router.push('/sales/orders/'+res.id+'/view')
      openTab('/view/sales-order-'+res.id, 'Sales Order: View Details')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      //router.push('/sales/orders/'+res.id+'/edit')
      openTab('/edit/sales-order-'+res.id, 'Sales Order: '+res.DocumentNo)
      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: '#', text: 'Sales'},
  { link: '/sales/orders', text: 'Orders'},
  { link: '#', text: 'Add Order', active: true}
]))

const tab = ref(route.query?.tab || 'order')
const tabs2 = computed(() => ([
  { value: 'order', text: 'Order'},
  { value: 'delivery', text: 'Delivery'},
  { value: 'invoicing', text: 'Invoicing'},
  { value: 'reference', text: 'Reference'},
  { value: 'integration', text: 'Integration'},
  { value: 'status', text: 'Status'}
]))

const openOtherTab = () => {
  if(tab.value === 'order') {
    tab.value = 'delivery'
  } else if(tab.value === 'delivery') {
    tab.value = 'invoicing'
  } else if(tab.value === 'invoicing') {
    tab.value = 'reference'
  } else if(tab.value === 'reference') {
    tab.value = 'integration'
  } else if(tab.value === 'integration') {
    tab.value = 'status'
  }
}
</script>

<template>
  <Head>
    <Title>Add Order</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.paymentRuleId === '' || form.paymentTermId === '' || form.dateOrdered === '' || form.datePromised === '' || form.partnerId === '' || form.partnerLocationId === '' || form.warehouseId === '' || form.deliveryViaRuleId === '' || form.deliveryRuleId === '' || form.priorityRuleId === '' || form.priceListId === '' || form.currencyId === '' || form.salesRepId === '' || form.docStatusId === 'CO' || (form.isDropShip && (form.dropShipPartnerId === '' || form.dropShipPartnerLocationId === '')) || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</button>
        <button v-if="tab !== 'status'" type="button" @click="openOtherTab" class="button">Next</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="tabs2" />
      </div>
      <div>
        <SalesOrderForm v-model="form" v-model:tab="tab" @save="save" />
      </div>
      <div class="opacity-0.6 pointerEvents-none">
        <SalesOrderDetailRecord action="create" :info="form" tab="order_line" />
      </div>
    </div>
  </NuxtLayout>
</template>