<script setup lang="ts">
import { cloneVNode, ref } from "vue";
import type { QTableProps } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useDataStore } from "@/modules/03_logs/stores/main";
import { storeToRefs } from "pinia";

/** importStore*/
const storeData = useDataStore();
const { logData, size, searchAfter, systemName } = storeToRefs(storeData);
const { date2Thai } = useCounterMixin();
const columns = ref<QTableProps["columns"]>([
  {
    name: "startTimeStamp",
    align: "left",
    label: "เวลา",
    sortable: true,
    field: "startTimeStamp",
    headerStyle: "font-size: 14px",
    format: (v) => date2Thai(v, false, true),
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "username",
    align: "left",
    label: "username",
    sortable: true,
    field: "username",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "host",
    align: "left",
    label: "host",
    sortable: true,
    field: "host",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "endpoint",
    align: "left",
    label: "endpoint",
    sortable: true,
    field: "endpoint",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "method",
    align: "left",
    label: "method",
    sortable: true,
    field: "method",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "responseCode",
    align: "left",
    label: "responseCode",
    sortable: true,
    field: "responseCode",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "logType",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "logType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "responseDescription",
    align: "left",
    label: "ข้อความ",
    sortable: true,
    field: "responseDescription",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const inputSearch = defineModel<string>("inputSearch");
const selectDate = ref<Date>(new Date());
const pagination = ref({
  page: 1,
  rowsPerPage: 0,
});

const visibleColumns = ref<string[]>([
  "startTimeStamp",
  "username",
  "host",
  "endpoint",
  "method",
  "responseCode",
  "logType",
  "responseDescription",
]);

function handleScroll(event: any) {
  const element = event.target;
  if (element.scrollHeight - element.scrollTop === element.clientHeight) {
    storeData.fetchLog(
      {
        size: size.value ?? undefined,
        search: inputSearch.value ?? undefined,
        systemName: systemName.value ?? undefined,
        searchAfter: searchAfter.value ?? undefined,
      },
      true
    );
    setTimeout(() => {}, 500);
  }
}
</script>

<template>
  <div class="bg-white">
    <div class="row q-pa-md">
      <datepicker
        menu-class-name="modalfix"
        v-model="selectDate"
        :locale="'th'"
        autoApply
        :enableTimePicker="false"
        @update:modelValue="console.log('date')"
        week-start="0"
      >
        <template #year="{ year }">{{ year + 543 }}</template>
        <template #year-overlay-value="{ value }">{{
          parseInt(value + 543)
        }}</template>
        <template #trigger>
          <q-input
            outlined
            dense
            :model-value="date2Thai(selectDate)"
            hide-bottom-space
          >
            <template v-slot:prepend>
              <q-icon name="event" class="cursor-pointer" color="primary">
              </q-icon>
            </template>
          </q-input>
        </template>
      </datepicker>
      <q-space />
      <div class="items-center q-gutter-md" style="display: flex">
        <!-- ค้นหาข้อความใน table -->
        <q-input
          standout
          dense
          clearable
          v-model="inputSearch"
          ref="filterRef"
          @update:model-value="
            storeData.fetchLog({
              size: size ?? undefined,
              search: inputSearch ?? undefined,
              systemName: systemName ?? undefined,
            })
          "
          outlined
          debounce="500"
          placeholder="ค้นหา"
          style="max-width: 200px"
          class="q-ml-sm"
        >
          <template v-slot:append>
            <q-icon name="search" />
          </template>
        </q-input>
        <!-- แสดงคอลัมน์ใน table -->
        <q-select
          v-model="visibleColumns"
          multiple
          outlined
          dense
          options-dense
          :display-value="$q.lang.table.columns"
          emit-value
          map-options
          :options="columns"
          option-value="name"
          options-cover
          style="min-width: 150px"
        />
      </div>
    </div>
    <div class="q-pa-md">
      <div style="max-height: 70vh; overflow: scroll" @scroll="handleScroll">
        <d-table
          ref="table"
          :columns="columns"
          :rows="storeData.logData"
          row-key="name"
          flat
          bordered
          hide-pagination
          v-model:pagination="pagination"
          dense
          :rows-per-page-options="[0]"
          class="custom-header-table"
          :visible-columns="visibleColumns"
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th v-for="col in props.cols" :key="col.name" :props="props">
                <span class="text-weight-medium">{{ col.label }}</span>
              </q-th>
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr
              :props="props"
              class="cursor-pointer"
              style="overflow: scroll"
            >
              <q-td v-for="col in props.cols" :key="col.id">
                <div v-if="col.name === 'username'">
                  {{ props.row.user }}
                  <div class="text-grey" style="font-size: 65%">
                    {{ props.row.userId }}
                  </div>
                </div>
                <div v-else-if="col.name === 'method'">
                  <q-badge
                    text-color="blue"
                    style="background-color: #f0ecec"
                    >{{ col.value ?? "-" }}</q-badge
                  >
                </div>
                <div v-else-if="col.name === 'logType'">
                  <q-badge
                    text-color="white"
                    :color="
                      col.value === 'error'
                        ? 'red'
                        : col.value === 'info'
                        ? 'primary'
                        : 'warning'
                    "
                    >{{ col.value ?? "-" }}</q-badge
                  >
                </div>
                <div
                  v-else-if="col.name === 'responseDescription'"
                  :class="`text-${
                    props.row.logType === 'Error'
                      ? 'red'
                      : props.row.logType === 'info'
                      ? 'primary'
                      : 'warning'
                  }`"
                >
                  {{ col.value ?? "-" }}
                </div>

                <div v-else class="ellipsis" style="max-width: 15vw">
                  {{ col.value === "" || col.value === null ? "-" : col.value }}
                  <q-tooltip> {{ col.value }} </q-tooltip>
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </div>
    </div>
  </div>
</template>

<style scoped></style>
