<script setup lang="ts">
import { cloneVNode, onMounted, ref, reactive, onBeforeMount } from "vue";
import { useQuasar, type QTableProps } from "quasar";
import { useRoute } from "vue-router";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useDataStore } from "@/modules/03_logs/stores/main";
import { storeToRefs } from "pinia";
import genReportXLSX from "@/plugins/genreportxlsx";

import type {
  Pagination,
  ItemsDropdown,
  DataTree,
  QueryProfile,
} from "@/modules/03_logs/interface/index/Main";

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

const route = useRoute();

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

/** use*/
const $q = useQuasar();
const storeData = useDataStore();
const { logData, size, searchAfter, systemName, date } = storeToRefs(storeData);
const { date2Thai, messageError, hideLoader, showLoader } = useCounterMixin();

const startTime = ref<Date | null>(null); // เวลาเริ่มต้น
const endTime = ref<Date | null>(null); //เวลาสินสุด
const startDate = ref<string>(""); // วันเริ่มต้น
const endDate = ref<string>(""); // วันสินสุด
const sortTime = ref<"desc" | "asc">("desc");
const openDialog = ref<boolean>(false);
const currentlogData =
  ref<Omit<ResLog, "endTimeStamp" | "tId" | "processTime" | "systemName">>();
const currentDataDiff = ref<{
  before: string;
  after: string;
}>({
  before: "",
  after: "",
});

//table
const inputSearch = defineModel<string>("inputSearch"); //คำค้หา
const columns = ref<QTableProps["columns"]>([
  {
    name: "startTimeStamp",
    align: "left",
    label: "เวลา",
    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: "ผู้ใช้",
    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",
    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",
    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",
    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",
    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: "สถานะ",
    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: "ข้อความ",
    field: "responseDescription",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "id",
    align: "left",
    label: "ID",
    field: "id",
    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 visibleColumns = ref<string[]>([
  "startTimeStamp",
  "username",
  "host",
  "endpoint",
  "method",
  "responseCode",
  "logType",
  "responseDescription",
  "sequence",
  "dataDiff",
]);
const pagination = ref<Pagination>({
  page: 1,
  rowsPerPage: 0,
});

const labelDropdown = ref<string>("วันนี้");
const valDropdown = ref<string>("");
const searchStatus = ref<string>("");

//รายการค้นหา
const itemsDropdown = ref<ItemsDropdown[]>([
  {
    labal: "วันนี้",
    val: "today",
  },
  {
    labal: "เมื่อวาน",
    val: "yesterday",
  },
  {
    labal: "ย้อนหลัง 24 ชั่วโมง",
    val: "past24hours",
  },
  {
    labal: "ย้อนหลัง 7 วัน",
    val: "past7days",
  },
  {
    labal: "ย้อนหลัง 30 วัน",
    val: "past30days",
  },
  {
    labal: "กำหนดเอง",
    val: "customized",
  },
]);

const statusOpt = ref<string[]>(["info", "warning", "error"]);
/******* โครงสร้าง *******/
const filter = ref<string>(""); // ค้นหาข้อมูลรายการโครงสร้าง
const nodeTree = ref<DataTree[]>([]); // ข้อมูลรายการโครงสร้าง
const expanded = ref<Array<string>>([]); // เปิดรายการโครงสร้าง

const qureyBody = reactive<QueryProfile>({
  searchKeyword: "", // คำค้นหา
  searchField: "fullName", // field ที่ต้องการค้นหา
  page: 1, // หน้า
  pageSize: 10, // จำนวนที่ต้องการ
  rootId: undefined, // หน่วยงานที่เลือก
});
/**
 * ฟังก์ชันเลือกหน่วยงาน
 * @param id หน่วยงานที่เลือก
 *
 * กำหนดค่าของ qureyBody ให้เป็นค่า defult และกำหนดค่าของ  qureyBody.rootId  เป็นหน่วยงานที่เลือก
 * และดึงข้อมูลรายชื่อคนที่มีสิทธิ์จัดการโครงสร้างในหน่วยงานที่เลือก
 */
async function selectedOrg(id: string) {
  qureyBody.rootId = id;
  qureyBody.page = 1;
  logData.value = [];
  await storeData.fetchLog(
    {
      rootId: qureyBody.rootId ?? undefined,
      size: size.value ?? undefined,
      search: inputSearch.value ?? undefined,
      systemName: systemName.value ?? undefined,
      // searchAfter: searchAfter.value ?? undefined,
      sort: sortTime.value,
      startDate: new Date(startDate.value) ?? undefined,
      endDate: new Date(endDate.value) ?? undefined,
      searchStatus: searchStatus.value ?? undefined,
    },
    true,
  );
}

/**
 *  ฟังชั่นสำหรับดึงไอดีโครงสร้างปัจจุบัน
 */
async function fetchOrganizationActive() {
  showLoader();
  await http
    .get(config.API.activeOrganization)
    .then(async (res) => {
      const data = res.data.result;
      if (data) {
        await fatchOrg(data.activeId);
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชันดึงข้อมูลโครงสร้างเก็บข้อมูลโครงสร้างไว้ใน nodeTree
 * revision id ของโครงสร้าง
 */
async function fatchOrg(id: string) {
  await http
    .get(config.API.orgByid(id))
    .then(async (res) => {
      const data = await res.data.result;
      nodeTree.value = data;
      searchAfter.value = undefined;
      if (data.length === 1) {
        selectedOrg(data[0].orgRootDnaId);
      } else {
        await storeData.fetchLog({
          size: size.value,
          systemName: systemName.value ?? undefined,
          date: date.value[0],
        });
      }
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/*** scroll และโหลดข้อมูลรายการ Logs เพิ่ม */
const infiniteScroll = handleScroll();
function handleScroll() {
  let scrollFlag = false;

  return async (e: Event) => {
    if (scrollFlag) return;

    const element = e.target as HTMLElement;

    if (
      Math.abs(
        element.scrollHeight - element.clientHeight - element.scrollTop,
      ) <= 1
    ) {
      scrollFlag = true;
      await storeData.fetchLog(
        {
          rootId: qureyBody.rootId ?? undefined,
          size: size.value ?? undefined,
          search: inputSearch.value ?? undefined,
          systemName: systemName.value ?? undefined,
          searchAfter: searchAfter.value ?? undefined,
          sort: sortTime.value,
          startDate: new Date(startDate.value) ?? undefined,
          endDate: new Date(endDate.value) ?? undefined,
          searchStatus: searchStatus.value ?? undefined,
        },
        true,
      );
      await new Promise((resolve) => setTimeout(resolve, 1000));
      scrollFlag = false;
    }
  };
}

/** ฟังก์ชั่นดึงข้อมูลรายการ Logs ตามเงื่อนไข */
function selectedDate() {
  if (!startDate.value) {
    const startDateToday = new Date();
    startDateToday.setHours(0, 0, 0, 0);

    // ตั้งค่า endDate เป็นเวลา 23:59:59 ของวันนี้
    const endDateToday = new Date();
    endDateToday.setHours(23, 59, 59, 999);

    startDate.value = startDateToday.toISOString();
    endDate.value = endDateToday.toISOString();
  }

  logData.value = [];
  searchAfter.value = undefined;
  storeData.fetchLog(
    {
      rootId: qureyBody.rootId ?? undefined,
      size: size.value ?? undefined,
      search: inputSearch.value ?? undefined,
      systemName: systemName.value ?? undefined,
      searchAfter: searchAfter.value ?? undefined,
      sort: sortTime.value,
      searchStatus: searchStatus.value ?? undefined,
      startDate: new Date(startDate.value),
      endDate: new Date(endDate.value),
    },
    true,
  );
}

/**
 * แปลงสึตาม method
 * @param val ค่า method
 * @returns ต่าสี
 */
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;
  }
}

/**
 * เลือกประเภทการค้นหาข้อมูล
 * @param labal ชื่อประเภทการค้นหาข้อมูล
 * @param type ประเภทการค้นหาข้อมูล
 *
 * และค้นหาข้อมูลรายการ Logs ใหม่
 */
function onItemClick(labal: string, type: string) {
  labelDropdown.value = labal;
  valDropdown.value = type;

  const setDateRange = (daysAgo: number = 0, endOfDay = false) => {
    const date = new Date();
    if (daysAgo) date.setDate(date.getDate() - daysAgo);
    date.setHours(
      endOfDay ? 23 : 0,
      endOfDay ? 59 : 0,
      endOfDay ? 59 : 0,
      endOfDay ? 999 : 0,
    );
    return date.toISOString();
  };

  if (type === "today") {
    //วันนี้
    startDate.value = setDateRange(0);
    endDate.value = setDateRange(0, true);
  } else if (type === "yesterday") {
    //เมื่อวาน
    startDate.value = setDateRange(1);
    endDate.value = setDateRange(1, true);
  } else if (type === "past24hours") {
    // ย้อนหลัง 24 ชั่วโมง
    const startDatePast24Hours = new Date();
    startDatePast24Hours.setHours(startDatePast24Hours.getHours() - 24);
    startDate.value = startDatePast24Hours.toISOString();

    // ตั้งค่า endDate เป็นเวลาปัจจุบัน
    endDate.value = new Date().toISOString();
  } else if (["past7days", "past30days"].includes(type)) {
    // ย้อนหลัง 7 วัน และ 30 วัน
    const days = { past7days: 7, past30days: 30 }[type];
    startDate.value = setDateRange(days);
    endDate.value = new Date().toISOString();
  }

  type !== "customized" && selectedDate();

  startTime.value = null;
  endTime.value = null;
}

/**
 * อัปเดทวันที่ต้องการค้นหาข้อมูลรายการ Logs
 *
 * และค้นหาข้อมูลรายการ Logs ใหม่
 */
function updateDate() {
  if (startTime.value && endTime.value) {
    startDate.value = startTime.value.toISOString();
    endDate.value = endTime.value.toISOString();
    selectedDate();
  }
}

function onSendCSV() {
  showLoader();
  const queryString = {
    rootId: qureyBody.rootId ?? undefined,
    // size: size.value ?? undefined,
    search: inputSearch.value ?? undefined,
    systemName: systemName.value ?? undefined,
    // searchAfter: searchAfter.value ?? undefined,
    sort: sortTime.value,
    startDate: new Date(startDate.value) ?? undefined,
    endDate: new Date(endDate.value) ?? undefined,
  };
  http
    .get(config.API.reportLog, {
      params: queryString,
    })
    .then(async (res) => {
      const data = res.data;
      await genReportXLSX(data, `LOG_${date2Thai(new Date(startDate.value))}`);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

async function downloadTxt() {
  if (currentlogData.value?.id) {
    await generateTxt(
      currentlogData.value?.id,
      `LOG_${date2Thai(new Date(startDate.value))}`,
    );
  }
}

onBeforeMount(async () => {
  await fetchOrganizationActive(); // ดึงข้อมูลโครงสร้างปัจจุบัน
});

onMounted(async () => {
  systemName.value = route.query.system as string;
  const date = new Date();
  date.setHours(0, 0, 0, 0); // ตั้งเวลาเป็น 00:00:00.000

  startDate.value = date.toISOString(); // แปลงเป็น ISO string
  endDate.value = new Date().toISOString();
});
</script>

<template>
  <div class="bg-white q-pa-md">
    <div class="row q-col-gutter-sm">
      <div class="col-md-3">
        <div class="q-mb-sm">
          <q-input dense outlined v-model="filter" label="ค้นหา">
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>
        </div>
        <div class="bg-white tree-container q-pa-xs">
          <q-tree
            class="q-pa-sm q-gutter-sm"
            dense
            :nodes="nodeTree"
            node-key="orgRootName"
            label-key="orgRootName"
            :filter="filter.trim()"
            no-results-label="ไม่พบข้อมูลที่ค้นหา"
            no-nodes-label="ไม่มีข้อมูล"
            v-model:expanded="expanded"
          >
            <template v-slot:default-header="prop">
              <q-item
                clickable
                class="row col-12 items-center text-dark q-py-xs q-pl-sm rounded-borders my-list"
                :active="qureyBody.rootId == prop.node.orgRootDnaId"
                active-class="my-list-link text-primary text-weight-medium"
                @click.stop="selectedOrg(prop.node.orgRootDnaId)"
              >
                <div>
                  <div class="text-weight-medium">
                    {{ prop.node.orgRootName }}
                  </div>
                  <div class="text-weight-light text-grey-8">
                    {{
                      prop.node.orgRootCode == null
                        ? null
                        : prop.node.orgRootCode
                    }}
                    {{
                      prop.node.orgRootShortName == null
                        ? null
                        : prop.node.orgRootShortName
                    }}
                  </div>
                </div>
              </q-item>
            </template>
          </q-tree>
        </div>
      </div>

      <div class="col-md-9">
        <div class="row">
          <div class="row q-gutter-sm">
            <div>
              <q-btn-dropdown outline color="grey-5" class="full-height">
                <template v-slot:label>
                  <div class="row items-center no-wrap">
                    <div class="text-black">{{ labelDropdown }}</div>
                  </div>
                </template>
                <q-list>
                  <q-item
                    dense
                    v-for="item in itemsDropdown"
                    clickable
                    v-close-popup
                    @click="onItemClick(item.labal, item.val)"
                  >
                    <q-item-section>
                      <q-item-label>{{ item.labal }}</q-item-label>
                    </q-item-section>
                  </q-item>
                </q-list>
              </q-btn-dropdown>
            </div>
            <q-btn
              dense
              flat
              color="green"
              type="submit"
              icon-right="download"
              @click="onSendCSV"
              ><q-tooltip>ดาวน์โหลด (.CSV)</q-tooltip></q-btn
            >
          </div>

          <q-space />
          <div
            class="items-center justify-end q-gutter-xs"
            style="display: flex"
          >
            <!-- ค้นหาข้อความใน table -->
            <!-- @update:model-value="" -->
            <q-input
              standout
              dense
              v-model="inputSearch"
              ref="filterRef"
              @keydown.enter.prevent="
                storeData.fetchLog({
                  rootId: qureyBody.rootId ?? undefined,
                  size: size ?? undefined,
                  search: inputSearch?.trim() ?? undefined,
                  systemName: systemName ?? undefined,
                  sort: sortTime,
                  // date: new Date(startDate),
                  startDate: new Date(startDate),
                  endDate: new Date(endDate),
                })
              "
              outlined
              placeholder="ค้นหา"
              style="max-width: 200px"
              class="q-ml-sm"
            >
              <template v-slot:append>
                <q-icon name="search" />
              </template>
            </q-input>

            <q-select
              v-model="searchStatus"
              label="ค้นหาสถานะ"
              dense
              emit-value
              map-options
              :options="statusOpt"
              option-value="id"
              option-label="name"
              lazy-rules
              hide-bottom-space
              borderless
              outlined
              style="width: 150px"
              :hide-dropdown-icon="false"
              @update:modelValue="selectedDate()"
              clearable
            >
              <template v-slot:selected-item="scope">
                <q-chip
                  v-if="searchStatus"
                  dense
                  :tabindex="scope.tabindex"
                  :color="
                    scope.opt === 'info'
                      ? 'primary'
                      : scope.opt === 'warning'
                      ? 'warning'
                      : scope.opt === 'error'
                      ? 'red'
                      : 'white'
                  "
                  text-color="white"
                  class="q-ma-none text-caption"
                  style="
                    border-radius: 3px;
                    max-width: 60vw;
                    word-wrap: break-word;
                  "
                >
                  {{ scope.opt }}
                </q-chip>
              </template>
            </q-select>
            <!-- แสดงคอลัมน์ใน 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"
              style="min-width: 140px"
            />
          </div>
        </div>
        <div
          v-if="valDropdown === 'customized'"
          class="row q-col-gutter-md q-mt-xs"
        >
          <div class="col-3">
            <datepicker
              v-model="startTime"
              :locale="'th'"
              :max-date="endTime"
              selectText="เลือก"
              cancelText="ยกเลิก"
              @update:modelValue="updateDate()"
            >
              <template #year="{ year }">{{ year + 543 }}</template>
              <template #year-overlay-value="{ value }">{{
                parseInt(value + 543)
              }}</template>
              <template #trigger>
                <q-input
                  dense
                  outlined
                  :model-value="
                    startTime ? date2Thai(startTime, false, true) : null
                  "
                  :label="`${'วันเริ่มต้น'}`"
                  hide-bottom-space
                >
                  <template v-slot:prepend>
                    <q-icon
                      name="event"
                      class="cursor-pointer"
                      style="color: var(--q-primary)"
                    >
                    </q-icon>
                  </template>
                </q-input>
              </template>

              <template #action-preview="{ value }">
                {{ date2Thai(value, false, true) }}
              </template>
            </datepicker>
          </div>
          <div class="col-3">
            <datepicker
              v-model="endTime"
              :locale="'th'"
              :enableTimePicker="true"
              selectText="เลือก"
              cancelText="ยกเลิก"
              @update:modelValue="updateDate()"
              :min-date="startTime"
            >
              <template #year="{ year }">{{ year + 543 }}</template>
              <template #year-overlay-value="{ value }">{{
                parseInt(value + 543)
              }}</template>
              <template #trigger>
                <q-input
                  dense
                  outlined
                  :model-value="
                    endTime ? date2Thai(endTime, false, true) : null
                  "
                  :label="`${'วันสิ้นสุด'}`"
                  hide-bottom-space
                >
                  <template v-slot:prepend>
                    <q-icon
                      name="event"
                      class="cursor-pointer"
                      style="color: var(--q-primary)"
                    >
                    </q-icon>
                  </template>
                </q-input>
              </template>
              <template #action-preview="{ value }">
                {{ date2Thai(value, false, true) }}
              </template>
            </datepicker>
          </div>
        </div>
        <div
          class="q-mt-md"
          style="max-height: 70vh; overflow: scroll"
          @scroll="infiniteScroll"
        >
          <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">
                  <div
                    v-if="col.name === 'startTimeStamp'"
                    class="text-weight-medium"
                  >
                    {{ col.label }}
                    <q-btn
                      v-if="sortTime === 'desc'"
                      flat
                      round
                      size="8px"
                      icon="mdi-arrow-up"
                      @click="
                        () => {
                          sortTime = 'asc';
                          selectedDate();
                        }
                      "
                    />
                    <q-btn
                      v-else
                      flat
                      round
                      size="8px"
                      icon="mdi-arrow-down"
                      @click="
                        () => {
                          sortTime = 'desc';
                          selectedDate();
                        }
                      "
                    />
                  </div>
                  <span v-else 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 as string)"
                      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'">
                    <q-btn
                      dense
                      flat
                      round
                      icon="mdi-eye"
                      color="info"
                      @click.stop="
                        () => {
                          currentDataDiff = col.value;
                          currentlogData = {
                            id: props.row.id,
                            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,
                            input: props.row.input,
                            output: props.row.output,
                          };
                          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>
  </div>

  <DialogDataDiff
    v-model:open-dialog="openDialog"
    title="รายละเอียดข้อมูล"
    :downloadTxt="downloadTxt"
    :close="
      () => {
        openDialog = false;
      }
    "
    style="max-width: 100%"
  >
    <div style="border: #f0ecec 1px solid; border-radius: 7px">
      <template :key="key" v-for="(item, key) in currentlogData">
        <div
          class="col row row-color"
          style="border-bottom: #f0ecec 1px solid"
          v-if="!!item"
        >
          <div
            class="col q-pl-sm text-bold q-pa-sm"
            :class="{
              'self-center': ![
                'dataDiff',
                'input',
                'output',
                'sequence',
              ].includes(key),
            }"
            style="max-width: 150px"
          >
            {{
              {
                id: "ID",
                startTimeStamp: "เวลา",
                username: "ผู้ใช้",
                host: "Host",
                endpoint: "Endpoint",
                method: "Method",
                responseCode: "Response Code",
                logType: "สถานะ",
                responseDescription: "ข้อความ",
                sequence: "ลำดับการทำงาน",
                dataDiff: "ข้อมูลที่เปลี่ยนแปลง",
                input: "ข้อมูลเข้า",
                output: "ข้อมูลออก",
              }[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="classColorMethod(item as string)"
              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">
                ลำดับที่ {{ Number(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;
                        max-width: 60vw;
                        word-wrap: break-word;
                      "
                    >
                      <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' &&
              key !== 'input' &&
              key !== 'output'
            "
          >
            {{ 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
            class="col q-py-sm"
            v-if="(item && key === 'input') || key === 'output'"
          >
            <pre style="margin: 0; max-width: 100%; overflow-x: auto">{{
              item
            }}</pre>
          </div>
        </div>
      </template>
    </div>
  </DialogDataDiff>
</template>

<style scoped>
.row-color:nth-child(2n + 1) {
  background-color: #eeeeee;
}

.dp__action_row {
  padding: 2px !important;
}

.tree-container {
  overflow: auto;
  height: 74vh;
  border: 1px solid #e6e6e7;
  border-radius: 10px;
}

.my-list-link {
  color: rgb(118, 168, 222);
  border-radius: 5px;
  background: #a3d3fb48 !important;
  font-weight: 600;
  border: 1px solid rgba(175, 185, 196, 0.217);
}
</style>
