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

import { checkPermission } from "@/utils/permissions";
import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useInsigniaDataStore } from "@/modules/04_registryPerson/stores/insignia";
import http from "@/plugins/http";
import config from "@/app.config";

import type { QTableProps } from "quasar";
import type {
  DataOption,
  DataOptionInsignia,
  InsigniaOps,
} from "@/modules/04_registryPerson/interface/index/Main";
import type { RequestItemsObject } from "@/modules/04_registryPerson/interface/request/Insignia";
import type { ResponseObject } from "@/modules/04_registryPerson/interface/response/Insignia";

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

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

/**
 * props
 */
 const props = defineProps({
  isLeave:Boolean
});

const profileId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);
const empType = ref<string>(pathRegistryEmp(route.name?.toString() ?? ""));

const id = ref<string>(""); //id ที่ต้องการแก้ไข
const insigniaType = ref<string>(""); //ลำดับชั้น
const insigniaForm = reactive<RequestItemsObject>({
  year: 0, //ปีที่ยื่นขอพระราชทานเครื่องราชฯ
  receiveDate: null, //วันที่ได้รับ
  insigniaId: "", //ชื่อเครื่องราชฯ
  no: "", //ลำดับที่
  issue: "", //ราชกิจจาฯ ฉบับที่
  volumeNo: "", //เล่มที่
  volume: "", //เล่ม
  section: "", //ตอน
  page: "", //หน้า
  dateAnnounce: null, //วันที่ประกาศในราชกิจจาฯ
  refCommandNo: "", //เลขที่คำสั่ง
  refCommandDate: null, //'เอกสารอ้างอิง (ลง วัน/เดือน/ปี)'
  note: "", //หมายเหตุ
});

const isEdit = ref<boolean>(false); //สถานะการแก้ไขข้อมูล
const modal = ref<boolean>(false); //แสดง popup ข้อมูลเครื่องราชอิสริยาภรณ์
const modeView = ref<string>("table"); //การแสดงผล Table,Card
const modalHistory = ref<boolean>(false); //แสดง popup ประวัติแก้ไข
//ข้อมูลเครื่องราช
const OpsFilter = ref<InsigniaOps>({
  insigniaOptions: [],
});
//ต้วลือกรายการครื่องราช
const Ops = ref<InsigniaOps>({
  insigniaOptions: [],
});

//Table Main
const rows = ref<ResponseObject[]>([]);
const filterSearch = ref("");
const columns = ref<QTableProps["columns"]>([
  {
    name: "year",
    align: "left",
    label: "ปีที่ยื่นขอ",
    sortable: true,
    field: "year",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => v + 543,
  },
  {
    name: "receiveDate",
    align: "left",
    label: "วันที่ได้รับ",
    sortable: true,
    field: "receiveDate",
    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: "insignia",
    align: "left",
    label: "ชื่อเครื่องราชฯ",
    sortable: true,
    field: "insigniaId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => Ops.value.insigniaOptions.find((r) => r.id === v)?.name,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "insigniaType",
    align: "left",
    label: "ลำดับชั้น",
    sortable: true,
    field: (v) => v.insignia.insigniaType.name,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "no",
    align: "left",
    label: "ลำดับที่",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "issue",
    align: "left",
    label: "ราชกิจจาฯ ฉบับที่",
    sortable: true,
    field: "issue",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "volumeNo",
    align: "left",
    label: "เล่มที่",
    sortable: true,
    field: "volumeNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "volume",
    align: "left",
    label: "เล่ม",
    sortable: true,
    field: "volume",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "section",
    align: "left",
    label: "ตอน",
    sortable: true,
    field: "section",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "page",
    align: "left",
    label: "หน้า",
    sortable: true,
    field: "page",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateAnnounce",
    align: "left",
    label: "วันที่ประกาศในราชกิจจาฯ",
    sortable: true,
    field: "dateAnnounce",
    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: "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,
    field: "refCommandDate",
    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: "note",
    align: "left",
    label: "หมายเหตุ",
    sortable: true,
    field: "note",
    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[]>([
  "insignia",
  "insigniaType",
  "year",
  "no",
  "issue",
  "volumeNo",
  "volume",
  "section",
  "page",
  "receiveDate",
  "dateAnnounce",
  "refCommandNo",
  "refCommandDate",
  "note",
]);
const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});

//Table ประวัติแก้ไข
const rowsHistory = ref<RequestItemsObject[]>([]);
const filterHistory = ref<string>("");
const columnsHistory = ref<QTableProps["columns"]>([
  {
    name: "year",
    align: "left",
    label: "ปีที่ยื่นขอ",
    sortable: true,
    field: "year",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => v + 543,
  },
  {
    name: "receiveDate",
    align: "left",
    label: "ลงวันที่",
    sortable: true,
    field: "receiveDate",
    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: "insignia",
    align: "left",
    label: "ชื่อเครื่องราชฯ",
    sortable: true,
    field: "insigniaId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => Ops.value.insigniaOptions.find((r) => r.id === v)?.name,
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "insigniaType",
    align: "left",
    label: "ลำดับชั้น",
    sortable: true,
    field: (v) => v.insignia.insigniaType.name,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "no",
    align: "left",
    label: "ลำดับที่",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "issue",
    align: "left",
    label: "ราชกิจจาฯ ฉบับที่",
    sortable: true,
    field: "issue",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "volumeNo",
    align: "left",
    label: "เล่มที่",
    sortable: true,
    field: "volumeNo",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "volume",
    align: "left",
    label: "เล่ม",
    sortable: true,
    field: "volume",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "section",
    align: "left",
    label: "ตอน",
    sortable: true,
    field: "section",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "page",
    align: "left",
    label: "หน้า",
    sortable: true,
    field: "page",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateAnnounce",
    align: "left",
    label: "วันที่ประกาศในราชกิจจาฯ",
    sortable: true,
    field: "dateAnnounce",
    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: "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,
    field: "refCommandDate",
    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: "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",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v, false, true),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumnsHistory = ref<String[]>([
  "insignia",
  "insigniaType",
  "year",
  "no",
  "issue",
  "volumeNo",
  "volume",
  "section",
  "page",
  "receiveDate",
  "dateAnnounce",
  "refCommandNo",
  "refCommandDate",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);
const historyPagination = ref({
  page: 1,
  rowsPerPage: 10,
});

/**
 * fetch ข้อมูลรายการเครื่องราชอิสริยาภรณ์
 */
async function fetchData() {
  if (!profileId.value) return;
  showLoader();
  try {
    const res = await http.get(
      config.API.profileNewInsignByProfileId(profileId.value, empType.value)
    );
    rows.value = res.data.result;
  } catch (error) {
    messageError($q, error);
  } finally {
    hideLoader();
  }
}

/**
 * fetch ข้อมูลเครื่องราชอิสริยาภรณ์
 */
async function fetchInsignia() {
  showLoader();
  try {
    const res = await http.get(config.API.insigniaOrg);
    const data = res.data.result;
    mapInsigniaOption(data);
  } catch (error) {
    messageError($q, error);
  } finally {
    hideLoader();
  }
}

/**
 * บันทึกข้อมูลเครื่องราชอิสริยาภรณ์
 * @param editStatus แก้ไข,เพิ่ม
 */
async function addEditData(editStatus: boolean = false) {
  if (!profileId.value) return;
  showLoader();
  const url = editStatus
    ? config.API.profileNewInsignById(id.value, empType.value)
    : config.API.profileNewInsign(empType.value);
  const method = editStatus ? "patch" : "post";
  const reqBody: RequestItemsObject = {
    ...insigniaForm,
    profileEmployeeId:
      !editStatus && empType.value !== "" ? profileId.value : undefined,
    profileId:
      !editStatus && empType.value === "" ? profileId.value : undefined,
  };
  try {
    await http[method](url, reqBody);
    await fetchData();
    await success($q, "บันทึกข้อมูลสำเร็จ");
    modal.value = false;
  } catch (e) {
    messageError($q, e);
  } finally {
    hideLoader();
  }
}

/**
 * เปิด form ข้อมูลเครื่องราชอิสริยาภรณ์
 */
function onClickOpenDialog(editStatus: boolean = false, row?: ResponseObject) {
  modal.value = true;
  isEdit.value = editStatus;

  if (editStatus && row) {
    id.value = row.id;
    insigniaType.value = row.insignia.insigniaType.name;
    insigniaForm.year = row.year;
    insigniaForm.no = row.no;
    insigniaForm.volume = row.volume;
    insigniaForm.section = row.section;
    insigniaForm.page = row.page;
    insigniaForm.receiveDate = row.receiveDate;
    insigniaForm.insigniaId = row.insigniaId;
    insigniaForm.dateAnnounce = row.dateAnnounce;
    insigniaForm.issue = row.issue;
    insigniaForm.volumeNo = row.volumeNo;
    insigniaForm.refCommandDate = row.refCommandDate;
    insigniaForm.refCommandNo = row.refCommandNo;
    insigniaForm.note = row.note;
  } else {
    clearData();
  }
}

/**
 * ปิด form ข้อมูลเครื่องราชอิสริยาภรณ์
 */
function clickClose() {
  clearData();
  modal.value = false;
}

/**
 * fetch ช้อมูลประวัติการแก้ไขรายการข้อมูลเครื่องราชอิสริยาภรณ์
 */
async function clickHistory(row: ResponseObject) {
  modalHistory.value = true;
  filterSearch.value = "";
  showLoader();
  try {
    const res = await http.get(
      config.API.profileNewInsignHisById(row.id, empType.value)
    );
    rowsHistory.value = res.data.result;
  } catch (e) {
    messageError($q, e);
  } finally {
    hideLoader();
  }
}

/**
 * ยืนยีนการบันทึกข้อมูล
 */
function onSubmit() {
  dialogConfirm(
    $q,
    () => {
      addEditData(isEdit.value);
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}

/**
 * ฟิลเตอร์ข้อมูลจาก input
 * @param val ค่าที่ป้อนให้ input
 * @param update function จาก quasar
 * @param refData type ที่กำหนด ของ input นั้นๆ
 */
function filterSelector(val: string, update: Function, refData: string) {
  switch (refData) {
    case "insigniaOptions":
      update(() => {
        Ops.value.insigniaOptions = OpsFilter.value.insigniaOptions.filter(
          (v: DataOption) => v.name.indexOf(val) > -1
        );
      });
      break;
    default:
      break;
  }
}

/**
 * ค้นหาลำดับชั้น
 */
function insigniaTypeSelection() {
  const insigniaTypeFilter = Ops.value.insigniaOptions.filter(
    (r: DataOptionInsignia) => r.id === insigniaForm.insigniaId
  );
  if (insigniaTypeFilter.length > 0) {
    insigniaType.value = insigniaTypeFilter[0].typeName;
  }
}

/**
 * เคลียร์ formDฟta
 */
function clearData() {
  id.value = "";
  (insigniaType.value = ""), (insigniaForm.year = 0);
  insigniaForm.receiveDate = null;
  insigniaForm.insigniaId = "";
  insigniaForm.no = "";
  insigniaForm.issue = "";
  insigniaForm.volumeNo = "";
  insigniaForm.volume = "";
  insigniaForm.section = "";
  insigniaForm.page = "";
  insigniaForm.dateAnnounce = null;
  insigniaForm.refCommandNo = "";
  insigniaForm.refCommandDate = null;
  insigniaForm.note = "";
}

/**
 * ทำงานเมื่อ Components ถูกเรียกใช้งาน
 */
onMounted(async () => {
  await fetchData();
  store.insigniaOption.length === 0 ? await fetchInsignia() : "";
  Ops.value.insigniaOptions = store.insigniaOption;
  OpsFilter.value.insigniaOptions = store.insigniaOption;
});
</script>

<template>
  <div class="row items-center q-gutter-x-sm q-pb-sm">
    <q-btn
      v-if="props.isLeave == false && checkPermission($route)?.attrIsUpdate"
      dense
      color="primary"
      icon="add"
      flat
      round
      @click="onClickOpenDialog()"
      ><q-tooltip>เพิ่มข้อมูล</q-tooltip></q-btn
    >

    <q-space />
    <q-input
      standout
      dense
      v-model="filterSearch"
      ref="filterRef"
      outlined
      placeholder="ค้นหา"
      debounce="300"
    >
      <template v-slot:append>
        <q-icon
          v-if="filterSearch == ''"
          name="search"
          @click.stop.prevent="filterSearch = ''"
          class="cursor-pointer"
        />
        <q-icon
          v-if="filterSearch"
          name="cancel"
          @click.stop.prevent="filterSearch = ''"
          class="cursor-pointer"
        />
      </template>
    </q-input>
    <q-select
      v-if="modeView == 'table'"
      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"
    />
    <q-btn-toggle
      v-model="modeView"
      dense
      class="no-shadow toggle-borderd"
      toggle-color="grey-4"
      :options="[
        { value: 'table', slot: 'table' },
        { value: 'card', slot: 'card' },
      ]"
    >
      <template v-slot:table>
        <q-icon
          name="format_list_bulleted"
          size="24px"
          :style="{
            color: modeView === 'table' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>

      <template v-slot:card>
        <q-icon
          name="mdi-view-grid-outline"
          size="24px"
          :style="{
            color: modeView === 'card' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>
    </q-btn-toggle>
  </div>

  <d-table
    flat
    dense
    bordered
    :rows="rows"
    :paging="true"
    :columns="columns"
    :filter="filterSearch"
    v-model:pagination="pagination"
    :grid="modeView === 'card'"
    :visible-columns="visibleColumns"
    :rows-per-page-options="[20, 50, 100]"
    :card-container-class="modeView === 'card' ? 'q-col-gutter-md' : ''"
  >
    <template v-slot:header="props">
      <q-tr :props="props">
        <q-th auto-width />
        <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" v-if="modeView === 'table'">
      <q-tr :props="props">
        <q-td auto-width>
          <q-btn
            flat
            dense
            round
            color="deep-purple"
            icon="mdi-history"
            @click="clickHistory(props.row)"
          >
            <q-tooltip>ประวัติแก้ไขเครื่องราชอิสริยาภรณ์</q-tooltip>
          </q-btn>

          <q-btn
            v-if="props.isLeave == false && checkPermission($route)?.attrIsUpdate"
            flat
            dense
            round
            color="edit"
            icon="edit"
            @click="onClickOpenDialog(true, props.row)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
        </q-td>
        <q-td v-for="col in props.cols" :key="col.name" :props="props">
          <div class="table_ellipsis">
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
      </q-tr>
    </template>

    <template v-slot:item="props" v-else>
      <div class="col-xs-12 col-sm-6 col-md-6">
        <q-card bordered>
          <q-card-actions class="bg-grey-3" align="right">
            <q-btn
              flat
              round
              color="deep-purple"
              icon="mdi-history"
              @click="clickHistory(props.row)"
            >
              <q-tooltip>ประวัติแก้ไขเครื่องราชอิสริยาภรณ์</q-tooltip>
            </q-btn>
            <q-btn
              v-if="props.isLeave == false && checkPermission($route)?.attrIsUpdate"
              flat
              round
              color="edit"
              icon="edit"
              @click="onClickOpenDialog(true, props.row)"
            >
              <q-tooltip>แก่ไขข้อมุล</q-tooltip>
            </q-btn>
          </q-card-actions>
          <q-separator />
          <div>
            <q-item
              v-for="(col, index) in props.cols.filter(
                (col:any) => col.name !== 'desc'
              )"
              :key="col.name"
              :class="index % 2 !== 0 ? 'bg-grey-1' : ''"
            >
              <q-item-section class="text-grey-6">
                <q-item-label>{{ col.label }}</q-item-label>
              </q-item-section>

              <q-item-section class="text-dark">
                <q-item-label>
                  {{ col.value ? col.value : "-" }}
                </q-item-label>
              </q-item-section>
            </q-item>
          </div>
        </q-card>
      </div>
    </template>
  </d-table>

  <q-dialog v-model="modal" persistent>
    <q-card>
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader
          :tittle="
            isEdit
              ? 'แก้ไขข้อมูลเครื่องราชอิสริยาภรณ์'
              : 'เพิ่มข้อมูลเครื่องราชอิสริยาภรณ์'
          "
          :close="clickClose"
        />
        <q-separator />
        <q-card-section>
          <div class="row col-12 q-col-gutter-sm">
            <div class="col-xs-6 col-sm-6 col-md-6">
              <datepicker
                autoApply
                year-picker
                v-model="insigniaForm.year"
                week-start="0"
                menu-class-name="modalfix"
                :locale="'th'"
                :enableTimePicker="false"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    dense
                    outlined
                    hide-bottom-space
                    class="inputgreen"
                    :model-value="insigniaForm.year !== 0 ? (insigniaForm.year as number) + 543 : null"
                    :rules="[
                    (val:string) =>
                      !!val ||
                      `${'กรุณาเลือกปีที่ยื่นขอพระราชทานเครื่องราชฯ'}`,
                  ]"
                    :label="`${'ปีที่ยื่นขอพระราชทานเครื่องราชฯ'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      />
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <datepicker
                autoApply
                borderless
                week-start="0"
                menu-class-name="modalfix"
                v-model="insigniaForm.receiveDate"
                :locale="'th'"
                :enableTimePicker="false"
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    dense
                    outlined
                    hide-bottom-space
                    class="inputgreen"
                    for="inputDatereceive"
                    ref="dateReceivedRef"
                    :model-value="
                    insigniaForm.receiveDate != null
                      ? date2Thai(insigniaForm.receiveDate as Date)
                      : null
                  "
                    :label="`${'วันที่ได้รับ'}`"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือกวันที่ได้รับ'}`]"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      />
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <selector
                dense
                outlined
                use-input
                emit-value
                lazy-rules
                map-options
                hide-bottom-space
                option-value="id"
                input-debounce="0"
                option-label="name"
                v-model="insigniaForm.insigniaId"
                class="inputgreen"
                :label="`${'ชื่อเครื่องราชฯ'}`"
                :options="Ops.insigniaOptions"
                :rules="[(val:string) => !!val || `${'กรุณาเลือกชื่อเครื่องราชฯ'}`]"
                @filter="(inputValue:string,
                    doneFn:Function) => filterSelector(inputValue, doneFn,'insigniaOptions'
                    ) "
                @update:modelValue="insigniaTypeSelection"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                dense
                readonly
                outlined
                lazy-rules
                hide-bottom-space
                v-model="insigniaType"
                :label="`${'ลำดับชั้น'}`"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="insigniaForm.no"
                class="inputgreen"
                :label="`${'ลำดับที่'}`"
                :rules="[(val:string) => !!val || `${'กรุณากรอกลำดับที่'}`]"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="insigniaForm.issue"
                class="inputgreen"
                :label="`${'ราชกิจจาฯ ฉบับที่'}`"
                :rules="[(val:string) => !!val || `${'กรุณากรอกราชกิจจาฯ ฉบับที่'}`]"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="insigniaForm.volumeNo"
                class="inputgreen"
                :label="`${'เล่มที่'}`"
                :rules="[(val:string) => !!val || `${'กรุณากรอกเล่มที่'}`]"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="insigniaForm.volume"
                class="inputgreen"
                :label="`${'เล่ม'}`"
                :rules="[(val:string) => !!val || `${'กรุณากรอกเล่ม'}`]"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="insigniaForm.section"
                class="inputgreen"
                :label="`${'ตอน'}`"
                :rules="[(val:string) => !!val || `${'กรุณากรอกตอน'}`]"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                dense
                lazy-rules
                outlined
                hide-bottom-space
                v-model="insigniaForm.page"
                class="inputgreen"
                :label="`${'หน้า'}`"
                :rules="[(val:string) => !!val || `${'กรุณากรอกหน้า'}`]"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <datepicker
                autoApply
                week-start="0"
                v-model="insigniaForm.dateAnnounce"
                menu-class-name="modalfix"
                :locale="'th'"
                :enableTimePicker="false"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    dense
                    outlined
                    hide-bottom-space
                    class="inputgreen"
                    :model-value="date2Thai(insigniaForm.dateAnnounce as Date)"
                    :label="`${'วันที่ประกาศในราชกิจจาฯ'}`"
                    :rules="[
                    (val:string) =>
                      !!val || `${'กรุณาเลือกวันที่ประกาศในราชกิจจาฯ'}`,
                  ]"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      />
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                v-model="insigniaForm.refCommandNo"
                class="inputgreen"
                :label="`${'เลขที่คำสั่ง'}`"
              >
                <template v-slot:append>
                  <q-icon name="mdi-file" class="cursor-pointer" />
                </template>
              </q-input>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <datepicker
                autoApply
                week-start="0"
                v-model="insigniaForm.refCommandDate"
                menu-class-name="modalfix"
                :locale="'th'"
                :enableTimePicker="false"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    dense
                    outlined
                    clearable
                    hide-bottom-space
                    class="inputgreen"
                    :label="`${'เอกสารอ้างอิง (ลง วัน/เดือน/ปี)'}`"
                    :model-value="
                    date2Thai(insigniaForm.refCommandDate as Date)
                  "
                    @clear="insigniaForm.refCommandDate = null"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      />
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-input
                dense
                outlined
                hide-bottom-space
                v-model="insigniaForm.note"
                class="inputgreen"
                label="หมายเหตุ"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn label="บันทึก" id="onSubmit" type="submit" color="public">
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <q-dialog v-model="modalHistory" persistent>
    <q-card style="min-width: 80%">
      <DialogHeader
        tittle="ประวัติแก้ไขเครื่องราชอิสริยาภรณ์"
        :close="() => ((modalHistory = false), (rowsHistory = []))"
      />
      <q-separator />

      <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="filterHistory"
            ref="filterRef"
            outlined
            placeholder="ค้นหา"
            debounce="300"
          >
            <template v-slot:append>
              <q-icon
                v-if="filterHistory == ''"
                name="search"
                @click.stop.prevent="filterHistory = ''"
                class="cursor-pointer"
              />
              <q-icon
                v-if="filterHistory"
                name="cancel"
                @click.stop.prevent="filterHistory = ''"
                class="cursor-pointer"
              />
            </template>
          </q-input>
          <q-select
            v-model="visibleColumnsHistory"
            multiple
            outlined
            dense
            options-dense
            :display-value="$q.lang.table.columns"
            emit-value
            map-options
            :options="columnsHistory"
            option-value="name"
            options-cover
            style="min-width: 150px"
          />
        </div>
        <d-table
          ref="table"
          flat
          bordered
          v-model:pagination="historyPagination"
          dense
          :columns="columnsHistory"
          :rows="rowsHistory"
          :paging="true"
          :rows-per-page-options="[10, 25, 50, 100]"
          :visible-columns="visibleColumnsHistory"
          :filter="filterHistory"
        >
          >
          <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>

<style lang="scss"></style>
