<script setup lang="ts">
import { cloneVNode, onMounted, 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";
import { useRoute } from "vue-router";

import DialogDataDiff from "@/modules/03_logs/components/DialogDataDiff.vue";

const route = useRoute();

import type { ResLog } from "@/modules/03_logs/interface/response/Main";

/** importStore*/
const storeData = useDataStore();
const { logData, size, searchAfter, systemName, date } = 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: "ผู้ใช้",
    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: "Response Code",
    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" }),
  },
  {
    name: "dataDiff",
    align: "left",
    label: "ข้อมูลที่เปลี่ยนแปลง",
    field: "dataDiff",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

const openDialog = ref<boolean>(false);
const currentlogData =
  ref<Omit<ResLog, "endTimeStamp" | "tId" | "processTime" | "systemName">>();
const currentDataDiff = ref<{
  before: string;
  after: string;
}>({
  before: "",
  after: "",
});

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

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

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,
        date: date.value,
      },
      true
    );
    setTimeout(() => {}, 500);
  }
}

function selectedDate() {
  logData.value = [];
  searchAfter.value = undefined;
  storeData.fetchLog(
    {
      size: size.value ?? undefined,
      search: inputSearch.value ?? undefined,
      systemName: systemName.value ?? undefined,
      searchAfter: searchAfter.value ?? undefined,
      date: date.value,
    },
    true
  );
}

function classColorMethod(val: string) {
  switch (val) {
    case "GET":
      return "blue";
    case "PUT":
      return "warning";
    case "POST":
      return "primary";
    case "PATCH":
      return "teal-12";
    case "DELETE":
      return "red";

    default:
      break;
  }
}

onMounted(() => {
  systemName.value = route.query.system as string;
});
</script>

<template>
  <div class="bg-white">
    <div class="row q-pa-md">
      <datepicker
        menu-class-name="modalfix"
        v-model="date"
        :locale="'th'"
        autoApply
        :enableTimePicker="false"
        @update:modelValue="selectedDate"
        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(date ?? new Date())"
            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,
              date: date ?? 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'">
                  <template v-if="props.row.userName && props.row.user">
                    {{ props.row.userName ?? "-" }}
                    <div class="text-grey" style="font-size: 65%">
                      {{ props.row.user ?? "-" }}
                    </div>
                  </template>
                  <template v-else> - </template>
                </div>
                <div v-else-if="col.name === 'method'">
                  <q-badge
                    :text-color="classColorMethod(col.value)"
                    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'
                  }`"
                  class="ellipsis"
                  style="max-width: 10vw"
                >
                  {{ col.value ?? "-" }}
                  <q-tooltip> {{ col.value }} </q-tooltip>
                </div>

                <div v-else-if="col.name === 'dataDiff' && !!col.value">
                  <q-btn
                    dense
                    flat
                    round
                    icon="mdi-eye-outline"
                    color="primary"
                    size="12px"
                    @click.stop="
                      () => {
                        currentDataDiff = col.value;
                        currentlogData = {
                          startTimeStamp: props.row.startTimeStamp,
                          username: props.row.userName,
                          host: props.row.host,
                          endpoint: props.row.endpoint,
                          method: props.row.method,
                          responseCode: props.row.responseCode,
                          logType: props.row.logType,
                          responseDescription: props.row.responseDescription,
                          sequence: props.row.sequence,
                          dataDiff: props.row.dataDiff,
                        };
                        openDialog = true;
                      }
                    "
                  >
                    <q-tooltip>ดูรายละเอียด </q-tooltip>
                  </q-btn>
                </div>

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

  <DialogDataDiff
    v-model:open-dialog="openDialog"
    title="รายละเอียดข้อมูล"
    :close="
      () => {
        openDialog = false;
      }
    "
    style="max-width: 100%"
  >
    <div class="column" style="border: #f0ecec 1px solid; border-radius: 7px">
      <div
        class="col row"
        :class="{ 'bg-grey-3': index % 2 }"
        v-for="(item, key, index) in currentlogData"
        :key="key"
        style="border-bottom: #f0ecec 1px solid; min-height: 40px"
      >
        <div
          class="col q-pl-sm text-bold"
          :class="{
            'self-center': key !== 'dataDiff' && key !== 'sequence',
            'q-pt-md': key === 'dataDiff',
          }"
          style="max-width: 150px"
        >
          {{
            {
              startTimeStamp: "เวลา",
              username: "ผู้ใช้",
              host: "Host",
              endpoint: "Endpoint",
              method: "Method",
              responseCode: "Response Code",
              logType: "สถานะ",
              responseDescription: "ข้อความ",
              sequence: "ลำดับการทำงาน",
              dataDiff: "ข้อมูลที่เปลี่ยนแปลง",
            }[key] || key
          }}
        </div>

        <div
          class="self-center"
          v-if="key === 'startTimeStamp' && typeof item === 'string'"
        >
          {{ date2Thai(new Date(item), true, true) }}
        </div>

        <div class="self-center" v-if="key === 'method'">
          <q-badge text-color="blue" style="background-color: #f0ecec">{{
            item ?? "-"
          }}</q-badge>
        </div>

        <div class="self-center" v-else-if="key === 'logType'">
          <q-badge
            text-color="white"
            :color="
              item === 'error' ? 'red' : item === 'info' ? 'primary' : 'warning'
            "
            >{{ item ?? "-" }}</q-badge
          >
        </div>
        <div class="col q-pr-md" v-else-if="key === 'sequence'">
          <div v-for="(row, index) in item">
            <div class="text-subtitle1 text-bold">ลำดับที่ {{ index + 1 }}</div>
            <div
              class="q-pa-md q-mb-md"
              style="border: 1px solid hsla(0 0% 0% / 0.1); border-radius: 7px"
            >
              <div class="row" v-for="(value, key) in row" :key="key">
                <div v-if="typeof key === 'string' && key === 'query'">
                  {{ `${key}: ` }}
                  <div
                    class="q-pa-md q-mt-sm"
                    style="
                      background-color: hsla(0 0% 0% / 0.07);
                      color: hsl(0 0% 30%);
                      border: 1px solid hsla(0 0% 0% / 0.1);
                      border-radius: 7px;
                    "
                    v-for="q in value"
                  >
                    {{ `${q}` }}
                  </div>
                </div>
                <div v-else-if="typeof key === 'string' && key === 'request'">
                  {{ `${key}: ` }}

                  <div
                    class="q-pa-md q-mt-sm"
                    style="
                      background-color: hsla(0 0% 0% / 0.07);
                      color: hsl(0 0% 30%);
                      border: 1px solid hsla(0 0% 0% / 0.1);
                      border-radius: 7px;
                    "
                  >
                    <div v-for="(req, k) in value">
                      {{ `${k}: ${req}` }}
                    </div>
                  </div>
                </div>
                <div v-else>
                  {{ `${key}: ${value}` }}
                </div>
              </div>
            </div>
          </div>
        </div>
        <div
          class="col self-center"
          v-if="
            key !== 'dataDiff' &&
            key !== 'method' &&
            key !== 'logType' &&
            key !== 'startTimeStamp' &&
            key !== 'sequence'
          "
        >
          {{ item }}
        </div>

        <div
          v-if="
            item &&
            typeof item === 'object' &&
            'before' in item &&
            'after' in item
          "
          class="col"
        >
          <code-diff
            :old-string="JSON.stringify(JSON.parse(item.before), null, 4)"
            :new-string="JSON.stringify(JSON.parse(item.after), null, 4)"
            output-format="side-by-side"
          />
        </div>
      </div>
    </div>
  </DialogDataDiff>
</template>

<style scoped></style>
