<script setup lang="ts">
import { ref, watch, reactive } from "vue";
import { useQuasar, type QTableProps } from "quasar";

import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import http from "@/plugins/http";
import config from "@/app.config";

import type { RequestItemsObject } from "@/modules/04_registryPerson/interface/index/discipline";

import DialogHeader from "@/components/DialogHeader.vue";

const $q = useQuasar();
const route = useRoute();
const mixin = useCounterMixin();
const { showLoader, hideLoader, messageError, date2Thai, pathRegistryEmp } =
  mixin;

/**
 * props
 */
const modal = defineModel<boolean>("modal", { required: true }); //แสดงประวัติแก้ไขวินัย
const id = defineModel<string>("id", { required: true }); //id วินัยที่ต้องการดูประวัติแก้ไขวินัย

const empType = ref<string>(pathRegistryEmp(route.name?.toString() ?? ""));
/**
 * props
 */

const filterKeyword = ref<string>(""); //คำค้นหา
const rows = ref<RequestItemsObject[]>([]); //รายการประวัติแก้ไขวินัย
const columns = ref<QTableProps["columns"]>([
  {
    name: "date",
    align: "left",
    label: "วัน เดือน ปี",
    sortable: true,
    field: "date",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "detail",
    align: "left",
    label: "รายละเอียด",
    sortable: true,
    field: "detail",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "level",
    align: "left",
    label: "ระดับการลงโทษทางวินัย",
    sortable: true,
    field: "level",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "unStigma",
    align: "left",
    label: "ล้างมลทิน",
    sortable: true,
    field: "unStigma",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "refCommandNo",
    align: "left",
    label: "เลขที่คำสั่ง",
    sortable: true,
    field: "refCommandNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "refCommandDate",
    align: "left",
    label: "เอกสารอ้างอิง (ลงวันที่)",
    sortable: true,
    format: (v) => date2Thai(v),
    field: "refCommandDate",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdateFullName",
    align: "left",
    label: "ผู้ดำเนินการ",
    sortable: true,
    field: "lastUpdateFullName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    format: (v) => date2Thai(v, false, true),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumns = ref<String[]>([
  "level",
  "detail",
  "unStigma",
  "refCommandNo",
  "refCommandDate",
  "date",
  "createdFullName",
  "createdAt",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);
const historyPagination = ref({
  page: 1,
  rowsPerPage: 10,
});

/**
 * fetch ข้อมูลประวัติการแก่ไขข้อมูลวินัย
 */
async function getHistory() {
  showLoader();
  await http
    .get(
      config.API.profileNewDisciplineHisByDisciplineId(id.value, empType.value)
    )
    .then(async (res) => {
      let data = await res.data.result;
      rows.value = [];
      data.map((e: RequestItemsObject) => {
        rows.value.push({
          ...e,
          id: e.id,
          level: e.level,
          detail: e.detail,
          unStigma: e.unStigma,
          refCommandNo: e.refCommandNo,
          refCommandDate:
            e.refCommandDate == null ? null : new Date(e.refCommandDate),
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ดูการเปลี่ยนแปลงของ modal
 *
 * ถ้า modal เป็น true  เรียก getHistory เพิ่อดึงข้อมูลประวัติการแก้ไขวินัย
 */
watch(modal, (status) => {
  if (status == true) {
    getHistory();
    filterKeyword.value = "";
  } else {
    filterKeyword.value = "";
  }
});
</script>

<template>
  <q-dialog v-model="modal" persistent>
    <q-card style="min-width: 80%">
      <DialogHeader
        tittle="ประวัติแก้ไขวินัย"
        :close="() => ((modal = false), (rows = []))"
      />
      <q-separator color="grey-4" />

      <q-card-section style="max-height: 60vh" class="scroll">
        <div class="row q-gutter-sm q-mb-sm">
          <q-space />
          <q-input
            standout
            dense
            v-model="filterKeyword"
            ref="filterRef"
            outlined
            placeholder="ค้นหา"
            debounce="300"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>
          <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>
        <d-table
          ref="table"
          flat
          bordered
          dense
          :columns="columns"
          :rows="rows"
          :paging="true"
          :rows-per-page-options="[10, 25, 50, 100]"
          :visible-columns="visibleColumns"
          v-model:pagination="historyPagination"
          :filter="filterKeyword.trim()"
        >
          >
          <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">
              <q-td v-for="col in props.cols" :key="col.id">
                <div>
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>
