<script setup>
import { date } from 'alga-js'
import { toast } from 'bulma-toast'
import shared from '@/assets/langs/shared.js'

const lang = ref('en-US')
const nuxtToast = useToast()
const getLang = computed(() => {
  return shared(lang.value)
})

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 { getMenuType } = useRoleMenu()

// This will be set using the composable method
const defaultSideBarMenu = ref('Menu')


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,
  dateCreated: date.now('date'),
  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: '',
  partnerLocationStreet: '',
  partnerLocationStreet2: '',
  partnerLocationZip: '',
  partnerLocationCity: '',
  partnerLocationCountry: '',
  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: '',
  amazonOrderId: '',
  plentyOneOrderId: '',
  inouts: [],
  canceledDate: '',
  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) {
    console.log(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,
      dateCreated: res?.Created || '',
      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 || res?.C_BPartner_Location_ID?.C_Location_ID?.identifier || '',
      partnerLocationId: res?.C_BPartner_Location_ID?.id || '',
      partnerLocationStreet: res?.C_BPartner_Location_ID?.C_Location_ID?.Address1 || '',
      partnerLocationStreet2: res?.C_BPartner_Location_ID?.C_Location_ID?.Address2 || '',
      partnerLocationZip: res?.C_BPartner_Location_ID?.C_Location_ID?.Postal || '',
      partnerLocationCity: res?.C_BPartner_Location_ID?.C_Location_ID?.City || '',
      partnerLocationCountry: res?.C_BPartner_Location_ID?.C_Location_ID?.C_Country_ID?.identifier || '',
      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 || '',
      amazonOrderId: res?.amazon_order_id || '',
      plentyOneOrderId: res?.plentyone_order_id || '',
      inouts: res?.m_inout ?? [],
      canceledDate: '',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }
    lastRecord.value = res
    setNoEdit()
    activeSave.value = false

    invoices.value = res?.c_invoice || []
    inouts.value = res?.m_inout || []
  }
}






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 || '') &&
    form.value.shopware6OrderId == (lastRecord.value?.shopware6_order_id || '') &&
    form.value.shopifyOrderId == (lastRecord.value?.shopify_order_id || '') &&
    form.value.xentralOrderId == (lastRecord.value?.xentral_order_id || '') &&
    form.value.plentyOneOrderId == (lastRecord.value?.plentyone_order_id || '') &&
    form.value.externalOrderId == (lastRecord.value?.ExternalOrderId || '')
  ) ? 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/orders/${route.params.id}/duplicate`)
  openTab('/duplicate/sales-order-'+route.params.id, 'Sales Order: Duplicate')
}
const print = () => {
  //router.push(`/sales/orders/${route.params.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/orders')
    if(window('partners')?.path) {
      windowFrom.value = ''
      windowParam.value = {}
    }*/
    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
  setNoEdit()
  if(!noEdit.value) {
    activeSave.value = true
  } else {
    activeSave.value = false
  }
}

const submit = async (saveType = '') => {
  if(activeSave.value === false && saveType === 'onlysave') return;
  if(activeSave.value === true && saveType === 'onlysave') {
    toast({
      message: 'Saving process...',
      type: 'is-info',
      duration: 2500
    })
  }
  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,
      dateCreated: form.value.dateCreated,
      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') {
      form.value.alert.processing = false
      toast({
        message: 'Saved!',
        type: 'is-success',
        duration: 2000
      })
      retrieve()
      // location.reload()
    } else if(saveType === 'onlysave') {
      form.value.alert.processing = false
      retrieve()
    } 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/orders', text: 'Orders'},
  { link: '#', text: 'Edit Order', active: true}
]))

const tab = ref(route.query?.tab || 'order')
const tabs2 = computed(() => {
  if (defaultSideBarMenu.value === 'c') {
    // Limited tabs for customer menu
    return [
      {value: 'order', text: 'Order'}
    ]
  }

  // Full tabs for other menus
  return [
    {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 getCancellationDateFromChangelog = (changelogData) => {
  if (!changelogData) return null

  // For voided orders, look for the Processed_Processed column change to "true"
  const cancelEntry = changelogData.find(item => {
    const isProcessedColumn = item.AD_Column_ID?.identifier === 'Processed_Processed'
    const isProcessedTrue = item.NewValue === 'true'

    return isProcessedColumn && isProcessedTrue
  })

  return cancelEntry ? cancelEntry.Updated : null
}

const fetchData = async () => {
  pending.value = true
  let groupedByUpdated = {}

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

  console.log('=== CHANGELOG ENTRIES ===')
  if (fetchedData.value && Array.isArray(fetchedData.value)) {
    fetchedData.value.forEach((item, index) => {
      console.log(`Entry ${index + 1}: Column="${item.AD_Column_ID?.identifier}" Old="${item.OldValue}" New="${item.NewValue}" Date="${item.Updated}" User="${item.UpdatedBy?.identifier}"`)
    })
  }

  if (fetchedData.value) {
    // Extract cancellation date if order is voided
    if (form.value.docStatusId === 'VO') {
      const cancelDate = getCancellationDateFromChangelog(fetchedData.value)
      if (cancelDate) {
        form.value.canceledDate = cancelDate
      }
    }

    groupedByUpdated = fetchedData.value?.reduce((acc, item) => {
      const updatedKey = item.Updated;
      if (!acc[updatedKey]) {
        acc[updatedKey] = [];
      }
      acc[updatedKey].push(item);
      return acc;
    }, {});
  }

  data.value = groupedByUpdated
  error.value = fetchError.value
  pending.value = false
}

const setDocumentAction = async (docAction) => {
  let shouldProceed = true;

  if (docAction === 'VO') {
    shouldProceed = confirm('Möchten sie diesen Auftrag stornieren?');
  }

  if (shouldProceed) {
    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
      })
      if(docAction !== 'RE') {
        back()
      } else {
        location.reload()
      }
    } 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]
}

const getShippingDateWithRandomMinutes = (shippingDate) => {
  if (!shippingDate) return ''

  const baseDate = new Date(shippingDate)
  const randomMinutes = Math.floor(Math.random() * (20 - 5 + 1) + 5)
  baseDate.setMinutes(baseDate.getMinutes() + randomMinutes)

  return date.format(baseDate, 'DD.MM.YYYY HH:mm', 'de-DE')
}

const copyTrackingNumber = async () => {
  const trackingNo = form.value.inouts[0]?.TrackingNo
  if (!trackingNo) {
    nuxtToast.add({
      title: 'Error',
      description: 'No tracking number available to copy',
      color: 'red',
      timeout: 3000
    })
    return
  }

  try {
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(trackingNo)
    } else {
      // Fallback for older browsers or non-secure contexts
      const textArea = document.createElement('textarea')
      textArea.value = trackingNo
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      document.execCommand('copy')
      textArea.remove()
    }

    nuxtToast.add({
      id: 'tracking-copy-success',
      title: 'Tracking Number Copied!',
      description: `Tracking number ${trackingNo} has been copied to clipboard`,
      timeout: 4000,
      icon: 'i-heroicons-clipboard-document-check',
      ui: {
        wrapper: 'relative overflow-hidden',
        container: 'bg-green-500 text-white shadow-lg',
        ring: '',
        rounded: 'rounded-lg',
        padding: 'p-4',
        gap: 'gap-3',
        title: 'text-white font-semibold text-sm',
        description: 'text-white text-sm opacity-90',
        icon: {
          base: 'flex-shrink-0 w-5 h-5',
          color: 'text-white'
        }
      }
    })
  } catch (error) {
    nuxtToast.add({
      title: 'Copy Failed',
      description: 'Failed to copy tracking number to clipboard',
      color: 'red',
      timeout: 3000,
      icon: 'i-heroicons-exclamation-triangle'
    })
  }
}

const attachmentQty = ref(0)
const getAttachment = async () => {
  const getAttachmentRecord = await $fetch(`/api/attachments/C_Order/${route.params.id}`)
  if(getAttachmentRecord?.Strapi_Attachment_ID && getAttachmentRecord?.Strapi_Attachment_documentId) {
    const res = await $fetch(`/api/attachments/C_Order/${getAttachmentRecord.Strapi_Attachment_documentId}/files`, {
      headers: useRequestHeaders(['cookie'])
    })
    if(res) {
      attachmentQty.value = res?.length ?? 0
    }
  }
}

// Computed property to get timeline steps in chronological order
const timelineSteps = computed(() => {
  const steps = []

  // Always add creation step first
  steps.push({
    key: 'created',
    title: 'Erstellt',
    date: form.value.dateCreated,
    completed: true,
    active: true,
    icon: 'ti-check',
    type: 'normal',
    order: 1
  })

  // Add processing step
  const hasProcessing = form.value.inouts && form.value.inouts.length > 0 && form.value.inouts[0].id
  steps.push({
    key: 'processing',
    title: 'In Bearbeitung',
    date: hasProcessing ? form.value.inouts[0].Created : null,
    completed: hasProcessing,
    active: hasProcessing,
    icon: 'ti-package',
    type: 'normal',
    order: 2
  })

  // Add commissioned step
  const hasCommissioned = form.value.inouts && form.value.inouts.length > 0 && form.value.inouts[0].IsCommissioned
  let commissionedDate = null
  if (hasCommissioned && form.value.inouts[0].shipping_date) {
    const baseDate = new Date(form.value.inouts[0].shipping_date)
    baseDate.setHours(baseDate.getHours() + 2)
    commissionedDate = baseDate.toISOString()
  }
  steps.push({
    key: 'commissioned',
    title: 'Kommissioniert',
    date: commissionedDate,
    completed: hasCommissioned,
    active: hasCommissioned,
    icon: 'ti-barcode',
    type: 'normal',
    order: 3
  })

  // Add shipped step
  const hasShipped = form.value.inouts && form.value.inouts.length > 0 && form.value.inouts[0].TrackingNo && form.value.inouts[0].TrackingNo.trim() !== ''
  steps.push({
    key: 'shipped',
    title: 'Versandt',
    date: hasShipped ? form.value.inouts[0].shipping_date : null,
    completed: hasShipped,
    active: hasShipped,
    icon: 'ti-truck-delivery',
    type: 'normal',
    order: 4
  })

  // Add canceled step if order is voided
  if (form.value.docStatusId === 'VO') {
    steps.push({
      key: 'canceled',
      title: 'Storniert',
      date: form.value.canceledDate || form.value.dateCreated,
      completed: true,
      active: true,
      icon: 'ti-x',
      type: 'canceled',
      order: 5
    })
  }

  // Sort steps chronologically for voided orders, logically for others
  return steps.sort((a, b) => {
    if (form.value.docStatusId === 'VO') {
      // For voided orders, sort chronologically by actual dates
      const dateA = a.date ? new Date(a.date) : new Date('9999-12-31') // Future date for incomplete steps
      const dateB = b.date ? new Date(b.date) : new Date('9999-12-31')

      // If dates are equal, use logical order
      if (dateA.getTime() === dateB.getTime()) {
        return a.order - b.order
      }

      return dateA - dateB
    } else {
      // For non-voided orders, use logical order
      return a.order - b.order
    }
  })
})

onMounted(async () => {
  await retrieve()
  defaultSideBarMenu.value = getMenuType()
  if (document.documentElement.getAttribute('lang')) {
    lang.value = document.documentElement.getAttribute('lang')
  }

  // Fetch changelog data automatically if order is voided to get cancellation date
  if (form.value.docStatusId === 'VO') {
    await fetchData()
  }

  // Get attachment information
  await getAttachment()
})
watch(() => route.params, getAttachment)
</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('changes')" 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 === 'CO1' || (form.isDropShip && (form.dropShipPartnerId === '' || form.dropShipPartnerLocationId === '')) || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''"><span class="tf-icon ti ti-device-floppy ti-xs me-1 color-inherit"></span> </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 === 'CO1' || (form.isDropShip && (form.dropShipPartnerId === '' || form.dropShipPartnerLocationId === '')) || noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''">Save + Exit</button>-->
          <button title="Dateien" type="button" @click="showAttachment = true" class="button hasBadge" :class="(form.processing) ? 'pointerEvents-none opacity-0.6' : ''">
            <span class="tf-icon ti ti-paperclip ti-xs me-1 color-inherit"></span>
            <span class="badgeAttachment">{{ attachmentQty }}</span>
          </button>
          <button title="Duplizieren" v-if="defaultSideBarMenu !== 'c'" type="button" @click="duplicate" class="button" :class="(!noEdit || form.alert.processing) ? 'pointerEvents-none opacity-0.6' : ''"><span class="tf-icon ti ti-copy ti-xs me-1 color-inherit"></span></button>


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

          <button v-if="defaultSideBarMenu !== 'c'" type="button" class="button" @click="isOpen = true; fetchData();">History</button>

<!--          <template v-if="form.docStatusId === 'CO'">-->
          <template v-if="defaultSideBarMenu !== 'c'">
          <button type="button" class="button" @click="print();">Print Preview</button>
          </template>
          <template v-if="form.docStatusId !== 'CO' && form.docStatusId !== 'VO' && form.docStatusId !== 'CL'">
            <button type="button" class="button" @click="setDocumentAction('CO')">Complete</button>
          </template>
          <template v-if="defaultSideBarMenu !== 'c' && form.docStatusId === 'CO' || form.docStatusId === 'RE'">
            <button type="button" class="button" @click="setDocumentAction('CL')">Close</button>
          </template>
<!--          <template v-if="defaultSideBarMenu !== 'c' && form.docStatusId === 'CO' || form.docStatusId === 'VO' || form.docStatusId === 'CL'">-->
          <template v-if="form.docStatusId === 'CO' && !inouts[0]?.TrackingNo">
          <button type="button" class="button" @click="setDocumentAction('RE')">Re-Activate</button>
          </template>
          <button v-if="!inouts[0]?.TrackingNo && form.docStatusId !== 'VO'" type="button" class="button color-backgr-red" @click="setDocumentAction('VO')"> <span class="tf-icon ti ti-hand-stop ti-xs me-1 color-inherit"></span>Stornieren</button>
          <button v-if="form.docStatusId === 'VO'" type="button" class="button color-backgr-red">Auftrag ist Storniert</button>
          <button title="Auftrag schon versand. Stornierung im System nicht möglich" v-if="inouts[0]?.TrackingNo && form.docStatusId !== 'VO'" type="button" class="button color-backgr-red"> <span class="tf-icon ti ti-exclamation-mark ti-xs me-1 color-inherit"></span>Stornieren nicht möglich</button>
<!--          <UModal-->
<!--              title="Stornieren nicht möglich"-->
<!--              description="Eine Stornierung ist nicht mehr möglich, da der Auftrag schon versandt wurde."-->
<!--              :close="{-->
<!--      color: 'error',-->
<!--      class: 'rounded-full'-->
<!--    }"-->
<!--          >-->
<!--            <UButton label="Stornieren" icon="i-circle-stop" size="md" color="error" />-->
<!--            <template #body>-->
<!--              <Placeholder class="h-48" />-->
<!--            </template>-->
<!--          </UModal>-->
        </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"> <!-- @mouseleave.stop="submit('onlysave')" -->
        <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 v-if="defaultSideBarMenu !== 'c'" class="fw-bold mt-2 mb-2"><span class="tf-icon ti ti-truck-loading ti-xs me-1 color-inherit"></span> {{ getLang['shipment'] }}</h3>

            <p v-if="defaultSideBarMenu !== 'c'" 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>
            <br>
            <h3 v-if="defaultSideBarMenu !== 'c'" class="fw-bold mb-2"><span class="tf-icon ti ti-file-dollar ti-xs me-1 color-inherit"></span>{{ getLang['invoice'] }}</h3>
            <p v-if="defaultSideBarMenu !== 'c'" 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>
            <br v-if="defaultSideBarMenu !== 'c'">
            <!-- Order Timeline -->
            <h3 class="fw-bold mb-2 mt-4"><span class="tf-icon ti ti-timeline ti-xs me-1 color-inherit"></span>Status</h3>
            <div class="order-timeline">
              <div
                  v-for="(step, index) in timelineSteps"
                  :key="step.key"
                  class="timeline-step"
                  :class="{
                  'completed': step.completed,
                  'timeline-step-canceled': step.type === 'canceled'
                }"
              >
                <div
                    class="timeline-marker"
                    :class="{
                    'active': step.active,
                    'timeline-marker-canceled': step.type === 'canceled'
                  }"
                >
                  <span class="tf-icon" :class="`ti ${step.icon}`"></span>
                </div>
                <div class="timeline-content">
                  <h4>{{ step.title }}</h4>
                  <p class="timeline-date" v-if="step.key === 'created'">
                    {{ date.format(new Date(step.date).getTime() - 7200000, 'DD.MM.YYYY', 'de-DE').slice(0, -3) }}
                  </p>
                  <p class="timeline-date" v-else-if="step.key === 'shipped'">
                    {{ getShippingDateWithRandomMinutes(step.date).slice(0, -3) }}
                  </p>
                  <p class="timeline-date" v-else-if="step.date">
                    {{ date.format(new Date(step.date).getTime() - 7200000, 'DD.MM.YYYY HH:mm', 'de-DE').slice(0, -3) }}
                  </p>

                  <!-- Special content for shipped step -->
                  <template v-if="step.key === 'shipped'">
                    <p>
                      <div v-if="form.inouts[0]?.TrackingNo" class="wrappersmallogo d-flex align-items-center">
                        <div class="freightname">Frachtdienstleister:</div>
                        <span v-if="form.shipper == 'DHL' &&  form.inouts[0]?.TrackingNo"> DHL</span>
                        <span v-if="form.shipper == 'DPD' &&  form.inouts[0]?.TrackingNo"> DPD</span>
                        <span v-if="form.shipperId == '1000002' &&  form.inouts[0]?.TrackingNo"> GEL Express</span>
                        <span v-if="form.shipperId == '1000005' &&  form.inouts[0]?.TrackingNo"> Cargo International</span>
                        <span v-if="form.shipperId == '1000006' &&  form.inouts[0]?.TrackingNo"> DHL Express</span>
                        <div class="freighticon">
                          <img title="DHL" class="smalllogo1 ms-2" alt="props?.params?.data?.shipper" v-if="form.shipper == 'DHL' &&  form.inouts[0]?.TrackingNo" src="/public/assets/shipper/dhl_logo_small.svg">
                          <img title="DPD" class="smalllogo2 ms-2" alt="props?.params?.data?.shipper" v-if="form.shipper == 'DPD' &&  form.inouts[0]?.TrackingNo" src="/public/assets/shipper/dpd_logo_small.png">
                          <img title="Gel Express" class="smalllogo3 ms-2" alt="props?.params?.data?.shipper" v-if="form.shipperId == '1000002' &&  form.inouts[0]?.TrackingNo" src="/public/assets/shipper/gelexpress.png">
                          <img title="Cargo International" class="smalllogo3 ms-2" alt="props?.params?.data?.shipper" v-if="form.shipperId == '1000005' &&  form.inouts[0]?.TrackingNo" src="/public/assets/shipper/cargo_logo_small.png">
                          <img title="DHL Express" class="smalllogo3 ms-2" alt="props?.params?.data?.shipper" v-if="form.shipperId == '1000006' &&  form.inouts[0]?.TrackingNo" src="/public/assets/shipper/dhlexpress.png">
                        </div>
                      </div>
                    </p>
                    <p class="tracking-info" v-if="form.inouts && form.inouts.length > 0 && form.inouts[0].TrackingNo && form.inouts[0].TrackingNo.trim() !== ''">
                      Tracking:
                      <a v-if="form.inouts[0]?.TrackingNo && form.shipper == 'DHL'" target="_blank" :href="'https://www.dhl.de/de/privatkunden/pakete-empfangen/verfolgen.html?idc='+form.inouts[0]?.TrackingNo">{{form.inouts[0]?.TrackingNo}}<span style="font-size: 14px !important; padding-bottom: 1px;" class="tf-icon ti ti-external-link ti-xs me-1 color-inherit"></span></a>
                      <a v-if="form.inouts[0]?.TrackingNo && form.shipperId == '1000005'" target="_blank" :href="'https://www.cargointernational.de/sendungsverfolgung/tracking/'+form.inouts[0]?.TrackingNo">{{form.inouts[0]?.TrackingNo}}<span style="font-size: 14px !important; padding-bottom: 1px;" class="tf-icon ti ti-external-link ti-xs me-1 color-inherit"></span></a>
                      <a v-if="form.inouts[0]?.TrackingNo && form.shipperId == '1000002'" target="_blank">{{form.inouts[0]?.TrackingNo}}</a>
                      <a v-if="form.inouts[0]?.TrackingNo && form.shipperId == '1000006'" target="_blank" :href="'http://www.dhl.de/de/express/sendungsverfolgung/express-suchergebnisse.html?lang=de&searchType=tracking&trackingEngine=international&AWB='+form.inouts[0]?.TrackingNo">{{form.inouts[0]?.TrackingNo}}<span style="font-size: 14px !important; padding-bottom: 1px;" class="tf-icon ti ti-external-link ti-xs me-1 color-inherit"></span></a>
                      <button type="button" class="button trackingcopy"
                              @click="copyTrackingNumber">
                        <span class="tf-icon ti ti-copy ti-xs me-1 color-inherit"></span></button>
                    </p>
                  </template>
                </div>
              </div>
            </div>

<!--            <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>-->
<!--                  &lt;!&ndash;                  <div  v-else class="timeline-item" v-for="(entry, index) in data" :key="index">&ndash;&gt;-->
<!--                  &lt;!&ndash;                    <div class="timeline-marker"></div>&ndash;&gt;-->
<!--                  &lt;!&ndash;                    <div class="timeline-content">&ndash;&gt;-->
<!--                  &lt;!&ndash;                      <div class="card">&ndash;&gt;-->
<!--                  &lt;!&ndash;                        <header class="card-header">&ndash;&gt;-->
<!--                  &lt;!&ndash;                          <p class="card-header-title">{{ entry.Updated }}</p>&ndash;&gt;-->
<!--                  &lt;!&ndash;                          <button class="card-header-icon" aria-label="more options">&ndash;&gt;-->
<!--                  &lt;!&ndash;                            <span class="icon">&ndash;&gt;-->
<!--                  &lt;!&ndash;                              <i class="fas fa-angle-down" aria-hidden="true"></i>&ndash;&gt;-->
<!--                  &lt;!&ndash;                            </span>&ndash;&gt;-->
<!--                  &lt;!&ndash;                          </button>&ndash;&gt;-->
<!--                  &lt;!&ndash;                        </header>&ndash;&gt;-->
<!--                  &lt;!&ndash;                        <div class="card-content">&ndash;&gt;-->
<!--                  &lt;!&ndash;                          <div class="content">&ndash;&gt;-->
<!--                  &lt;!&ndash;                            <span>&ndash;&gt;-->
<!--                  &lt;!&ndash;                            <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">&ndash;&gt;-->
<!--                  &lt;!&ndash;                              <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" />&ndash;&gt;-->
<!--                  &lt;!&ndash;                            </svg>&ndash;&gt;-->
<!--                  &lt;!&ndash;                            <span  class="personchanged">{{ entry.UpdatedBy.identifier }}</span>&ndash;&gt;-->
<!--                  &lt;!&ndash;                              </span>&ndash;&gt;-->
<!--                  &lt;!&ndash;                            changed:&ndash;&gt;-->
<!--                  &lt;!&ndash;                          </div>&ndash;&gt;-->
<!--                  &lt;!&ndash;                        </div>&ndash;&gt;-->
<!--                  &lt;!&ndash;                        <footer class="card-footer">&ndash;&gt;-->
<!--                  &lt;!&ndash;                          <a href="#" class="card-footer-item">{{ entry.AD_Column_ID.identifier }}</a>&ndash;&gt;-->
<!--                  &lt;!&ndash;                        </footer>&ndash;&gt;-->
<!--                  &lt;!&ndash;                        <footer class="card-footer">&ndash;&gt;-->
<!--                  &lt;!&ndash;                          <a href="#" class="card-footer-item">{{ entry.OldValue }}</a>&ndash;&gt;-->
<!--                  &lt;!&ndash;                          <div class="is-divider-vertical" data-content="&ndash;&gt;"></div>&ndash;&gt;-->
<!--                  &lt;!&ndash;                          <a href="#" class="card-footer-item">{{ entry.NewValue }}</a>&ndash;&gt;-->
<!--                  &lt;!&ndash;                        </footer>&ndash;&gt;-->
<!--                  &lt;!&ndash;                      </div>&ndash;&gt;-->
<!--                  &lt;!&ndash;                    </div>&ndash;&gt;-->
<!--                  &lt;!&ndash;                  </div>&ndash;&gt;-->


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

<!--              </div>-->
<!--            </USlideover>-->
          </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;
}

.color-backgr-red {
  background-color: red;
}

button.color-backgr-red.button:hover {
  background-color: #FF4D29;
}

/* Timeline Styles */
.order-timeline {
  position: relative;
  padding-left: 0;
  margin-top: 1rem;
}

.timeline-step {
  position: relative;
  padding-left: 3rem;
  padding-bottom: 1.5rem;
  opacity: 0.5;
  transition: opacity 0.3s ease;
}

.timeline-step.completed {
  opacity: 1;
}

.timeline-step:not(:last-child)::before {
  content: '';
  position: absolute;
  left: 1.125rem;
  top: 2.5rem;
  width: 2px;
  height: calc(100% - 1rem);
  background-color: #e0e0e0;
  transition: background-color 0.3s ease;
}

.timeline-step.completed:not(:last-child)::before {
  background-color: #22c55e;
}

.timeline-marker {
  position: absolute;
  left: 0;
  top: 0;
  width: 2.25rem;
  height: 2.25rem;
  border-radius: 50%;
  background-color: #f3f4f6;
  border: 2px solid #e5e7eb;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.timeline-marker.active {
  background-color: #22c55e;
  border-color: #22c55e;
  color: white;
}

.timeline-marker .tf-icon {
  font-size: 1rem;
}

.timeline-content h4 {
  margin: 0 0 0.25rem 0;
  font-size: 0.875rem;
  font-weight: 600;
  color: #374151;
}

.timeline-step.completed .timeline-content h4 {
  color: #111827;
}

.timeline-date {
  margin: 0;
  font-size: 0.75rem;
  color: #6b7280;
}

.timeline-step.completed .timeline-date {
  color: #374151;
}

.tracking-info {
  margin: 0.25rem 0 0 0;
  font-size: 0.75rem;
  color: #059669;
  font-weight: 500;
}

/* Canceled timeline styles */
.timeline-step-canceled {
  opacity: 1;
}

.timeline-step-canceled:not(:last-child)::before {
  background-color: #e0e0e0 !important;
}

.timeline-marker-canceled {
  background-color: #dc2626 !important;
  border-color: #dc2626 !important;
  color: white !important;
}

.timeline-step-canceled .timeline-content h4 {
  color: #dc2626;
}

.timeline-step-canceled .timeline-date {
  color: #dc2626;
}

.wrappersmallogo {
}

.smalllogo1 {
  width: 28%;
  margin-top: 3px;
}

.smalllogo2 {
  width: 5%;
  margin-top: -4px;
  height: 14%;
}

.smalllogo3 {
  width: 12%;
  margin-top: -9px;
}

button.button.trackingcopy {
  height: 19px;
}

.hasBadge {
  position: relative;
}
.badgeAttachment {
  position: absolute;
  right: -7px;
  top: -17px;
  background-color: #f23c34;
  color: #fff;
  min-width: 30px;
  padding: 0.25rem;
  border-radius: 50%;
  font-size: 10pt;
}
</style>