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

const router = useRouter()
const tabs = useTabs()
const printPreview = usePrintPreview()
const printParam = usePrintParam()
const quickView = useQuickView()
const quickViewParam = useQuickViewParam()
const generateShipments = useGenerateShipments()

const props = defineProps({
  params: Object
})

const removeQueryFromPath = (path) => {
  let newPath = path
  if(path.includes('?')) {
    const splittedPath = path.split('?')
    newPath = splittedPath[0]
  }
  return newPath
}

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 === removeQueryFromPath(comparePath)).length >= 1) {
    const tabIndex = tabs.value.findIndex(i => i.link === removeQueryFromPath(comparePath))
    tabs.value[tabIndex].active = true
    if(oldPath) {
      tabs.value[tabIndex].link = removeQueryFromPath(toPath)
      tabs.value[tabIndex].text = pathName
    }
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  } else {
    tabs.value.push({link: removeQueryFromPath(toPath), text: pathName, active: true})
    localStorage.setItem('tabs', JSON.stringify(tabs.value))
    router.push(toPath)
  }
  //location.href = toPath
}

const viewHandler = () => {
  //router.push(`/sales/orders/${props.params.data.id}/view`)
  //replaceActiveTabUrl(`/sales/orders/${props.params.data.id}/view`)
  quickView.value = 'order'
  quickViewParam.value = props.params.data
}
const duplicateHandler = () => {
  //router.push(`/sales/orders/${props.params.data.id}/duplicate`)
  openTab(`/duplicate/sales-order-${props.params.data.id}`, `Sales Order: Duplicate`)
}
const printHandler = () => {
  //router.push(`/sales/orders/${props.params.data.id}/print`)
  printParam.value = props.params.data
  printPreview.value = true
}
const generateShipmentHandler = () => {
  generateShipments.value = {
    warehouse: props.params.data.warehouse,
    warehouseId: props.params.data.warehouseId,
    partner: props.params.data.partner,
    partnerId: props.params.data.partnerId
  }
  openTab('/generate-shipments', 'Generate Shipments')
}
const editHandler = () => {
  //router.push(`/sales/orders/${props.params.data.id}/edit`)
  openTab(`/edit/sales-order-${props.params.data.id}`, `Sales Order: ${props.params.data.documentNo}`)
}
const deleteHandler = async () => {
  const confirmation = confirm('Are you sure want to delete this record?')
  if(confirmation) {
    await $fetch('/api/orders/'+props.params.data.id, {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
    location.reload()
  }
}

const checkNumberInStreet = computed(() => {
  let numStreet = true
  if(props.params.data?.locationStreet) {
    const match = props.params.data.locationStreet.match(/(\d+[a-zA-Z]*.*)$/)
    numStreet = match ? true : false
  }
  return numStreet
})

const setDocumentAction = async (docAction) => {
  if(props.params.data?.id) {
    const res = await $fetch('/api/orders/'+props.params.data.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
      })
      location.reload()
    } else {
      toast({
        message: 'Document failed to set to '+docAction+' status.',
        type: 'is-danger',
        duration: 2000
      })
    }
  }
}
</script>

<template>
  <div class="p-1.5rem overflowY-auto h-100pct">
    <div class="columns mb-3">
      <div class="column is-full mb-3">
        <div class="d-flex justify-flexEnd gap-5px mb-3">
<!--          <button type="button" class="button" @click="viewHandler">More</button>-->
<!--          <button type="button" class="button" @click="printHandler">Print Preview</button>-->
<!--          <button v-if="props.params.data.docStatusId !== 'VO'" type="button" class="button" @click="setDocumentAction('VO')">Void</button>-->
        </div>
        <SalesOrderDetailRecord action="view" :info="params.data" tab="order_line" />
      </div>
    </div>
  </div>
</template>

<style scoped>
@ref fs-28pt fs-18pt fw-bold justify-center mb-4;
</style>