<script setup>
import { string } from 'alga-js'
const config = useRuntimeConfig()
const route = useRoute()

const trackingNo = ref(route.query?.no ?? '')
const trackingShipment = ref({})
const trackingContents = ref([])
const trackingInfo = ref({
  no: '',
  zip: '',
  active: true
})
const trackingNoHandler = async (info = '') => {
  if ((trackingNo.value || route.query?.no || '') !== '') {
    const res = await $fetch(`/api/commission/trackings/${trackingNo.value || route.query?.no || '-'}/shipment`, {
      headers: useRequestHeaders(['cookie']) //startswith(MovementType,'C') AND xxxx AND (DocStatus neq 'VO' AND DocStatus neq 'DR')
    })
    if (Number(res.records.length) === 1) {
      trackingShipment.value = res.records[0]
    } else {
      trackingShipment.value = res.records.filter(i => i.m_inoutline.length >= 1)?.[0] ?? {}
    }

    if (info !== '') {
      if (trackingShipment.value?.C_BPartner_Location_ID?.C_Location_ID?.Postal !== info && !(trackingShipment.value?.C_BPartner_Location_ID?.C_Location_ID?.Address1 ?? '').includes(info)) {
        trackingNo.value = ''
        alert('Please enter the correct Postal code or house number')
      }
    }
    //console.log(trackingShipment.value)

    try {
      const resp = await $fetch(`/api/commission/trackings/tracking?no=${trackingNo.value}&service=${route.query?.service ?? trackingShipment.value?.shipping_service_name ?? trackingShipment.value?.M_Shipper_ID?.Name ?? trackingShipment.value?.C_Order_ID?.M_Shipper_ID?.Name ?? 'dhl'}&inout_id=${trackingShipment.value?.id ?? ''}`, {
        headers: useRequestHeaders(['cookie'])
      })
      if (resp?.tracking_content) {
        trackingContents.value = resp?.tracking_content
        //console.log(trackingContents.value)
      } else {
        //console.log(res)
        console.log(resp)
      }
    } catch (error) {
      console.log(error)
    }

    trackingInfo.value.active = true
  }
}

onMounted(() => {
  if (route.query?.no) {
    trackingNo.value = route.query.no
    trackingNoHandler()
  }
})

watch(() => route.query, () => {
  if (route.query?.no) {
    trackingNo.value = route.query.no
    trackingNoHandler()
  }
})

const trackingInfoHandler = () => {
  if (trackingInfo.value.no && trackingInfo.value.zip) {
    trackingInfo.value.active = false
    trackingNo.value = trackingInfo.value.no
    trackingNoHandler(trackingInfo.value.zip)
  } else {
    alert('Please enter both inputs')
  }
}
</script>

<template>
  <NuxtLayout name="tracking">
    <section class="section py-0.75rem">
      <div class="d-grid placeItems-center w-100pct my-0.75rem">
        <img src="~/assets/logyou-logo.jpg" alt="LogYou GmBH" />
      </div>
      <template v-if="trackingNo && trackingInfo.active">
        <div class="card my-0.75rem">
          <div class="card-content">
            <div class="columns is-desktop">
              <div class="column is-half">
                <p>
                  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"  stroke-linejoin="round" class="mr-2 icon icon-tabler icons-tabler-outline icon-tabler-map-pin"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M9 11a3 3 0 1 0 6 0a3 3 0 0 0 -6 0" /><path d="M17.657 16.657l-4.243 4.243a2 2 0 0 1 -2.827 0l-4.244 -4.243a8 8 0 1 1 11.314 0z" /></svg>
                  <strong>Delivery address</strong>
                </p>
                <p>{{ trackingShipment?.C_BPartner_ID?.identifier ?? '' }}</p>
                <p>{{ trackingShipment?.M_Shipper_ID?.Name ?? '' }}</p>
                <p>{{ trackingShipment?.C_BPartner_Location_ID?.C_Location_ID?.Address1 ?? '' }}</p>
                <p v-if="trackingShipment?.C_BPartner_Location_ID?.C_Location_ID?.Address2">{{ trackingShipment?.C_BPartner_Location_ID?.C_Location_ID?.Address2 ?? '' }}</p>
                <p v-if="trackingShipment?.C_BPartner_Location_ID?.C_Location_ID?.CountryState">{{ trackingShipment?.C_BPartner_Location_ID?.C_Location_ID?.CountryState ?? '' }}</p>
                <p>{{ trackingShipment?.C_BPartner_Location_ID?.C_Location_ID?.C_Country_ID?.identifier ?? '' }}</p>
                <p>{{ trackingShipment?.C_BPartner_Location_ID?.C_Location_ID?.Postal ?? '' }}</p>
              </div>
              <div class="column is-half">
                <p>
                  <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"  fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"  stroke-linejoin="round"  class="mr-2 icon icon-tabler icons-tabler-outline icon-tabler-truck-delivery"><path stroke="none" d="M0 0h24v24H0z" fill="none"/><path d="M7 17m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0" /><path d="M17 17m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0" /><path d="M5 17h-2v-4m-1 -8h11v12m-4 0h6m4 0h2v-6h-8m0 -5h5l3 5" /><path d="M3 9l4 0" /></svg>
                  <strong>Tracking</strong>
                  <p>{{ trackingShipment?.shipping_service_name?.toUpperCase() ?? 'DHL' }}: {{ trackingShipment?.TrackingNo ?? trackingNo ?? '' }}</p>
                </p>
              </div>
            </div>
          </div>
        </div>
        <div class="card my-0.75rem">
          <div class="card-content">

            <table class="table tableList tableFlush m-0.75rem">
              <thead>
                <tr>
                  <th>No</th>
                  <th>Description</th>
                  <th>Quantity</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item, index) in (trackingShipment?.m_inoutline ?? [])" :key="index">
                  <td>{{ Number(index) + 1 }}</td>
                  <td>{{ item.M_Product_ID.Name }}</td>
                  <td>{{ item.QtyEntered }} {{ item?.C_UOM_ID?.identifier ?? item.M_Product_ID?.C_UOM_ID?.identifier ?? '' }}</td>
                </tr>
              </tbody>
            </table>

          </div>
        </div>
        <div class="card my-0.75rem">
          <div class="card-content">

            <div class="timeline">
              <div v-for="(trackingContent, index) in trackingContents" :key="index" class="timelineWrapper">
                <div class="timelineContent">
                  <h2>{{ trackingContent.timestamp }} {{ trackingContent.status }}</h2>
                  <p>{{ trackingContent.description || trackingContent.title }}</p>
                </div>
              </div>
              <!--<div class="timelineWrapper">
                <div class="timelineContent">
                  <h2>2016</h2>
                  <p>Lorem ipsum dolor sit amet, quo ei simul congue exerci, ad nec admodum perfecto mnesarchum, vim ea mazim fierent detracto. Ea quis iuvaret expetendis his, te elit voluptua dignissim per, habeo iusto primis ea eam.</p>
                </div>
              </div>
              <div class="timelineWrapper">
                <div class="timelineContent">
                  <h2>2015</h2>
                  <p>Lorem ipsum dolor sit amet, quo ei simul congue exerci, ad nec admodum perfecto mnesarchum, vim ea mazim fierent detracto. Ea quis iuvaret expetendis his, te elit voluptua dignissim per, habeo iusto primis ea eam.</p>
                </div>
              </div>
              <div class="timelineWrapper">
                <div class="timelineContent">
                  <h2>2012</h2>
                  <p>Lorem ipsum dolor sit amet, quo ei simul congue exerci, ad nec admodum perfecto mnesarchum, vim ea mazim fierent detracto. Ea quis iuvaret expetendis his, te elit voluptua dignissim per, habeo iusto primis ea eam.</p>
                </div>
              </div>
              <div class="timelineWrapper">
                <div class="timelineContent">
                  <h2>2011</h2>
                  <p>Lorem ipsum dolor sit amet, quo ei simul congue exerci, ad nec admodum perfecto mnesarchum, vim ea mazim fierent detracto. Ea quis iuvaret expetendis his, te elit voluptua dignissim per, habeo iusto primis ea eam.</p>
                </div>
              </div>
              <div class="timelineWrapper">
                <div class="timelineContent">
                  <h2>2007</h2>
                  <p>Lorem ipsum dolor sit amet, quo ei simul congue exerci, ad nec admodum perfecto mnesarchum, vim ea mazim fierent detracto. Ea quis iuvaret expetendis his, te elit voluptua dignissim per, habeo iusto primis ea eam.</p>
                </div>
              </div>-->
            </div>

          </div>
        </div>
      </template>
      <div v-else class="columns is-desktop">
        <div class="column is-one-third"></div>
        <div class="column is-one-third">
          <div class="card my-0.75rem">
            <div class="card-content">
              <p class="mb-2">
                <label class="label">Tracking code</label>
                <input type="text" v-model="trackingInfo.no" class="input" placeholder="JDI2345623456" />
              </p>
              <p class="mb-2">
                <label class="label">Postal code or house number</label>
                <input type="text" v-model="trackingInfo.zip" class="input" placeholder="5642VV" />
                <span><i>If your country doesn't have postal codes then fill in your house number.</i></span>
              </p>
              <p>
                <button type="button" class="button" @click="trackingInfoHandler">Process</button>
              </p>
            </div>
          </div>
        </div>
        <div class="column is-one-third"></div>
      </div>
    </section>
  </NuxtLayout>
</template>

<style scoped>
@ref d-grid placeItems-center py-0.75rem my-0.75rem mr-2;

/* The actual timeline (the vertical ruler) */
.timeline {
  position: relative;
  max-width: 1200px;
  margin: 0 auto;
}

/* The actual timeline (the vertical ruler) */
.timeline::after {
  content: '';
  position: absolute;
  width: 6px;
  background-color: #192e47;
  top: 0;
  bottom: 0;
  left: -80px;
  margin-left: -3px;
}

/* Container around content */
.timelineWrapper {
  padding: 10px 40px;
  position: relative;
  background-color: inherit;
  width: 100%;
  left: -78px;
}

/* The circles on the timeline */
.timelineWrapper::after {
  content: '';
  position: absolute;
  width: 25px;
  height: 25px;
  right: -17px;
  background-color: white;
  border: 4px solid #eb531e;
  top: 15px;
  border-radius: 50%;
  z-index: 1;
  left: -16px;
}

/* Add arrows to the right container (pointing left) */
.timelineWrapper::before {
  content: " ";
  height: 0;
  position: absolute;
  top: 22px;
  width: 0;
  z-index: 1;
  left: 30px;
  border: medium solid white;
  border-width: 10px 10px 10px 0;
  border-color: transparent white transparent transparent;
}

/* The actual content */
.timelineContent {
  padding: 20px 30px;
  background-color: white;
  position: relative;
  border-radius: 6px;
}

/* Media queries - Responsive timeline on screens less than 600px wide */
@media screen and (max-width: 600px) {
  /* Place the timelime to the left */
  .timeline::after {
    left: 31px;
  }
  
  /* Full-width containers */
  .timelineWrapper {
    width: 100%;
    padding-left: 70px;
    padding-right: 25px;
    left: 0%;
  }
  
  /* Make sure that all arrows are pointing leftwards */
  .timelineWrapper::before {
    left: 60px;
    border: medium solid white;
    border-width: 10px 10px 10px 0;
    border-color: transparent white transparent transparent;
  }

  /* Make sure all circles are at the same spot */
  .timelineWrapper::after {
    left: 15px;
  }
  
}
</style>