<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 printPreview = usePrintPreview()
const printParam = usePrintParam()
const activeSave = useActiveSave()
const windowFrom = useWindowFrom()
const windowParam = useWindowParam()

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

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

const showDocumentAction = ref(false)
const lastRecord = ref({})
const form = ref({
  id: '',
  uid: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  warehouse: '',
  warehouseId: '',
  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: true,
  isDiscountPrinted: false,
  isTaxIncluded: false,
  isSelected: false,
  sendEMail: false,
  isSelfService: false,
  isDropShip: false,
  processedOn: 0,
  isPayScheduleValid: false,
  isPriviledgedRate: false,
  docStatus: 'Draft',
  docStatusId: 'DR',
  docType: 0,
  docTypeId: 0,
  docTypeTarget: '',
  docTypeTargetId: '',
  salesRep: '',
  salesRepId: '',
  paymentTerm: '',
  paymentTermId: '',
  currency: '',
  currencyId: '',
  invoiceRule: '',
  invoiceRuleId: '',
  deliveryViaRule: '',
  deliveryViaRuleId: '',
  deliveryRule: '',
  deliveryRuleId: '',
  priorityRule: '',
  priorityRuleId: '',
  freightCostRule: '',
  freightCostRuleId: '',
  paymentRule: '',
  paymentRuleId: '',
  priceList: '',
  priceListId: '',
  partner: '',
  partnerId: '',
  partnerLocation: '',
  partnerLocationId: '',
  cashLine: '',
  cashLineId: '',
  billPartner: '',
  billPartnerId: '',
  billPartnerLocation: '',
  billPartnerLocationId: '',
  project: '',
  projectId: '',
  campaign: '',
  campaignId: '',
  shipper: '',
  shipperId: '',
  freightCategory: '',
  freightCategoryId:  '',
  user: '',
  userId:  '',
  billUser: '',
  billUserId:  '',
  promotionCode: '',
  dropShipPartner: '',
  dropShipPartnerId: '',
  dropShipPartnerLocation: '',
  dropShipPartnerLocationId: '',
  dropShipUser: '',
  dropShipUserId:  '',
  conversionType: '',
  conversionTypeId:  '',
  orderSource: '',
  orderSourceId:  '',
  shopware6OrderId: '',
  shopifyOrderId: '',
  xentralOrderId: '',
  externalOrderId: '',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false
  }
})
const invoices = ref([])
const inouts = ref([])

const retrieve = async () => {
  const res = await $fetch('/api/orders/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: route.params.id,
      uid: res?.uid || route.params.id,
      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: res?.DocumentNo || '',
      description: res?.Description || '',
      isApproved: res?.IsApproved ?? false,
      isCreditApproved: res?.IsCreditApproved ?? false,
      isDelivered: res?.IsDelivered ?? false,
      isInvoiced: res?.IsInvoiced ?? false,
      isPrinted: res?.IsPrinted ?? false,
      isTransferred: res?.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: res?.Processed ?? false,
      isSOTrx: res?.IsSOTrx ?? true,
      isDiscountPrinted: res?.IsDiscountPrinted ?? false,
      isTaxIncluded: res?.IsTaxIncluded ?? false,
      isSelected: res?.IsSelected ?? false,
      sendEMail: res?.SendEMail ?? false,
      isSelfService: res?.IsSelfService ?? false,
      isDropShip: res?.IsDropShip ?? false,
      processedOn: res?.ProcessedOn || 0,
      isPayScheduleValid: res?.IsPayScheduleValid ?? false,
      isPriviledgedRate: res?.IsPriviledgedRate ?? false,
      docStatus: res?.DocStatus?.identifier || 'Draft',
      docStatusId: res?.DocStatus?.id || '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 || '',
      shopware6OrderId: res?.shopware6_order_id || '',
      shopifyOrderId: res?.shopify_order_id || '',
      xentralOrderId: res?.xentral_order_id || '',
      externalOrderId: res?.ExternalOrderId || '',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }
    lastRecord.value = res
    setNoEdit()
    activeSave.value = false

    invoices.value = res?.c_invoice || []
    inouts.value = res?.m_inout || []
  }
}
onMounted(retrieve)

const noEdit = ref(true)
const setNoEdit = () => {
  noEdit.value = (
    form.value.organizationId == (lastRecord.value?.AD_Org_ID?.id || '') &&
    form.value.warehouseId == (lastRecord.value?.M_Warehouse_ID?.id || '') &&
    form.value.isActive == (lastRecord.value?.IsActive ?? true) &&
    form.value.documentNo == (lastRecord.value?.DocumentNo || '') &&
    form.value.description == (lastRecord.value?.Description || '') &&
    form.value.isApproved == (lastRecord.value?.IsApproved ?? false) &&
    form.value.isCreditApproved == (lastRecord.value?.IsCreditApproved ?? false) &&
    form.value.isDelivered == (lastRecord.value?.IsDelivered ?? false) &&
    form.value.isInvoiced == (lastRecord.value?.IsInvoiced ?? false) &&
    form.value.isPrinted == (lastRecord.value?.IsPrinted ?? false) &&
    form.value.isTransferred == (lastRecord.value?.IsTransferred ?? false) &&
    form.value.dateOrdered == (lastRecord.value?.DateOrdered || date.now('date')) &&
    form.value.datePromised == (lastRecord.value?.DatePromised || date.now('date')) &&
    form.value.dateAcct == (lastRecord.value?.DateAcct || date.now('date')) &&
    form.value.freightAmt == (lastRecord.value?.FreightAmt || 0) &&
    form.value.totalLines == (lastRecord.value?.TotalLines || 0) &&
    form.value.grandTotal == (lastRecord.value?.GrandTotal || 0) &&
    form.value.chargeAmt == (lastRecord.value?.ChargeAmt || 0) &&
    form.value.processed == (lastRecord.value?.Processed ?? false) &&
    form.value.isSOTrx == (lastRecord.value?.IsSOTrx ?? true) &&
    form.value.isDiscountPrinted == (lastRecord.value?.IsDiscountPrinted ?? false) &&
    form.value.isTaxIncluded == (lastRecord.value?.IsTaxIncluded ?? false) &&
    form.value.isSelected == (lastRecord.value?.IsSelected ?? false) &&
    form.value.sendEMail == (lastRecord.value?.SendEMail ?? false) &&
    form.value.isSelfService == (lastRecord.value?.IsSelfService ?? false) &&
    form.value.isDropShip == (lastRecord.value?.IsDropShip ?? false) &&
    form.value.processedOn == (lastRecord.value?.ProcessedOn || 0) &&
    form.value.isPayScheduleValid == (lastRecord.value?.IsPayScheduleValid ?? false) &&
    form.value.isPriviledgedRate == (lastRecord.value?.IsPriviledgedRate ?? false) &&
    form.value.docStatusId == (lastRecord.value?.DocStatus?.id || '') &&
    form.value.docTypeId == (lastRecord.value?.C_DocType_ID?.id || '') &&
    form.value.docTypeTargetId == (lastRecord.value?.C_DocTypeTarget_ID?.id || '') &&
    form.value.salesRepId == (lastRecord.value?.SalesRep_ID?.id || '') &&
    form.value.paymentTermId == (lastRecord.value?.C_PaymentTerm_ID?.id || '') &&
    form.value.currencyId == (lastRecord.value?.C_Currency_ID?.id || '') &&
    form.value.invoiceRuleId == (lastRecord.value?.InvoiceRule?.id || '') &&
    form.value.deliveryViaRuleId == (lastRecord.value?.DeliveryViaRule?.id || '') &&
    form.value.deliveryRuleId == (lastRecord.value?.DeliveryRule?.id || '') &&
    form.value.priorityRuleId == (lastRecord.value?.PriorityRule?.id || '') &&
    form.value.freightCostRuleId == (lastRecord.value?.FreightCostRule?.id || '') &&
    form.value.paymentRuleId == (lastRecord.value?.PaymentRule?.id || '') &&
    form.value.priceListId == (lastRecord.value?.M_PriceList_ID?.id || '') &&
    form.value.partnerId == (lastRecord.value?.C_BPartner_ID?.id || '') &&
    form.value.partnerLocationId == (lastRecord.value?.C_BPartner_Location_ID?.id || '') &&
    form.value.cashLineId == (lastRecord.value?.C_CashLine_ID?.id || '') &&
    form.value.billPartnerId == (lastRecord.value?.Bill_BPartner_ID?.id || '') &&
    form.value.billPartnerLocationId == (lastRecord.value?.Bill_Location_ID?.id || '') &&
    form.value.projectId == (lastRecord.value?.C_Project_ID?.id || '') &&
    form.value.campaignId == (lastRecord.value?.C_Campaign_ID?.id || '') &&
    form.value.shipperId == (lastRecord.value?.M_Shipper_ID?.id || '') &&
    form.value.freightCategoryId == (lastRecord.value?.M_FreightCategory_ID?.id || '') &&
    form.value.userId == (lastRecord.value?.AD_User_ID?.id || '') &&
    form.value.billUserId == (lastRecord.value?.Bill_User_ID?.id || '') &&
    form.value.promotionCode == (lastRecord.value?.PromotionCode || '') &&
    form.value.dropShipPartnerId == (lastRecord.value?.DropShip_BPartner_ID?.id || '') &&
    form.value.dropShipPartnerLocationId == (lastRecord.value?.DropShip_Location_ID?.id || '') &&
    form.value.dropShipUserId == (lastRecord.value?.DropShip_User_ID?.id || '') &&
    form.value.conversionTypeId == (lastRecord.value?.C_ConversionType_ID?.id || '') &&
    form.value.orderSourceId == (lastRecord.value?.C_OrderSource_ID?.id || '')
  ) ? true : 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 duplicate = () => {
  //router.push(`/sales/fulfillment-orders/${route.params.id}/duplicate`)
  openTab('/duplicate/sales-fulfillment-order-'+route.params.id, 'Fulfillment Order: Duplicate')
}
const print = () => {
  //router.push(`/sales/fulfillment-orders/${props.params.data.id}/print`)
  printParam.value = form.value
  printPreview.value = true
}

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/fulfillment-orders')
    if(window('partners')?.path) {
      windowFrom.value = ''
      windowParam.value = {}
    }*/
    let newUrl = '/sales/fulfillment-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
  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/orders/update', {
    method: 'PUT',
    headers: useRequestHeaders(['cookie']),
    body: {
      id: form.value.id,
      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,
    }
  })

  if(Number(res.status) === 200) {
    windowFrom.value = ''
    windowParam.value = {}
    form.value.alert.processing = false
    activeSave.value = false
    
    if(saveType === 'preview') {
      //router.push('/sales/fulfillment-orders/'+res.id+'/view')
      openTab('/view/sales-fulfillment-order-'+res.id, 'Fulfillment Order: View Details')
    } else if(saveType === 'changes' || saveType === 'onlysave') {
      form.value.alert.processing = false
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
      retrieve()
      // location.reload()
    } else {
      back()
    }
  } else {
    //form.value.alert.status = res.status
    //form.value.alert.message = res.message
    form.value.alert.processing = false
    activeSave.value = true
    toast({
      message: res.message || 'Save error',
      type: 'is-danger',
      duration: 2000
    })
    //window.scrollTo(0, 0)
  }
}

const showAttachment = ref(false)

const breadCrumb = computed(() => ([
  { link: '#', text: 'Sales'},
  { link: '/sales/fulfillment-orders', text: 'Fulfillment Orders'},
  { link: '#', text: 'Edit 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 isOpen = ref(false)

// const { data, error, pending } = useFetch('/api/changelog/' + route.params.id, {
//   headers: useRequestHeaders(['cookie'])
// })

const data = ref(null)
const error = ref(null)
const pending = ref(false)
const fetchData = async () => {
  pending.value = true
  let groupedByUpdated = {}

  const { data: fetchedData, error: fetchError } = await useFetch('/api/changelog/' + route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })

  groupedByUpdated = fetchedData.value?.reduce((acc, item) => {
    const updatedKey = item.Updated;
    if (!acc[updatedKey]) {
      acc[updatedKey] = [];
    }
    acc[updatedKey].push(item);
    return acc;
  }, {});
  //groupedByUpdated = Object.values(groupedByUpdated).map(arr => arr?.[Number(arr.length) - 1] || []).flat()

  console.log('YOUNES')
  //console.log(fetchedData.value)
  console.log(groupedByUpdated)
  
  data.value = groupedByUpdated
  error.value = fetchError.value
  pending.value = false
}

const setDocumentAction = async (docAction) => {
  const res = await $fetch('/api/orders/'+route.params.id+'/document-action', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      documentAction: docAction
    }
  })
  if(res) {
    toast({
      message: 'Document has been successfully set to '+docAction+' status.',
      type: 'is-success',
      duration: 2000
    })
    back()
  } else {
    toast({
      message: 'Document failed to set to '+docAction+' status.',
      type: 'is-danger',
      duration: 2000
    })
  }
}

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 = 'sales-orders'
    if(windowParam.value) {
      windowParam.value['sales-orders'] = {
        path: url.pathname,
        data: form.value
      }
    } else {
      windowParam.value = {
        'sales-orders': {
          path: url.pathname,
          data: form.value
        }
      }
    }
    
    tabs.value.map(item => {
      item.active = false
      return item
    })
    if(tabs.value.filter(i => i.link === toPath).length >= 1) {
      const tabIndex = tabs.value.findIndex(i => i.link === toPath)
      tabs.value[tabIndex].active = true
      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 takeFieldLabel = (fieldName) => {
  const splitFieldLabels = fieldName.split('_')
  return splitFieldLabels[Number(splitFieldLabels.length || 1) - 1]
}
</script>

<template>
  <Head>
    <Title>Edit 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 === '')) || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save</button>
        <template v-if="form.id !== ''">
          <button type="button" @click="submit" 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 === '')) || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>
          <button type="button" @click="showAttachment = true" class="button" :class="(form.processing) ? 'pointerEvents-none opacity-0.6' : ''">Attachment</button>
          <button type="button" @click="duplicate" class="button" :class="(!noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Duplicate</button>

          <!--<div v-if="form.id !== '' && form.docStatusId !== 'CO'">
            <button type="button" class="button" @click="showDocumentAction = true">Document Action</button>
          </div>-->

          <button type="button" class="button" @click="isOpen = true; fetchData();">History</button>
          <button type="button" class="button" @click="print();">Print Preview</button>

          <template v-if="form.docStatusId !== 'CO' && form.docStatusId !== 'VO' && form.docStatusId !== 'CL'">
            <button type="button" class="button" @click="setDocumentAction('CO')">Complete</button>
          </template>
          <button type="button" class="button" @click="setDocumentAction('VO')">Void</button>

          <USlideover v-model="isOpen" :overlay="false">
              <div class="p-4 flex-1 scrollover historyslidein">
                <div class="timeline">
                  <header class="timeline-header">
                    <span class="tag is-medium is-primary">Start</span>
                  </header>

                  <div v-if="error">{{ error.message }}</div>
                  <div v-else-if="pending">Loading...</div>
                  <template v-else>
                    <div class="timeline-item" v-for="(itm, indx) in Object.entries(data ?? {})" :key="indx">
                      <div class="timeline-marker"></div>
                      <div class="timeline-content">
                        <h3>{{ date.format(itm[0], '', 'de-DE') }}</h3>
                        <p v-for="(it, idx) in itm[1]" :key="idx">{{ takeFieldLabel(it.AD_Column_ID.identifier || '_') }} - {{ it.UpdatedBy.identifier }} - {{ it.OldValue }} - {{ it.NewValue }}</p>
                      </div>
                    </div>
                  </template>
<!--                  <div  v-else class="timeline-item" v-for="(entry, index) in data" :key="index">-->
<!--                    <div class="timeline-marker"></div>-->
<!--                    <div class="timeline-content">-->
<!--                      <div class="card">-->
<!--                        <header class="card-header">-->
<!--                          <p class="card-header-title">{{ entry.Updated }}</p>-->
<!--                          <button class="card-header-icon" aria-label="more options">-->
<!--                            <span class="icon">-->
<!--                              <i class="fas fa-angle-down" aria-hidden="true"></i>-->
<!--                            </span>-->
<!--                          </button>-->
<!--                        </header>-->
<!--                        <div class="card-content">-->
<!--                          <div class="content">-->
<!--                            <span>-->
<!--                            <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-5 h-5 personicon">-->
<!--                              <path stroke-linecap="round" stroke-linejoin="round" d="M15.75 6a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0ZM4.501 20.118a7.5 7.5 0 0 1 14.998 0A17.933 17.933 0 0 1 12 21.75c-2.676 0-5.216-.584-7.499-1.632Z" />-->
<!--                            </svg>-->
<!--                            <span  class="personchanged">{{ entry.UpdatedBy.identifier }}</span>-->
<!--                              </span>-->
<!--                            changed:-->
<!--                          </div>-->
<!--                        </div>-->
<!--                        <footer class="card-footer">-->
<!--                          <a href="#" class="card-footer-item">{{ entry.AD_Column_ID.identifier }}</a>-->
<!--                        </footer>-->
<!--                        <footer class="card-footer">-->
<!--                          <a href="#" class="card-footer-item">{{ entry.OldValue }}</a>-->
<!--                          <div class="is-divider-vertical" data-content="&ndash;&gt;"></div>-->
<!--                          <a href="#" class="card-footer-item">{{ entry.NewValue }}</a>-->
<!--                        </footer>-->
<!--                      </div>-->
<!--                    </div>-->
<!--                  </div>-->


<!--                  <div class="timeline-item">-->
<!--                    <div class="timeline-marker is-image is-32x32">-->
<!--                      <img src="https://bulma.io/images/placeholders/32x32.png">-->
<!--                    </div>-->
<!--                    <div class="timeline-content">-->
<!--                      <p class="heading">February 2016</p>-->
<!--                      <p>Timeline content - Can include any HTML element</p>-->
<!--                    </div>-->
<!--                  </div>-->
<!--                  <header class="timeline-header">-->
<!--                    <span class="tag is-primary">2017</span>-->
<!--                  </header>-->
<!--                  <div class="timeline-item">-->
<!--                    <div class="timeline-marker is-icon">-->
<!--                      <i class="fa fa-flag"></i>-->
<!--                    </div>-->
<!--                    <div class="timeline-content">-->
<!--                      <p class="heading">March 2017</p>-->
<!--                      <p>Timeline content - Can include any HTML element</p>-->
<!--                    </div>-->
<!--                  </div>-->
                  <div class="timeline-header">
                    <span class="tag is-medium is-primary">End</span>
                  </div>
                </div>

              </div>
            </USlideover>

        </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="tabs2" />
      </div>
      <div class="editwrapper">
        <div class="columns is-desktop">
          <div class="column is-three-quarters">
            <SalesOrderForm v-model="form" v-model:tab="tab" @save="save" />
          </div>
          <div class="column is-one-quarter">
            <h3 class="fw-bold mb-2">Sales Invoices</h3>
            <p v-for="(sur, inx) in invoices" :key="inx">
              <span @click="goTo('/windows/sales-invoices-edit/'+sur.id, 'Invoice: '+sur.DocumentNo)" 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 inouts" :key="inx">
              <span @click="goTo('/windows/sales-shipments-edit/'+sur.id, 'Shipment: '+sur.DocumentNo)" class="cursor-pointer">{{ sur.DocumentNo }} - {{ sur.DateAcct }} - {{ sur.IsCommissioned ? 'Yes' : 'No' }}</span>
            </p>
          </div>
        </div>
      </div>
      <div>
        <SalesOrderDetailRecord :action="(form.docStatusId === 'CO' || form.docStatusId === 'VO') ? 'view' : 'edit'" :info="form" tab="order_line" />
      </div>
      <div>
        <AttachmentModal v-model="showAttachment" target="C_Order" :info="form" />
      </div>
    </div>
  </NuxtLayout>

  <Teleport to="body">
    <PrintPreview modelName="orders" />
    <SalesOrderDocumentAction v-model="showDocumentAction" :id="form.id" v-model:docId="form.docStatusId"/>
  </Teleport>
</template>

<style scoped>
.scrollover {
  overflow: scroll;
}
.historyslidein {
  border-left: 1px solid #535353;
}
.card-footer-item:not(:last-child) {
  border-inline-end: none;
}

.personicon {
  float:left;
  margin-right: 5px;
}
.personchanged {
  border: 1px solid grey;
  border-radius: 3px;
  padding:3px 5px 3px 5px;
  background-color: #3273dc;
  color: white;
}
</style>