<template>
  <q-dialog v-model="showSalesSummaryReport" @before-show="dirty && getData()">
    <q-card class="dialog-width">
      <q-bar>
        <div>Sales Summary</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 items-center">
          <div class="col-auto q-gutter-sm q-pr-lg">
            <q-radio
              v-model="lookupMode"
              val="singlecust"
              label="Single customer"
            />
            <q-radio v-model="lookupMode" val="allcust" label="All customers" />
          </div>

          <q-input
            class="col-auto search-lookup shadow-2 q-mr-sm"
            placeholder="Enter customer #"
            aria-label="Enter customer #"
            v-model.trim="cust"
            bg-color="white"
            filled
            dense
            :disable="lookupMode === 'allcust'"
            @keyup.enter="getData"
          />

          <div class="col-auto">
            <q-btn color="dark" icon="search" @click="getData" />
          </div>

          <q-input
            v-if="!globalStore.isProd"
            class="col-auto search-lookup shadow-2 q-mx-sm"
            placeholder="Enter rep # (DEV-ONLY)"
            aria-label="Enter rep # (DEV-ONLY)"
            v-model.trim="repNum"
            bg-color="white"
            filled
            dense
            @keyup.enter="getData"
          />
        </div>

        <q-tabs
          v-model="tab"
          dense
          class="text-grey"
          active-color="primary"
          indicator-color="primary"
          align="justify"
          narrow-indicator
        >
          <q-tab name="customers" label="Customer" />
          <q-tab name="brands" label="Brand" />
          <q-tab name="category" label="Category" />
        </q-tabs>

        <q-tab-panels v-model="tab" animated>
          <q-tab-panel name="customers" class="q-pa-none">
            <SalesSummaryTable
              :rows="customerTotals"
              :columns="customerColumns"
              :filter="customerFilter"
            />
          </q-tab-panel>

          <q-tab-panel name="brands" class="q-pa-none">
            <SalesSummaryTable
              :rows="brandTotals"
              :columns="brandColumns"
              :filter="brandFilter"
            />
          </q-tab-panel>

          <q-tab-panel name="category" class="q-pa-none">
            <SalesSummaryTable
              :rows="categoryTotals"
              :columns="categoryColumns"
              :filter="categoryFilter"
            />
          </q-tab-panel>
        </q-tab-panels>
      </q-card-section>
      <q-card-actions align="right">
        <q-btn color="dark" class="q-mr-sm" v-close-popup>Close</q-btn>
      </q-card-actions>
    </q-card>
  </q-dialog>
</template>

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

const globalStore = window.PiniaStores.useGlobalStore();
const { showSalesSummaryReport, customerInfo } =
  window.Pinia.storeToRefs(globalStore);
const lookupMode = ref('singlecust');
const cust = ref(customerInfo.value?.cust_num || '');
const dirty = ref(false);
const results = ref([]);
const customerTotals = ref([]);
const brandTotals = ref([]);
const categoryTotals = ref([]);
const tab = ref('customers');
const customerFilter = ref('');
const brandFilter = ref('');
const categoryFilter = ref('');
const repNum = ref('');

const sharedColumns = [
  {
    name: 'pytdsales',
    field: 'pytdsales',
    label: 'PYTD Sales',
    sortable: true,
    format: (val) => globalStore.toCurrency(val),
  },
  {
    name: 'ytdsales',
    field: 'ytdsales',
    label: 'YTD Sales',
    sortable: true,
    format: (val) => globalStore.toCurrency(val),
  },
  {
    name: 'deltasales',
    field: 'deltasales',
    label: 'Delta ($)',
    sortable: true,
    format: (val) => globalStore.toCurrency(val),
  },
  {
    name: 'deltapercent',
    field: 'deltapercent',
    label: 'Delta (%)',
    sortable: true,
    format: (val) => `${val}%`,
  },
];

const customerColumns = [
  {
    name: 'mode',
    field: 'customer',
    label: 'customer',
    sortable: true,
    align: 'left',
  },
  ...sharedColumns,
];

const brandColumns = [
  {
    name: 'mode',
    field: 'brand',
    label: 'brand',
    sortable: true,
    align: 'left',
  },
  ...sharedColumns,
];

const categoryColumns = [
  {
    name: 'mode',
    field: 'category',
    label: 'category',
    sortable: true,
    align: 'left',
  },
  ...sharedColumns,
];

const calculateDeltaSales = (row) => row.ytdsales - row.pytdsales;

const calculateDeltaPercent = (row) => {
  const deltasales = calculateDeltaSales(row);
  const deltapercent =
    row.pytdsales > 0
      ? Math.round((deltasales / row.pytdsales) * 100 * 10) / 10
      : '';
  return deltapercent;
};

const calculateSubtotals = (match, row) => {
  match.ytdsales += row.ytdsales;
  match.pytdsales += row.pytdsales;
  match.deltasales = calculateDeltaSales(match);
  match.deltapercent = calculateDeltaPercent(match);
};

const getData = async () => {
  const response = await globalStore.getSalesSummary(
    lookupMode.value,
    cust.value,
    repNum.value
  );
  globalStore.handleResponseMessage(response);

  results.value = response?.data?.ProDataSet?.ttSummaryData || [];
  customerTotals.value = [];
  brandTotals.value = [];
  // categoryTotals.value = [];

  for (let i = 0; i < results.value.length; ++i) {
    const row = results.value[i];

    const rowValues = {
      ytdsales: row.ytdsales,
      pytdsales: row.pytdsales,
      deltasales: calculateDeltaSales(row),
      deltapercent: calculateDeltaPercent(row),
    };

    if (row.customer) {
      const match = customerTotals.value.find(
        (r) => r.customer === row.customer
      );
      if (match) {
        calculateSubtotals(match, row);
      } else {
        customerTotals.value.push({
          customer: row.customer,
          ...rowValues,
        });
      }
    }

    if (row.brand) {
      const match = brandTotals.value.find((r) => r.brand === row.brand);
      if (match) {
        calculateSubtotals(match, row);
      } else {
        brandTotals.value.push({
          brand: row.brand,
          ...rowValues,
        });
      }
    }

    if (row.category) {
      const match = categoryTotals.value.find((r) => r.category === row.category);
      if (match) {
        calculateSubtotals(match, row);
      } else {
        categoryTotals.value.push({
          category: row.category,
          ...rowValues,
        });
      }
    }
  }

  dirty.value = false;
  globalStore.closeLoading();
};

watch(
  showSalesSummaryReport,
  () => showSalesSummaryReport.value && results.value.length === 0 && getData()
);
</script>

<style scoped>
@media screen and (min-width: 800px) {
  .dialog-width {
    width: max-content;
    min-width: max-content;
    height: max-content;
    min-height: 95vh;
  }
}

@media screen and (max-width: 801px) {
  .dialog-width {
    min-width: 98vw;
    min-height: 95vh;
  }
}

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

<style>
.sales-summary {
  width: 100%;
}

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

.sales-summary .q-table tbody td {
  font-size: 1em;
  color: black;
}

.sales-summary .q-table tbody tr:nth-child(odd) {
  background-color: #eee;
}

.sales-summary .search-offline {
  border: gray solid 1px;
  border-radius: 4px;
  padding: 0;
  min-width: 50px;
}

.sales-summary .search-offline:focus-within {
  outline: 2px #ee8900 solid;
  border: 1px #ee8900 solid;
}

.sales-summary input[type='text']:focus {
  background-color: white !important;
}

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