<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,
  name: '',
  processing: true,
  isSOTrx: false,
  processed: false,
  amt: 0,
  help: '',
  inOut: '',
  inOutId: '',
  order: '',
  orderId: '',
  docType: '',
  docTypeId: '',
  docStatus: 'Draft',
  docStatusId: 'DR',
  salesRep: '',
  salesRepId: '',
  rmaType: '',
  rmaTypeId: '',
  currency: '',
  currencyId: '',
  partner: '',
  partnerId: '',
  processing: false,
  alert: {
    status: '',
    message: ''
  }
})

const detailRecordSelected = ref('rma_line')
const detailRecord = ref({
  rma_line: [],
  rma_tax: []
})

const retrieve = async () => {
  const res = await $fetch('/api/rma/'+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,
      name: res?.Name || '',
      processing: res?.Processing ?? true,
      isSOTrx: res?.IsSOTrx ?? false,
      processed: res?.Processed ?? false,
      amt: res?.Amt || 0,
      help: res?.Help || '',
      inOut: res?.InOut_ID?.identifier || '',
      inOutId: res?.InOut_ID?.id || '',
      order: res?.C_Order_ID?.identifier || '',
      orderId: res?.C_Order_ID?.id || '',
      docType: res?.C_DocType_ID?.identifier || '',
      docTypeId: res?.C_DocType_ID?.id || '',
      docStatus: res?.DocStatus?.identifier || 'Draft',
      docStatusId: res?.DocStatus?.id || 'DR',
      salesRep: res?.SalesRep_ID?.identifier || '',
      salesRepId: res?.SalesRep_ID?.id || '',
      rmaType: res?.M_RMAType_ID?.identifier || '',
      rmaTypeId: res?.M_RMAType_ID?.id || '',
      currency: res?.C_Currency_ID?.identifier || '',
      currencyId: res?.C_Currency_ID?.id || '',
      partner: res?.C_BPartner_ID?.identifier || '',
      partnerId: res?.C_BPartner_ID?.id || '',
      processing: false,
      alert: {
        status: '',
        message: ''
      }
    }
    
    for(let record of ['rma_line', 'rma_tax']) {
      const response = await $fetch('/api/rma/'+route.params.id+'/'+record.replaceAll('_', '-'), {
        headers: useRequestHeaders(['cookie'])
      })
      if(response) {
        let newData = []
        if(record === 'rma_line') {
          newData = response.records.map(item => {
            return {
              id: item.id,
              isActive: item?.IsActive ?? true,
              qty: item.Qty,
              processed: item?.Processed ?? false,
              amt: item.Amt,
              line: item.line,
              lineNetAmt: Number(body.lineNetAmt || 0),
              description: item.description,
              product: item?.M_Product_ID?.identifier || item?.M_Product_ID?.Name || '',
              productId: item?.M_Product_ID?.id || '',
              inOutLine: item?.M_InOutLine_ID?.identifier || '',
              inOutLineId: item?.M_InOutLine_ID?.id || '',
              tax: item?.C_Tax_ID?.identifier || '',
              taxId: item?.C_Tax_ID?.id || '',
              charge: item?.C_Charge_ID?.identifier || '',
              chargeId: item?.C_Charge_ID?.id || '',
            }
          }).sort((a, b) => Number(a.line) - Number(b.line))
        }
        if(record === 'rma_tax') {
          newData = response.records.map(item => {
            return {
              id: item.uid,
              tax: item.C_Tax_ID.identifier,
              taxId: item.C_Tax_ID.id,
              taxAmt: item.TaxAmt,
              taxBaseAmt: item.TaxBaseAmt,
              processed: item.Processed,
              isTaxIncluded: item.IsTaxIncluded,
              isActive: item.IsActive,
            }
          })
        }

        detailRecord.value[record] = newData
      }
    }
  }
}
onMounted(retrieve)

const printReport = async (fileType) => {
  const response = await $fetch('/api/rma/'+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('/procurements/vendor-rma')
}
const print = () => {
  router.push('/procurements/vendor-rma/'+route.params.id+'/print')
}
const edit = () => {
  router.push(`/procurements/vendor-rma/${route.params.id}/edit`)
}
const destroy = async () => {
  const confirmation = confirm('Are you sure want to delete this record?')
  if(confirmation) {
    await $fetch('/api/rma/'+route.params.id, {
      method: 'DELETE',
      headers: useRequestHeaders(['cookie'])
    })
    router.push(`/procurements/vendor-rma`)
  }
}

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: 'Procurements'},
  { link: '/procurements/vendor-rma', text: 'Vendor RMA'},
  { link: '#', text: 'View RMA Details', active: true}
]))
</script>

<template>
  <Head>
    <Title>View RMA 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">
            <div class="column is-half">
              <div class="d-flex gap-10px">
                <div class="w-150px d-flex justify-between gap-10px">
                  <strong>Name</strong>
                  <strong>:</strong>
                </div>
                <div>{{ form.name }}</div>
              </div>
            </div>
            <div class="column is-half">
              <div class="d-flex gap-10px">
                <div class="w-150px d-flex justify-between gap-10px">
                  <strong>Orgaanization</strong>
                  <strong>:</strong>
                </div>
                <div>{{ form.organization }}</div>
              </div>
            </div>
            
          </div>
          <div class="columns">
            <div class="column is-half">
              <div class="d-flex gap-10px">
                <div class="w-150px d-flex justify-between gap-10px">
                  <strong>Description</strong>
                  <strong>:</strong>
                </div>
                <div>{{ form.description }}</div>
              </div>
            </div>
            <div class="column is-half">
              <div class="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>
            
          </div>
          <div class="columns">
            <div class="column is-half">
              <div class="d-flex gap-10px">
                <div class="w-150px d-flex justify-between gap-10px">
                  <strong>RMA Type</strong>
                  <strong>:</strong>
                </div>
                <div>{{ form.rmaType }}</div>
              </div>
            </div>
            <div class="column is-half">
              <div class="d-flex gap-10px">
                <div class="w-150px d-flex justify-between gap-10px">
                  <strong>Sales Representative</strong>
                  <strong>:</strong>
                </div>
                <div>{{ form.salesRep }}</div>
              </div>
            </div>
            
          </div>
          <div class="columns">
            <div class="column is-half">
              <div class="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>
            <div class="column is-half">
              <div class="d-flex gap-10px">
                <div class="w-150px d-flex justify-between gap-10px">
                  <strong>Currency</strong>
                  <strong>:</strong>
                </div>
                <div>{{ form.currency }}</div>
              </div>
            </div>
            
          </div>
          <div class="columns">
            <div class="column is-half">
              <div class="d-flex gap-10px">
                <div class="w-150px d-flex justify-between gap-10px">
                  <strong>Order</strong>
                  <strong>:</strong>
                </div>
                <div>{{ form.order }}</div>
              </div>
            </div>
            <div class="column is-half">
              <div class="d-flex gap-10px">
                <div class="w-150px d-flex justify-between gap-10px">
                  <strong>Shipment/Receipt</strong>
                  <strong>:</strong>
                </div>
                <div>{{ form.inOut }}</div>
              </div>
            </div>
            
          </div>
          <div class="columns">
            <div class="column is-half">
              <div class="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="column is-half">
              <div class="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>
          <div class="columns">
            <div class="column is-half">
              <div class="d-flex gap-10px">
                <div class="w-150px d-flex justify-between gap-10px">
                  <strong>Comment/Help</strong>
                  <strong>:</strong>
                </div>
                <div>{{ form.help }}</div>
              </div>
            </div>
            <div class="column is-half">
              <div class="d-flex gap-10px">
                <div class="w-150px d-flex justify-between gap-10px">
                  <strong>Status</strong>
                  <strong>:</strong>
                </div>
                <div class="d-flex flexDirection-column">
                  <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.isSOTrx" class="checkInput" id="isSOTrx" :checked="form.isSOTrx" disabled>
                    <label class="checkLabel" for="isSOTrx">Sales Transaction</label>
                  </div>
                  <div class="check">
                    <input type="checkbox" v-model="form.processing" class="checkInput" id="processing" :checked="form.processing" disabled>
                    <label class="checkLabel" for="processing">Processing</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>
              </div>
            </div>
            
          </div>
          
          <div class="mb-3">
            <h4 class="mb-3">Detail Record</h4>
            <div>
              <RmasVendorRmaDetailRecord v-model="detailRecordSelected" :entries="detailRecord" action="view" />
            </div>
          </div>

        </div>
      </div>

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