<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: 'Draft',
  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 retrieve = async () => {
  const res = await $fetch('/api/orders/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: '',
      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 || '',
      warehouse: res?.M_Warehouse_ID?.identifier || '',
      warehouseId: res?.M_Warehouse_ID?.id || '',
      isActive: res?.IsActive ?? true,
      documentNo: '',
      poReference: '',
      description: res?.Description || '',
      isApproved: false,
      isCreditApproved: false,
      isDelivered: false,
      isInvoiced: false,
      isPrinted: false,
      isTransferred: false,
      dateOrdered: res?.DateOrdered || date.now('date'),
      datePromised: res?.DatePromised || date.now('date'),
      dateAcct: res?.DateAcct || date.now('date'),
      freightAmt: res?.FreightAmt || 0,
      totalLines: res?.TotalLines || 0,
      grandTotal: res?.GrandTotal || 0,
      chargeAmt: res?.ChargeAmt || 0,
      processed: false,
      isSOTrx: false,
      isDiscountPrinted: false,
      isTaxIncluded: res?.IsTaxIncluded ?? false,
      isSelected: res?.IsSelected ?? false,
      sendEMail: res?.SendEMail ?? false,
      isSelfService: false,
      isDropShip: res?.IsDropShip ?? false,
      processedOn: 0,
      isPayScheduleValid: res?.IsPayScheduleValid ?? false,
      isPriviledgedRate: res?.IsPriviledgedRate ?? false,
      docStatus: 'Draft',
      docStatusId: 'DR',
      docType: res?.C_DocType_ID?.identifier || '',
      docTypeId: res?.C_DocType_ID?.id || '',
      docTypeTarget: res?.C_DocTypeTarget_ID?.identifier || '',
      docTypeTargetId: res?.C_DocTypeTarget_ID?.id || '',
      salesRep: res?.SalesRep_ID?.identifier || '',
      salesRepId: res?.SalesRep_ID?.id || '',
      paymentTerm: res?.C_PaymentTerm_ID?.identifier || '',
      paymentTermId: res?.C_PaymentTerm_ID?.id || '',
      currency: res?.C_Currency_ID?.identifier || '',
      currencyId: res?.C_Currency_ID?.id || '',
      invoiceRule: res?.InvoiceRule?.identifier || '',
      invoiceRuleId: res?.InvoiceRule?.id || '',
      deliveryViaRule: res?.DeliveryViaRule?.identifier || '',
      deliveryViaRuleId: res?.DeliveryViaRule?.id || '',
      deliveryRule: res?.DeliveryRule?.identifier || '',
      deliveryRuleId: res?.DeliveryRule?.id || '',
      priorityRule: res?.PriorityRule?.identifier || '',
      priorityRuleId: res?.PriorityRule?.id || '',
      freightCostRule: res?.FreightCostRule?.identifier || '',
      freightCostRuleId: res?.FreightCostRule?.id || '',
      paymentRule: res?.PaymentRule?.identifier || '',
      paymentRuleId: res?.PaymentRule?.id || '',
      priceList: res?.M_PriceList_ID?.identifier || '',
      priceListId: res?.M_PriceList_ID?.id || '',
      partner: res?.C_BPartner_ID?.identifier || '',
      partnerId: res?.C_BPartner_ID?.id || '',
      partnerLocation: res?.C_BPartner_Location_ID?.identifier || '',
      partnerLocationId: res?.C_BPartner_Location_ID?.id || '',
      cashLine: res?.C_CashLine_ID?.identifier || '',
      cashLineId: res?.C_CashLine_ID?.id || '',
      billPartner: res?.Bill_BPartner_ID?.identifier || '',
      billPartnerId: res?.Bill_BPartner_ID?.id || '',
      billPartnerLocation: res?.Bill_Location_ID?.identifier || '',
      billPartnerLocationId: res?.Bill_Location_ID?.id || '',
      project: res?.C_Project_ID?.identifier || '',
      projectId: res?.C_Project_ID?.id || '',
      campaign: res?.C_Campaign_ID?.identifier || '',
      campaignId: res?.C_Campaign_ID?.id || '',
      shipper: res?.M_Shipper_ID?.identifier || '',
      shipperId: res?.M_Shipper_ID?.id || '',
      freightCategory: res?.M_FreightCategory_ID?.identifier || '',
      freightCategoryId: res?.M_FreightCategory_ID?.id || '',
      user: res?.AD_User_ID?.identifier || '',
      userId:  res?.AD_User_ID?.id || '',
      billUser: res?.Bill_User_ID?.identifier || '',
      billUserId:  res?.Bill_User_ID?.id || '',
      promotionCode: res?.PromotionCode || '',
      dropShipPartner: res?.DropShip_BPartner_ID?.identifier || '',
      dropShipPartnerId: res?.DropShip_BPartner_ID?.id || '',
      dropShipPartnerLocation: res?.DropShip_Location_ID?.identifier || '',
      dropShipPartnerLocationId: res?.DropShip_Location_ID?.id || '',
      dropShipUser: res?.DropShip_User_ID?.identifier || '',
      dropShipUserId:  res?.DropShip_User_ID?.id || '',
      conversionType: res?.C_ConversionType_ID?.identifier || '',
      conversionTypeId:  res?.C_ConversionType_ID?.id || '',
      orderSource: res?.C_OrderSource_ID?.identifier || '',
      orderSourceId: res?.C_OrderSource_ID?.id || '',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }

    lines.value = res.c_orderline.map(item => {
      return {
        id: '',
        client: item?.AD_Client_ID?.identifier || '',
        clientId: item?.AD_Client_ID?.id || '',
        organization: item?.AD_Org_ID?.identifier || '',
        organizationId: item?.AD_Org_ID?.id || '',
        warehouse: item?.M_Warehouse_ID?.identifier || '',
        warehouseId: item?.M_Warehouse_ID?.id || '',
        order: item?.C_Order_ID?.identifier || '',
        orderId: item?.C_Order_ID?.id || '',
        isActive: item?.IsActive ?? true,
        line: item?.Line || '',
        product: item?.M_Product_ID?.Name || '',
        productId: item?.M_Product_ID?.id || '',
        galleries: [],
        qtyEntered: item?.QtyEntered || 1,
        qtyOrdered: item?.QtyOrdered || 1,
        qtyReserved: item?.QtyReserved || 0.0,
        qtyDelivered: item?.QtyDelivered || 0.0,
        qtyInvoiced: item?.QtyInvoiced || 0.0,
        uom: item?.C_UOM_ID?.identifier || '',
        uomId: item?.C_UOM_ID?.id || '',
        priceActual: item?.PriceActual || 0,
        priceEntered: item?.PriceEntered || 0,
        priceList: item?.PriceList || 0,
        tax: item?.C_Tax_ID?.identifier || '',
        taxId: item?.C_Tax_ID?.id || '',
        discount: item?.Discount || 0,
        lineNetAmt: item?.LineNetAmt || 0,
        currency: item?.C_Currency_ID?.identifier || '',
        currencyId: item?.C_Currency_ID?.id || '',
        attributeSetInstance: item?.M_AttributeSetInstance_ID?.identifier || '',
        attributeSetInstanceId: item?.M_AttributeSetInstance_ID?.id || '',
        charge: item?.C_Charge_ID?.identifier || '',
        chargeId: item?.C_Charge_ID?.id || '',
        project: item?.C_Project_ID?.identifier || '',
        projectId: item?.C_Project_ID?.id || '',
        campaign: item?.C_Campaign_ID?.identifier || '',
        campaignId: item?.C_Campaign_ID?.id || '',
        show: false,
        alert: {
          status: '',
          message: '',
          processing: false,
        }
      }
    })
    
    const newEntries = []
    for(let item of lines.value) {
      const response = await $fetch(`/api/materials/products/${item.productId}`)
      if(response?.Strapi_Product_documentId) {
        const resp = await $fetch(`/api/materials/products/${response.Strapi_Product_documentId}/galleries/images`)
        if(resp) {
          item.galleries = resp
        }
      }
      newEntries.push(item)
    }
    lines.value = newEntries
  
    setActiveSave()
  }
}
onMounted(retrieve)

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>