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

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 { QTableColumn } from "quasar";
import type {
  DataOption,
  InsigniasType,
  InsigniasTypeSub,
  ResFileData,
} 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";
import DialogHistory from "@/modules/04_registryPerson/components/detail/DialogHistory.vue";

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

const isUpload = ref<boolean>(false);
const fileUpload = ref<File | null>(null);
const fileData = ref<ResFileData | null>(null);
const uploadUrl = ref<string>("");
/** props*/
const isLeave = defineModel<boolean>("isLeave", {
  required: true,
});

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 insigniaOptions = ref<InsigniasType[]>([]);
const insigniaOptionsMain = ref<InsigniasType[]>([]);
const insigniaOptionsName = ref<InsigniasTypeSub[]>([]);
const insigniaOptionsNameMain = ref<InsigniasTypeSub[]>([]);

//Table Main
const baseColumns = ref<QTableColumn[]>([
  {
    name: "year",
    align: "left",
    label: "ปีที่ยื่นขอ",
    sortable: true,
    field: "year",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => (v ? v + 543 : "-"),
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    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) => store.allNameInsignia.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: "insigniaType",
    format(val, row) {
      return row.insignia ? row.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" }),
  },
  {
    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 baseVisibleColumns = ref<string[]>([
  "insignia",
  "insigniaType",
  "year",
  "no",
  "issue",
  "volumeNo",
  "volume",
  "section",
  "page",
  "receiveDate",
  "dateAnnounce",
  "refCommandNo",
  "refCommandDate",
  "note",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);

const rows = ref<ResponseObject[]>([]);
const rowsMain = ref<ResponseObject[]>([]);
const filterSearch = ref<string>("");
const columns = ref<QTableColumn[]>(
  baseColumns.value.filter((e: QTableColumn) => e.name !== "lastUpdateFullName")
);
const visibleColumns = ref<string[]>(
  baseVisibleColumns.value.filter((e: string) => e !== "lastUpdateFullName")
);
const pagination = ref({
  sortBy: "lastUpdatedAt",
});

//Table ประวัติแก้ไข
const historyId = ref<string>("");
const columnsHistory = ref<QTableColumn[]>(baseColumns.value);
const visibleColumnsHistory = ref<string[]>(baseVisibleColumns.value);

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

/** ดึง */
async function getInsigniaActive() {
  showLoader();
  http
    .get(config.API.orgInsigniaActive())
    .then((res) => {
      const data = res.data.result;
      mapInsigniaOption(data);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .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,
    isUpload: !isEdit.value ? undefined : isUpload.value,
    profileEmployeeId:
      !editStatus && empType.value !== "" ? profileId.value : undefined,

    profileId:
      !editStatus && empType.value === "" ? profileId.value : undefined,
  };
  try {
    await http[method](url, reqBody).then(async (res) => {
      if (fileUpload.value) {
        await uploadProfile(editStatus ? id.value : res.data.result);
      }
    });

    await fetchData();
    await success($q, "บันทึกข้อมูลสำเร็จ");
    modal.value = false;
  } catch (e) {
    messageError($q, e);
  } finally {
    hideLoader();
  }
}

/**
 * ฟังก์ชันส้ราง Path อัปโหลดไฟล์
 * @param id
 */
async function uploadProfile(id: string) {
  await http
    .post(
      config.API.subFile("ทะเบียนประวัติ", "เครื่องราชฯ", profileId.value, id),
      {
        replace: true,
        fileList: [
          {
            fileName: "เอกสารหลักฐาน",
          },
        ],
      }
    )
    .then(async (res) => {
      uploadUrl.value = res.data["เอกสารหลักฐาน"].uploadUrl;
      await uploadFileURL(uploadUrl.value, fileUpload.value, id);
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/**
 * ฟังก์ชันอัปโหลดำไฟล์
 * @param uploadUrl Path อัปโหลดไฟล์
 * @param file ไฟล์เอกสาร
 */
async function uploadFileURL(uploadUrl: string, file: any, id: string) {
  await axios
    .put(uploadUrl, file, {
      headers: {
        "Content-Type": file.type,
      },
    })
    .then(async (res) => {
      if (res.status == 200) {
        await isUploadFn(id);
      }
      fileUpload.value = null;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

async function isUploadFn(id: string) {
  await http
    .patch(config.API.profileNewInsignById(id, empType.value), {
      isUpload: fileUpload.value ? true : false,
    })
    .then(async (res) => {})

    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ฟังก์ชันโหลไฟลเอกสารหลักฐาน
 * @param id รายการที่ต้องการโหลด
 */
async function onDownloadFile(id: string, isLoad: boolean = true) {
  showLoader();
  await http
    .get(
      config.API.subFileByFileName(
        "ทะเบียนประวัติ",
        "เครื่องราชฯ",
        profileId.value,
        id,
        "เอกสารหลักฐาน"
      )
    )
    .then(async (res) => {
      const data = res.data;
      fileData.value = data;
      if (isLoad) {
        window.open(data.downloadUrl, "_blank");
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .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.id;
    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;
    isUpload.value = row.isUpload;

    if (isUpload.value) {
      onDownloadFile(row.id, false);
    }
    const list = store.insigniaTypeOpMain;

    const insigniaTypeFilter = list.filter(
      (r: InsigniasType) => r.id === insigniaType.value
    );
    if (insigniaTypeFilter.length > 0) {
      const type = insigniaTypeFilter;
      const name = insigniaTypeFilter[0].insignias.map(
        (item: InsigniasTypeSub) => ({
          ...item,
          name: `${item.name} (${item.shortName})`,
        })
      );
      insigniaOptions.value = type;
      insigniaOptionsMain.value = type;
      insigniaOptionsName.value = name;
      insigniaOptionsNameMain.value = name;
    }
  } else {
    clearData();
  }
}

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

/** fetch ช้อมูลประวัติการแก้ไขรายการข้อมูลเครื่องราชอิสริยาภรณ์ */
async function clickHistory(row: ResponseObject) {
  modalHistory.value = true;
  filterSearch.value = "";
  historyId.value = row.id;
}

async function fetchDataHistory() {
  showLoader();
  try {
    const res = await http.get(
      config.API.profileNewInsignHisById(historyId.value, empType.value)
    );
    return 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) {
  if (refData == "type") {
    update(() => {
      insigniaOptions.value = store.insigniaTypeOpMain.filter(
        (v: DataOption) => v.name.indexOf(val) > -1
      );
    });
  } else if (refData == "insigniaOptions") {
    update(() => {
      insigniaOptionsName.value = insigniaOptionsNameMain.value.filter(
        (v: DataOption) => v.name.indexOf(val) > -1
      );
    });
  }
}

/** ค้นหาลำดับชั้น*/
function insigniaTypeSelection(check: boolean, id: string) {
  if (check) {
    insigniaForm.insigniaId = "";
    console.log(store.insigniaTypeOpMain);

    const data = store.insigniaTypeOpMain.find(
      (item: InsigniasType) => item.id == id
    );
    if (data) {
      const listData = data.insignias.map((item: InsigniasTypeSub) => ({
        id: item.id,
        createdAt: item.createdAt,
        createdUserId: item.createdUserId,
        lastUpdatedAt: item.lastUpdatedAt,
        lastUpdateUserId: item.lastUpdateUserId,
        createdFullName: item.createdFullName,
        lastUpdateFullName: item.lastUpdateFullName,
        name: `${item.name} (${item.shortName})`,
        shortName: item.shortName,
        level: item.level,
        isActive: item.isActive,
        note: item.note,
        insigniaTypeId: item.insigniaTypeId,
      }));
      insigniaOptionsNameMain.value = listData;
    }
  }
}

/** เคลียร์ formData*/
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 = "";
  fileUpload.value = null;
  isUpload.value = false;
  fileData.value = null;
}

function serchDataTable() {
  rows.value = onSearchDataTable(
    filterSearch.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

function handleDelete(rowId: string) {
  dialogRemove($q, async () => {
    showLoader();
    try {
      await http.patch(
        config.API.profileNewInsignUpdateDelete(empType.value) + `${rowId}`
      );
      await fetchData();
      success($q, "ลบข้อมูลสำเร็จ");
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
    }
  });
}

/** ทำงานเมื่อ Components ถูกเรียกใช้งาน*/
onMounted(async () => {
  await fetchData();
  store.insigniaTypeOpMain.length === 0 ? await getInsigniaActive() : "";

  insigniaOptionsMain.value = store.insigniaTypeOpMain;
  insigniaOptions.value = store.insigniaOption;
});
</script>

<template>
  <div class="row items-center q-gutter-x-sm q-pb-sm">
    <q-btn
      v-if="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="ค้นหา"
      @keydown.enter.prevent="serchDataTable"
    >
      <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"
    />
    <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"
    :columns="columns"
    v-model:pagination="pagination"
    :grid="modeView === 'card'"
    :visible-columns="visibleColumns"
  >
    <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-th auto-width></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="isLeave == false && checkPermission($route)?.attrIsUpdate"
            flat
            dense
            round
            color="edit"
            icon="edit"
            @click="onClickOpenDialog(true, props.row)"
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>

          <q-btn
            v-if="isLeave == false && checkPermission($route)?.attrIsDelete"
            color="red"
            flat
            dense
            round
            icon="delete"
            @click="handleDelete(props.row.id)"
          >
            <q-tooltip>ลบข้อมูล</q-tooltip>
          </q-btn>
        </q-td>
        <q-td
          v-for="col in props.cols"
          :key="col.name"
          :props="props"
          :class="props.row.isEntry ? 'text-grey' : ''"
        >
          <div class="table_ellipsis">
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
        <q-td auto-width>
          <q-btn
            v-if="props.row.isUpload == true"
            color="green"
            flat
            dense
            round
            icon="mdi-file-document-outline"
            @click="onDownloadFile(props.row.id)"
          >
            <q-tooltip>ดาวน์โหลด</q-tooltip>
          </q-btn>
        </q-td>
      </q-tr>
    </template>

    <template v-slot:item="props" v-else>
      <div class="q-pa-xs col-xs-12 col-sm-4 col-md-3">
        <q-card flat bordered>
          <q-card-actions class="bg-grey-3" align="right">
            <q-btn
              v-if="props.row.isUpload"
              color="green"
              flat
              dense
              round
              icon="mdi-file-document-outline"
              @click="onDownloadFile(props.row.id)"
            >
              <q-tooltip>ดาวน์โหลด</q-tooltip>
            </q-btn>
            <q-btn
              flat
              round
              color="deep-purple"
              icon="mdi-history"
              @click="clickHistory(props.row)"
            >
              <q-tooltip>ประวัติแก้ไขเครื่องราชอิสริยาภรณ์</q-tooltip>
            </q-btn>

            <q-btn
              v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
              flat
              round
              color="edit"
              icon="edit"
              @click="onClickOpenDialog(true, props.row)"
            >
              <q-tooltip>แก้ไขข้อมูล</q-tooltip>
            </q-btn>

            <q-btn
              v-if="isLeave == false && checkPermission($route)?.attrIsDelete"
              color="red"
              flat
              round
              icon="delete"
              @click="handleDelete(props.row.id)"
            >
              <q-tooltip>ลบข้อมูล</q-tooltip>
            </q-btn>
          </q-card-actions>
          <q-separator />
          <q-list>
            <div
              :class="`row q-pa-sm`"
              :style="`background-color: ${index % 2 !== 0 ? '#FAFAFA' : ''}`"
              v-for="(col, index) in props.cols"
              :key="col.name"
            >
              <div class="col text-grey-6">
                <div>{{ col.label }}</div>
              </div>
              <div class="col">
                <div>{{ col.value ? col.value : "-" }}</div>
              </div>
            </div>
          </q-list>
        </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 ? year + 543 : "-"
                }}</template>
                <template #year-overlay-value="{ value }">{{
                  value ? parseInt(value + 543) : "-"
                }}</template>
                <template #trigger>
                  <q-input
                    dense
                    outlined
                    hide-bottom-space
                    class="inputgreen"
                    :model-value="insigniaForm.year != null && 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">
              <q-select
                dense
                outlined
                use-input
                hide-selected
                fill-input
                emit-value
                lazy-rules
                map-options
                hide-bottom-space
                option-value="id"
                input-debounce="0"
                option-label="name"
                v-model="insigniaType"
                class="inputgreen"
                :label="`${'ลำดับชั้น'}`"
                :options="insigniaOptions"
                :rules="[(val:string) => !!val || `${'กรุณาเลือกลำดับชั้น'}`]"
                @filter="(inputValue:string,
                    doneFn:Function) => filterSelector(inputValue, doneFn,'type'
                    ) "
                @update:modelValue="(val:any)=>insigniaTypeSelection(true,val)"
              >
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-grey">
                      ไม่มีข้อมูล
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <q-select
                dense
                outlined
                :readonly="insigniaType == ''"
                use-input
                hide-selected
                fill-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="insigniaOptionsName"
                :rules="[(val:string) => !!val || `${'กรุณาเลือกชื่อเครื่องราชฯ'}`]"
                @filter="(inputValue:string,
                    doneFn:Function) => filterSelector(inputValue, doneFn,'insigniaOptions'
                    ) "
              >
                <template v-slot:no-option>
                  <q-item>
                    <q-item-section class="text-grey">
                      ไม่มีข้อมูล
                    </q-item-section>
                  </q-item>
                </template>
              </q-select>
            </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 class="col-xs-12 col-sm-12 col-md-12">
              <div class="row">
                <q-uploader
                  v-if="!isUpload"
                  color="gray"
                  type="file"
                  flat
                  ref="uploader"
                  class="full-width"
                  text-color="white"
                  :max-size="10000000"
                  accept=".pdf"
                  bordered
                  label="[ไฟล์ pdf ขนาดไม่เกิน 10MB]"
                  @added="(v:any) => (fileUpload = v[0])"
                >
                  <template v-slot:header="scope">
                    <div class="row no-wrap items-center q-pa-sm q-gutter-xs">
                      <q-btn
                        v-if="scope.queuedFiles.length > 0"
                        icon="clear_all"
                        @click="scope.removeQueuedFiles"
                        round
                        dense
                        flat
                      >
                        <q-tooltip>ลบทั้งหมด</q-tooltip>
                      </q-btn>
                      <q-btn
                        v-if="scope.uploadedFiles.length > 0"
                        icon="done_all"
                        @click="scope.removeUploadedFiles"
                        round
                        dense
                        flat
                      >
                        <q-tooltip>ลบไฟล์ที่อัปโหลด</q-tooltip>
                      </q-btn>
                      <q-spinner
                        v-if="scope.isUploading"
                        class="q-uploader__spinner"
                      />
                      <div class="col">
                        <div class="q-uploader__title">
                          {{ "[ไฟล์ .pdf ขนาดไม่เกิน 10MB]" }}
                        </div>
                        <div class="q-uploader__subtitle">
                          {{ scope.uploadSizeLabel }} /
                          {{ scope.uploadProgressLabel }}
                        </div>
                      </div>
                      <q-btn
                        v-if="scope.canAddFiles"
                        type="a"
                        icon="add_box"
                        @click="scope.pickFiles"
                        round
                        dense
                        flat
                      >
                        <q-uploader-add-trigger />
                        <q-tooltip>เลือกไฟล์</q-tooltip>
                      </q-btn>
                      <q-btn
                        v-if="scope.isUploading"
                        icon="clear"
                        @click="scope.abort"
                        round
                        dense
                        flat
                      >
                        <q-tooltip>ยกเลิกการอัปโหลด</q-tooltip>
                      </q-btn>
                    </div>
                  </template>
                </q-uploader>

                <q-list bordered dense separator v-else class="full-width">
                  <q-item>
                    <q-item-section> {{ fileData?.fileName }}</q-item-section>
                    <q-item-section avatar>
                      <div class="row">
                        <q-btn
                          flat
                          round
                          color="primary"
                          icon="mdi-download"
                          @click="onDownloadFile(id)"
                        />

                        <q-btn
                          flat
                          round
                          color="grey"
                          icon="close"
                          @click="isUpload = false"
                        />
                      </div>
                    </q-item-section>
                  </q-item>
                </q-list>
              </div>
            </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>

  <DialogHistory
    v-model:modal="modalHistory"
    :visible-columns="visibleColumnsHistory"
    :title="`ประวัติแก้ไขเครื่องราชอิสริยาภรณ์`"
    :columns="columnsHistory"
    :fetch-data="fetchDataHistory"
    :type="'insignia'"
  />
</template>

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