<script setup>
import { date, string } from 'alga-js'
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 generateShipmentActive = useGenerateShipmentActive()

const props = defineProps({
  params: Object
})

// Use the centralized role menu composable
const { getMenuType } = useRoleMenu()

// Use a computed property that will be reactive
const isFulCustomer = computed(() => getMenuType())

const setDocumentAction = async (docAction) => {
  const confirmation = confirm('Möchten sie diesen Auftrag stornieren?')
  if (confirmation) {
    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
        })
      }
    }
  }
}

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 = async () => {
  generateShipments.value = {
    warehouse: props.params.data.warehouse,
    warehouseId: props.params.data.warehouseId,
    partner: props.params.data.partner,
    partnerId: props.params.data.partnerId
  }
  generateShipmentActive.value = true
  /*openTab('/generate-shipments', 'Generate Shipments')*/

  /*const res = await $fetch('/api/processes/inouts/generate', {
    method: 'POST',
    headers: useRequestHeaders(['cookie']),
    body: {
      warehouseId: props.params.data.warehouseId,
      dateAcct: date.now('date'),
      partnerId: props.params.data.partnerId,
      datePromised: date.now('date'),
      docStatusId: 'CO',
      isUnconfirmed: false,
      isOneDocument: false,
      inProgress: false,
      isRunJob: false,
    }
  })

  if(Number(res.status) === 200) {
    toast({
      message: `Shipment has been generated from sales order`,
      type: 'is-success',
      duration: 2000
    })
  }*/
}
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 shipment = ref({})
const getShipment = async () => {
  if(props.params.data.id) {
    const res = await $fetch(`/api/inouts/${props.params.data.id}/order`)
    if(res) {
      shipment.value = res
    }
  }
}
onMounted(getShipment)
watch(() => props.params, getShipment)

 // console.log(props.params.data)
</script>

<template>
  <div class="d-inlineFlex items-center gap-5px">
<!--    <span class="tf-icon ti ti-eye ti-sm me-1 fg-info cursor-pointer" @click="viewHandler" title="View"></span>-->
    <span v-if="isFulCustomer !== 'c'" class="tf-icon ti ti-file-invoice ti-sm me-1 fg-primary cursor-pointer" @click="printHandler" title="Print"></span>
<!--    <span class="tf-icon ti ti-copy ti-sm me-1 fg-info cursor-pointer" @click="duplicateHandler" title="Duplicate"></span>-->
<!--    <span>{{props.params.data?.minout?.TrackingNo}}</span>-->
    <span v-if="params?.data?.docStatusId !== 'CO' && params?.data?.docStatusId !== 'VO'" class="tf-icon ti ti-pencil ti-sm me-1 fg-warning cursor-pointer" @click="editHandler" title="Edit"></span>
<!--    <span v-else class="tf-icon ti ti-forms ti-sm me-1 fg-warning cursor-pointer" @click="editHandler" title="Open"></span>-->
<!--    <span v-if="params.data.docStatusId === 'CO' && checkNumberInStreet && !props.params.data?.minout[0]?.TrackingNo" class="tf-icon ti ti-truck ti-sm me-1 fg-primary cursor-pointer" @click="generateShipmentHandler" title="Generate Shipments"></span>-->
    <span v-if="isFulCustomer !== 'c' && !shipment?.TrackingNo" class="tf-icon ti ti-truck ti-sm me-1 fg-primary cursor-pointer" @click="generateShipmentHandler" title="Generate Shipments"></span>
    <span v-if="params?.data?.docStatusId !== 'CO' && params?.data?.docStatusId !== 'VO'" class="tf-icon ti ti-trash ti-sm me-1 fg-danger cursor-pointer" @click="deleteHandler" title="Delete"></span>
<!--    <span>{{ params.data.documentNo }}</span>-->
    <span v-if="params?.data?.docStatusId !== 'VO' && !shipment?.TrackingNo" class="tf-icon ti ti-hand-stop ti-sm me-1 fg-danger cursor-pointer"  @click="setDocumentAction('VO')" title="Stornieren"></span>


  </div>
</template>