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

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

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

const client = useCookie('logship_client')
const clientId = useCookie('logship_client_id')
const organization = useCookie('logship_organization')
const organizationId = useCookie('logship_organization_id')
const warehouse = useCookie('logship_warehouse')
const warehouseId = useCookie('logship_warehouse_id')
const user = useCookie('logship_user')

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

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

const lines = ref([])
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: 1,
  grandTotal: 0,
  chargeAmt: 0,
  processed: false,
  isSOTrx: false,
  isDiscountPrinted: false,
  isTaxIncluded: false,
  isSelected: false,
  sendEMail: false,
  isSelfService: false,
  isDropShip: preference('IsDropShip')?.identifier ?? false,
  processedOn: 0,
  isPayScheduleValid: false,
  isPriviledgedRate: false,
  docStatus: '',
  docStatusId: 'DR',
  docType: '',
  docTypeId: 0,
  docTypeTarget: preference('C_DocTypeTarget_ID')?.identifier || '',
  docTypeTargetId: preference('C_DocTypeTarget_ID')?.id || '',
  salesRep: preference('SalesRep_ID')?.identifier || user.value?.Name || '',
  salesRepId: preference('SalesRep_ID')?.id || user.value?.id || '',
  paymentTerm: preference('C_PaymentTerm_ID')?.identifier || '',
  paymentTermId: preference('C_PaymentTerm_ID')?.id || '',
  currency: 'EUR',
  currencyId: '102',
  invoiceRule: '',
  invoiceRuleId: '',
  deliveryViaRule: preference('DeliveryViaRule')?.identifier || 'Delivery',
  deliveryViaRuleId: preference('DeliveryViaRule')?.id || 'D',
  deliveryRule: '',
  deliveryRuleId: '',
  priorityRule: preference('PriorityRule')?.identifier || 'Medium',
  priorityRuleId: preference('PriorityRule')?.id || '5',
  freightCostRule: '',
  freightCostRuleId: '',
  paymentRule: 'Cash',
  paymentRuleId: preference('PaymentRule')?.id || 'B',
  priceList: preference('M_PriceList_ID')?.identifier || '',
  priceListId: preference('M_PriceList_ID')?.id || '',
  partner: '',
  partnerId: '',
  partnerLocation: '',
  partnerLocationId: '',
  cashLine: '',
  cashLineId: '',
  billPartner: '',
  billPartnerId: '',
  billPartnerLocation: '',
  billPartnerLocationId: '',
  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: '',
  dropShipPartnerId: '',
  dropShipPartnerLocation: '',
  dropShipPartnerLocationId: '',
  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 || '',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})

const checkRequiredLines = computed(() => {
  return lines.value.filter(i => i.productId === '' || i.uomId === '' || i.qtyEntered === '' || i.priceEntered === '').length >= 1
})

const setActiveSave = () => {
  if(form.value.paymentRuleId !== '' || form.value.dateOrdered !== '' || form.value.datePromised !== '' || form.value.partnerId !== '' || form.value.partnerLocationId !== '' || form.value.warehouseId !== '' || form.value.deliveryViaRuleId !== '' || form.value.priorityRuleId !== '' || form.value.priceListId !== '' || form.value.currencyId !== '' || form.value.salesRepId !== '' || (form.value.isDropShip === false || (form.value.isDropShip === true && (form.value.dropShipPartnerId !== '' && form.value.dropShipPartnerLocationId !== ''))) && !checkRequiredLines.value) {
    activeSave.value = true
  } else {
    activeSave.value = 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('/procurements/orders')
  }
}

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

const saveLines = async (orderLines) => {
  lines.value = orderLines
  
  setActiveSave()
}

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

  let newObjValue = {}
  if(lines.value.length >= 1) {
    newObjValue = {...newObjValue, 
      orderLines: lines.value.map(entry => {
        let newObjEntry = {}
        if(entry.productId) {
          newObjEntry = {...newObjEntry, 
            M_Product_ID: {
              id: entry.productId
            }
          }
        }
        if(entry.uomId) {
          newObjEntry = {...newObjEntry, 
            C_UOM_ID: {
              id: entry.uomId
            }
          }
        }
        if(entry.taxId) {
          newObjEntry = {...newObjEntry, 
            C_Tax_ID: {
              id: entry.taxId
            }
          }
        }
        if(form.value.warehouseId) {
          newObjEntry = {...newObjEntry, 
            M_Warehouse_ID: {
              id: form.value.warehouseId
            }
          }
        }
        if(form.value.currencyId) {
          newObjEntry = {...newObjEntry, 
            C_Currency_ID: {
              id: form.value.currencyId
            }
          }
        }
        if(form.value.partnerId) {
          newObjEntry = {...newObjEntry, 
            C_BPartner_ID: {
              id: form.value.partnerId
            }
          }
        }
        if(form.value.partnerLocationId) {
          newObjEntry = {...newObjEntry, 
            C_BPartner_Location_ID: {
              id: form.value.partnerLocationId
            }
          }
        }
        if(entry.attributeSetInstanceId) {
          newObjEntry = {...newObjEntry, 
            M_AttributeSetInstance_ID: {
              id: entry.attributeSetInstanceId
            }
          }
        }
        if(entry.chargeId) {
          newObjEntry = {...newObjEntry, 
            C_Charge_ID: {
              id: entry.chargeId
            }
          }
        }
        if(entry.projectId) {
          newObjEntry = {...newObjEntry, 
            C_Project_ID: {
              id: entry.projectId
            }
          }
        }
        if(entry.campaignId) {
          newObjEntry = {...newObjEntry, 
            C_Campaign_ID: {
              id: entry.campaignId
            }
          }
        }

        return {
          line: entry.line,
          isActive: entry.isActive,
          dateOrdered: form.value.dateOrdered,
          datePromised: form.value.datePromised,
          qtyOrdered: entry?.qtyOrdered || entry.qtyEntered,
          qtyReserved: entry?.qtyReserved || 0,
          qtyDelivered: entry?.qtyDelivered || 0,
          qtyInvoiced: entry?.qtyInvoiced || 0,
          qtyLostSales: entry?.qtyLostSales || 0,
          qtyEntered: entry.qtyEntered,
          priceActual: entry.priceActual,
          priceEntered: entry.priceEntered,
          priceList: entry.priceList,
          priceLimit: entry.priceList,
          discount: entry.discount,
          lineNetAmt: entry.lineNetAmt,
          ...newObjEntry
        }
      })
    }
  }
  /*if(entries?.['payment_schedule']) {
    newObjValue = {...newObjValue, 
      paymentSchedules: entries['payment_schedule'].map(entry => {
        let newObjEntry = {}
        if(entry.payScheduleId) {
          newObjEntry = {...newObjEntry, 
            C_PaySchedule_ID: {
              id: entry.payScheduleId
            }
          }
        }

        return {
          discountAmt: entry.discountAmt,
          discountDate: entry.discountDate,
          dueAmt: entry.dueAmt,
          dueDate: entry.dueDate,
          isActive: entry.isActive,
          isValid: entry.isValid,
          ...newObjEntry
        }
      })
    }
  }*/

  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: false,
      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,
      ...newObjValue
    }
  })

  if(Number(res.status) === 200 && Number(res.id) !== 0) {
    form.value.alert.processing = false
    activeSave.value = false

    if(saveType === 'preview') {
      router.push('/procurements/orders/'+res.id+'/view')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      router.push('/procurements/orders/'+res.id+'/edit')
      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: 'Procurements'},
  { link: '/procurements/orders', text: 'Orders'},
  { link: '#', text: 'Add Order', active: true}
]))

const tab = ref(route.query?.tab || 'order')
const tabs = computed(() => ([
  { value: 'order', text: 'Order'},
  { value: 'delivery', text: 'Delivery'},
  { value: 'invoicing', text: 'Invoicing'},
  { value: 'reference', text: 'Reference'},
  { 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 = '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.dateOrdered === '' || form.datePromised === '' || form.partnerId === '' || form.partnerLocationId === '' || form.warehouseId === '' || form.deliveryViaRuleId === '' || form.priorityRuleId === '' || form.priceListId === '' || form.currencyId === '' || form.salesRepId === '' || form.docStatusId === 'CO' || (form.isDropShip && (form.dropShipPartnerId === '' || form.dropShipPartnerLocationId === '')) || checkRequiredLines || 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="tabs" />
      </div>
      <div>
        <ProcurementsOrderForm v-model="form" v-model:tab="tab" @save="save" />
      </div>
      <div>
        <ProcurementsOrderLineTable v-model="lines" action="create" :info="form" @save="saveLines" />
      </div>
    </div>
  </NuxtLayout>
</template>