<script setup>
import { date } from 'alga-js'
const router = useRouter()
const route = useRoute()

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

const form = ref({
  id: '',
  client: '',
  clientId: '',
  organization: '',
  organizationId: '',
  isActive: true,
  documentNo: '',
  description: '',
  isApproved: false,
  processed: false,
  isSOTrx: true,
  isPrinted: false,
  dateAcct: date.now('date'),
  poReference: '',
  freightAmt: 0,
  chargeAmt: 0,
  dateOrdered: date.now('date'),
  sendEMail: false,
  noPackages: 0,
  isInTransit: false,
  isInDispute: false,
  volume: 0,
  weight: 0,
  isDropShip: false,
  processedOn: 0,
  isAlternateReturnAddress: false,
  movementType: 'Customer Returns',
  movementTypeId: 'C+',
  docType: '',
  docTypeId: '',
  partner: '',
  partnerId: '',
  partnerLocation: '',
  partnerLocationId: '',
  user: '',
  userId: '',
  dropShipPartner: '',
  dropShipPartnerId: '',
  dropShipPartnerLocation: '',
  dropShipPartnerLocationId: '',
  dropShipUser: '',
  dropShipUserId: '',
  returnPartner: '',
  returnPartnerId: '',
  returnPartnerLocation: '',
  returnPartnerLocationId: '',
  returnUser: '',
  returnUserId: '',
  warehouse: '',
  warehouseId: '',
  deliveryRule: '',
  deliveryRuleId: '',
  freightCostRule: '',
  freightCostRuleId: '',
  deliveryViaRule: '',
  deliveryViaRuleId: '',
  priorityRule: '',
  priorityRuleId: '',
  order: '',
  orderId: '',
  docStatus: 'Draft',
  docStatusId: 'DR',
  salesRep: '',
  salesRepId: '',
  project: '',
  projectId: '',
  campaign: '',
  campaignId: '',
  processing: false,
  alert: {
    status: '',
    message: '',
    processing: false,
  }
})

const retrieve = async () => {
  const res = await $fetch('/api/inouts/'+route.params.id, {
    headers: useRequestHeaders(['cookie'])
  })
  if(res) {
    form.value = {
      id: 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 || '',
      isActive: res?.IsActive ?? true,
      documentNo: res?.DocumentNo || '',
      description: res?.Description || '',
      isApproved: res?.IsApproved ?? false,
      processed: res?.Processed ?? false,
      isSOTrx: true,
      isPrinted: res?.IsPrinted ?? false,
      dateAcct: res?.DateAcct || date.now('date'),
      poReference: res?.POReference || '',
      freightAmt: res?.FreightAmt || 0,
      chargeAmt: res?.ChargeAmt || 0,
      dateOrdered: res?.DateOrdered || date.now('date'),
      sendEMail: res?.SendEMail ?? false,
      noPackages: res?.NoPackages || 0,
      isInTransit: res?.IsInTransit ?? false,
      isInDispute: res?.IsInDispute ?? false,
      volume: res?.Volume || 0,
      weight: res?.Weight || 0,
      isDropShip: res?.IsDropShip ?? false,
      processedOn: res?.ProcessedOn || 0,
      isAlternateReturnAddress: res?.IsAlternateReturnAddress ?? false,
      movementType: res?.MovementType?.identifier || 'Customer Returns',
      movementTypeId: res?.MovementType?.id || 'C+',
      docType: res?.C_DocType_ID?.identifier || '',
      docTypeId: res?.C_DocType_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 || '',
      user: res?.AD_User_ID?.identifier || '',
      userId: res?.AD_User_ID?.id || '',
      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 || '',
      returnPartner: res?.Return_BPartner_ID?.identifier || '',
      returnPartnerId: res?.Return_BPartner_ID?.id || '',
      returnPartnerLocation: res?.Return_Location_ID?.identifier || '',
      returnPartnerLocationId: res?.Return_Location_ID?.id || '',
      returnUser: res?.Return_User_ID?.identifier || '',
      returnUserId: res?.Return_User_ID?.id || '',
      warehouse: res?.M_Warehouse_ID?.identifier || '',
      warehouseId: res?.M_Warehouse_ID?.id || '',
      deliveryRule: res?.DeliveryRule?.identifier || '',
      deliveryRuleId: res?.DeliveryRule?.id || '',
      freightCostRule: res?.FreightCostRule?.identifier || '',
      freightCostRuleId: res?.FreightCostRule?.id || '',
      deliveryViaRule: res?.DeliveryViaRule?.identifier || '',
      deliveryViaRuleId: res?.DeliveryViaRule?.id || '',
      priorityRule: res?.PriorityRule?.identifier || '',
      priorityRuleId: res?.PriorityRule?.id || '',
      order: res?.C_Order_ID?.identifier || '',
      orderId: res?.C_Order_ID?.id || '',
      docStatus: res?.DocStatus?.identifier || 'Draft',
      docStatusId: res?.DocStatus?.id || 'DR',
      salesRep: res?.SalesRep_ID?.identifier || '',
      salesRepId: res?.SalesRep_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 || '',
      processing: false,
      alert: {
        status: '',
        message: '',
        processing: false
      }
    }
  }
}
onMounted(retrieve)

const printReport = async (fileType) => {
  const response = await $fetch('/api/inouts/'+route.params.id+'/print/'+fileType, {
    headers: useRequestHeaders(['cookie'])
  })
  if(response) {
    let mimeType = ''
    let blob = new Blob([])
    if(fileType === 'PDF') {
      mimeType = 'application/pdf'
      const base64Response = await fetch(`data:${mimeType};base64,${response.reportFile}`);
      blob = await base64Response.blob();
    } else if(fileType === 'HTML') {
      mimeType = 'text/html'
      blob = new Blob([atob(response.exportFile)], {type: mimeType})
    } else if(fileType === 'CSV') {
      mimeType = 'text/csv'
      blob = new Blob([atob(response.exportFile)], {type: mimeType})
    } else if(fileType === 'XLSX') {
      mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
      blob = new Blob([atob(response.exportFile)], {type: mimeType})
    } else if(fileType === 'XLS') {
      mimeType = 'application/vnd.ms-excel'//data:application/octet-stream;base64
      blob = new Blob([atob(response.exportFile)], {type: mimeType})
    }
    const blobUrl = URL.createObjectURL(blob)
    open(blobUrl, '_blank')
  }
}

const back = () => {
  router.push('/sales/returns')
}
const print = () => {
  router.push('/sales/returns/'+route.params.id+'/print')
}
const edit = () => {
  router.push(`/sales/returns/${route.params.id}/edit`)
}
const destroy = async () => {
  const confirmation = confirm('Are you sure want to delete this record?')
  if(confirmation) {
    await $fetch('/api/inouts/'+route.params.id, {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
    router.push(`/sales/returns`)
  }
}

const dropDownHandler = (e) => {
  if(e.target.parentElement.classList.contains('show')) {
    e.target.parentElement.classList.remove('show')
  } else {
    e.target.parentElement.classList.add('show')
  }
}

const dropItemHandler = (e) => {
  if(e.target.parentElement.parentElement.classList.contains('show')) {
    e.target.parentElement.parentElement.classList.remove('show')
  } else {
    e.target.parentElement.parentElement.classList.add('show')
  }
}

const breadCrumb = computed(() => ([
  { link: '#', text: 'Sales'},
  { link: '/sales/returns', text: 'Customer Returns'},
  { link: '#', text: 'View Return Details', active: true}
]))
</script>

<template>
  <Head>
    <Title>View Return Details</Title>
  </Head>

  <NuxtLayout name="new-dash">
    <NewBreadCrumb :items="breadCrumb" />
    <div>
      <div class="banner">
        <div class="d-flex justify-between mb-3">
          <h4></h4>
          <div class="d-flex gap-0.75rem">
            <div>
              <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 class="dropDown">
              <button type="button" class="button dropDownToggler" @click="dropDownHandler">
                <span class="tf-icon ti ti-settings ti-xs me-1 color-inherit"></span> Action
              </button>
              <div class="dropDownBackdrop" @click="dropDownHandler"></div>
              <div class="dropDownMenu dropDownRight mnw-80px">
                <span class="dropDownItem" @click="dropItemHandler($event); edit();">Edit</span>
                <span class="dropDownItem" @click="dropItemHandler($event); destroy();">Delete</span>
              </div>
            </div>
            <div>
              <button type="button" @click="print" class="button">
                <span class="tf-icon ti ti-file-invoice ti-xs me-1 color-inherit"></span> Print Preview
              </button>
            </div>
            <div class="dropDown">
              <button type="button" class="button dropDownToggler" @click="dropDownHandler">
                <span class="tf-icon ti ti-file-export ti-xs me-1 color-inherit"></span> Print Report
              </button>
              <div class="dropDownBackdrop" @click="dropDownHandler"></div>
              <div class="dropDownMenu dropDownRight">
                <span class="dropDownItem" @click="dropItemHandler($event); printReport('PDF');">Print Report in PDF</span>
                <span class="dropDownItem" @click="dropItemHandler($event); printReport('HTML');">Print Report in HTML</span>
                <span class="dropDownItem" @click="dropItemHandler($event); printReport('CSV');">Print Report in CSV</span>
                <span class="dropDownItem" @click="dropItemHandler($event); printReport('XLSX');">Print Report in XLSX</span>
                <span class="dropDownItem" @click="dropItemHandler($event); printReport('XLS');">Print Report in XLS</span>
              </div>
            </div>
          </div>
        </div>
        <div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Tenant</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.client }}</div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Organization</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.organization }}</div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Order</strong>
                <strong>:</strong>
              </div>
              <div></div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Order Date</strong>
                <strong>:</strong>
              </div>
              <div></div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Document Number</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.documentNo }}</div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Order Reference</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.poReference }}</div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Movement Date</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.dateOrdered }}</div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Date Accounted</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.dateAcct }}</div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Business Partner</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.partner }}</div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Document Type</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.docType }}</div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Partner Location</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.partnerLocation }}</div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>User/Contact</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.user }}</div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Warehouse</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.warehouse }}</div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Delivery Rule</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.deliveryRule }}</div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Sales Rep</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.salesRep }}</div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Priority</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.priorityRule }}</div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Project</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.project }}</div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Campaign</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.campaign }}</div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Freight Cost Rule</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.freightCostRule }}</div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Freight Amount</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.freightAmt }}</div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Delivery Via</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.deliveryViaRule }}</div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Shipper</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.shipper }}</div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Drop Shipment Partner</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.dropShipPartner }}</div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Drop Shipment Location</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.dropShipPartnerLocation }}</div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Drop Shipment Contact</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.dropShipUser }}</div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Return Partner</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.returnPartner }}</div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Return Location</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.returnPartnerLocation }}</div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Return User/Contact</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.returnUser }}</div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Movement Type</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.movementType }}</div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Document Status</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.docStatus }}</div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Picked Date</strong>
                <strong>:</strong>
              </div>
              <div></div>
            </div>
            <div class="column is-half d-flex gap-10px">
              <div class="w-150px d-flex justify-between gap-10px">
                <strong>Date Received</strong>
                <strong>:</strong>
              </div>
              <div></div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-full d-flex gap-10px">
              <div class="w-150px d-inlineFlex justify-between gap-10px mb-2">
                <strong>Status</strong>
                <strong>:</strong>
              </div>
              <div class="d-flex flexWrap-wrap gap-10px">
                <div class="check">
                  <input type="checkbox" v-model="form.isActive" class="checkInput" id="isActive" :checked="form.isActive" disabled>
                  <label class="checkLabel" for="isActive">Active</label>
                </div>
                <div class="check">
                  <input type="checkbox" v-model="form.isApproved" class="checkInput" id="isApproved" :checked="form.isApproved" disabled>
                  <label class="checkLabel" for="isApproved">Approved</label>
                </div>
                <div class="check">
                  <input type="checkbox" v-model="form.processed" class="checkInput" id="processed" :checked="form.processed" disabled>
                  <label class="checkLabel" for="processed">Processed</label>
                </div>
                <div class="check">
                  <input type="checkbox" v-model="form.isInTransit" class="checkInput" id="isInTransit" :checked="form.isInTransit" disabled>
                  <label class="checkLabel" for="isInTransit">In Transit</label>
                </div>
                <div class="check">
                  <input type="checkbox" v-model="form.isInDispute" class="checkInput" id="isInDispute" :checked="form.isInDispute" disabled>
                  <label class="checkLabel" for="isInDispute">In Dispute</label>
                </div>
                <div class="check">
                  <input type="checkbox" v-model="form.isDropShip" class="checkInput" id="isDropShip" :checked="form.isDropShip" disabled>
                  <label class="checkLabel" for="isDropShip">Drop Shipment</label>
                </div>
                <div class="check">
                  <input type="checkbox" v-model="form.isAlternateReturnAddress" class="checkInput" id="isAlternateReturnAddress" :checked="form.isAlternateReturnAddress" disabled>
                  <label class="checkLabel" for="isAlternateReturnAddress">Alternate Return Address</label>
                </div>
              </div>
            </div>
          </div>
          <div class="columns is-desktop">
            <div class="column is-half">
              <div class="w-150px d-flex justify-between gap-10px mb-2">
                <strong>Description</strong>
                <strong>:</strong>
              </div>
              <div>{{ form.description }}</div>
            </div>
          </div>
          
          <div class="m-3">
            <div>
              <SalesShipmentDetailRecord action="view" :info="form" tab="inout_line" />
            </div>
          </div>

        </div>
      </div>

    </div>
  </NuxtLayout>
</template>