<template>
  <q-dialog
    v-model="showCartonDetailLookupDialog"
    persistent
    @before-show="lookupCode && dirty && getData()"
  >
    <q-card class="dialog-width">
      <q-bar>
        <div>Carton Detail Lookup</div>
        <q-space />
        <q-btn dense flat icon="close" label="Close" v-close-popup />
      </q-bar>
      <q-card-section>
        <div class="row q-pa-xs justify-start">
          <div class="col q-gutter-sm">
            <q-radio v-model="lookupMode" val="UCC128" label="UCC128" />
            <q-radio
              v-model="lookupMode"
              val="Consolidated #"
              label="Consolidated #"
            />
            <q-radio v-model="lookupMode" val="Order" label="Order #" />
            <q-radio v-model="lookupMode" val="Invoice" label="Invoice #" />
          </div>

          <div class="col">
            <q-input
              class="search-lookup shadow-2"
              placeholder="Enter lookup value"
              aria-label="Enter lookup value"
              v-model.trim="lookupCode"
              bg-color="white"
              filled
              dense
              @keyup.enter="getData"
            >
              <template v-slot:append>
                <q-btn flat dense icon="search" @click="getData" />
              </template>
            </q-input>
          </div>
        </div>

        <q-table
          id="carton-detail-lookup-table"
          :rows="results"
          :columns="columns"
          :rows-per-page-options="[0, 10, 20, 50, 100]"
        >
          <template v-slot:header-cell="props">
            <q-th :props="props">
              {{ props.col.label }}
              <br v-if="props.col.label2" />
              {{ props.col.label2 }}
              <br v-if="props.col.label3" />
              {{ props.col.label3 }}
            </q-th>
          </template>
          <template v-slot:body-cell-UCC128="props">
            <q-td :props="props">
              {{ props.row.UCC128 }}
              <br />
              {{ props.row.cartonNum }}
              <br />
              {{ props.row.consolidatedNum || '-' }}
            </q-td>
          </template>
          <template v-slot:body-cell-orderNum="props">
            <q-td :props="props">
              {{ props.row.orderNum }}
              <br />
              {{ props.row.invoiceNum || '-' }}
            </q-td>
          </template>
          <template v-slot:body-cell-itemBRSNum="props">
            <q-td :props="props">
              {{ props.row.itemBRSNum }}
              <br />
              {{ props.row.itemUPC || '-' }}
            </q-td>
          </template>
          <template v-slot:body-cell-itemMFGPart="props">
            <q-td :props="props">
              {{ props.row.itemMFGPart }}
              <br />
              {{ props.row.itemCustomerSKU || '-' }}
            </q-td>
          </template>
          <template v-slot:body-cell-qtyOrd="props">
            <q-td :props="props">
              {{ props.row.qtyOrd }}
              <br />
              {{ props.row.qtyShipped || '-' }}
            </q-td>
          </template>
          <template v-slot:body-cell-yourCost="props">
            <q-td :props="props">
              {{ props.row.yourCost }}
              <br />
              {{ props.row.yourRetail || '-' }}
            </q-td>
          </template>
        </q-table>

        <q-table
          id="xlsx-table"
          :rows="results"
          :columns="xlsxColumns"
          hide-bottom
          table-style="display: none"
        />

        <div class="row justify-end q-mt-sm">
          <q-btn
            v-if="results.length"
            color="dark"
            class="q-ml-md"
            @click="exportFile('csv')"
          >
            Export CSV
          </q-btn>
          <q-btn
            v-if="results.length"
            color="dark"
            class="q-ml-md"
            @click="exportFile('xlsx')"
          >
            Export XLSX
          </q-btn>
          <q-btn
            v-if="results.length"
            color="dark"
            class="q-ml-md"
            @click="print"
          >
            Print
          </q-btn>
          <q-btn color="dark" class="q-ml-md" v-close-popup>Close</q-btn>
        </div>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue';

const globalStore = window.PiniaStores.useGlobalStore();
const { showCartonDetailLookupDialog, lookupMode, lookupCode } =
  window.Pinia.storeToRefs(globalStore);

const results = ref([]);
const dirty = ref(false);

const columns = [
  {
    name: 'UCC128',
    label: 'UCC128',
    label2: 'Carton#',
    label3: 'Consol.#',
  },
  {
    name: 'orderNum',
    label: 'Order#',
    label2: 'Invoice#',
  },
  {
    name: 'itemBRSNum',
    label: 'Part#',
    label2: 'UPC',
  },
  {
    name: 'itemMFGPart',
    label: 'MFG#',
    label2: 'Cust.SKU',
  },
  {
    name: 'itemDescription',
    label: 'Description',
    field: 'itemDescription',
    align: 'left',
    headerStyle: 'width: 40ch',
  },
  {
    name: 'qtyOrd',
    label: 'Ordered',
    label2: 'Shipped',
  },
  {
    name: 'yourCost',
    label: 'Unit Cost',
    label2: 'Your Retail',
  },
];

const xlsxColumns = [
  {
    name: 'cartonNum',
    label: 'Carton #',
    field: 'cartonNum',
  },
  {
    name: 'UCC128',
    label: 'UCC128',
    field: 'UCC128',
  },
  {
    name: 'consolidatedNum',
    label: 'Consolidated #',
    field: 'consolidatedNum',
  },
  {
    name: 'orderNum',
    label: 'Order #',
    field: 'orderNum',
  },
  {
    name: 'invoiceNum',
    label: 'Invoice #',
    field: 'invoiceNum',
  },
  {
    name: 'itemBRSNum',
    label: 'Part #',
    field: 'itemBRSNum',
  },
  {
    name: 'itemUPC',
    label: 'UPC',
    field: 'itemUPC',
  },
  {
    name: 'itemMFGPart',
    label: 'MFG Part #',
    field: 'itemMFGPart',
  },
  {
    name: 'itemCustomerSKU',
    label: 'Customer SKU',
    field: 'itemCustomerSKU',
  },
  {
    name: 'itemDescription',
    label: 'Description',
    field: 'itemDescription',
  },
  {
    name: 'qtyOrd',
    label: 'Ordered',
    field: 'qtyOrd',
  },
  {
    name: 'qtyShipped',
    label: 'Shipped',
    field: 'qtyShipped',
  },
  {
    name: 'yourCost',
    label: 'Unit Cost',
    field: 'yourCost',
  },
  {
    name: 'yourRetail',
    label: 'Your Retail',
    field: 'yourRetail',
  },
];

const getData = async () => {
  const response = await globalStore.lookupUcc128ConsolidatedNumber(
    lookupMode.value,
    lookupCode.value
  );
  globalStore.handleResponseMessage(response);

  results.value = response?.data?.ProDataSet?.ttUCC128 || [];
  dirty.value = false;
};

const print = () => {
  const divContents = document.getElementById(
    'carton-detail-lookup-table'
  ).innerHTML;
  const a = window.open('', '', 'height=700, width=900');
  a.document.write('<html>');
  a.document.write('<body>');
  a.document.write(`<title>Big Rock Sports - Carton Detail Lookup</title>
    <link
      href="https://cdn.jsdelivr.net/npm/quasar@2.11.5/dist/quasar.prod.css"
      rel="stylesheet"
      type="text/css"
    />
    <style type="text/css" media="print">@page { size: landscape; }</style>
    <style>
      .q-table__bottom {
        display: none;
      }
    </style>`);
  a.document.write(divContents);
  a.document.write('</body></html>');
  a.document.close();

  setTimeout(() => a.print(), 500);
};

const exportFile = (fileType) => {
  /* Create worksheet from HTML DOM TABLE */
  const wb = window.XLSX.utils.table_to_book(
    document.querySelector('#xlsx-table .q-table')
  );
  /* Export to file (start a download) */
  window.XLSX.writeFile(wb, 'Carton-Details.' + fileType);
};

watch(lookupCode, () => (dirty.value = true));
</script>

<style scoped>
.dialog-width {
  width: 95vw;
  min-width: 95vw;
  height: max-content;
}

.search-lookup {
  border: gray solid 1px;
  border-radius: 4px;
  padding: 0;
  min-width: 50px;
}
</style>

<style>
#carton-detail-lookup-table {
  width: 100%;
}

#carton-detail-lookup-table .q-table thead,
#carton-detail-lookup-table .q-table th {
  font-size: 1.5rem;
  background-color: #313131;
  color: white;
}

#carton-detail-lookup-table .q-table tbody td {
  font-size: 1em;
  color: black;
}

#carton-detail-lookup-table .q-table tbody tr:nth-child(odd) {
  background-color: #eee;
}

#carton-detail-lookup-table .search-offline {
  border: gray solid 1px;
  border-radius: 4px;
  padding: 0;
  min-width: 50px;
}

#carton-detail-lookup-table .search-offline:focus-within {
  outline: 2px #ee8900 solid;
  border: 1px #ee8900 solid;
}

#carton-detail-lookup-table input[type='text']:focus {
  background-color: white !important;
}

#carton-detail-lookup-table .q-table tbody tr:hover {
  background-color: rgb(239, 238, 201);
}
</style>
