<script setup lang="ts">
import { ref, onMounted, 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 http from "@/plugins/http";
import config from "@/app.config";

import type { QTableColumn } from "quasar";
import type { RequestItemsObject } from "@/modules/04_registryPerson/interface/request/DeclarationHonor";
import type {
  DataOption,
  ResFileData,
} from "@/modules/04_registryPerson/interface/index/Main";
import type { ResponseObject } from "@/modules/04_registryPerson/interface/response/DeclarationHonor";

import DialogHeader from "@/components/DialogHeader.vue";
import DialogHistory from "@/modules/04_registryPerson/components/detail/DialogHistory.vue";

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

const profileId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);
const empType = ref<string>(pathRegistryEmp(route.name?.toString() ?? ""));
const isUpload = ref<boolean>(false);
const fileUpload = ref<File | null>(null);
const fileData = ref<ResFileData | null>(null);
/** props*/
const isLeave = defineModel<boolean>("isLeave", {
  required: true,
});

const uploadUrl = ref<string>("");

const typeOp = ref<DataOption[]>([
  {
    id: "CER_RETIRE",
    name: "ประกาศเกียรติคุณประเภทที่ 4 ชั้นที่ 1 (เกษียณอายุราชการ)",
  },
  {
    id: "CER_20YEAR",
    name: "ประกาศเกียรติคุณประเภทที่ 4 ชั้นที่ 2 (ปฏิบัติหน้าที่ราชการครบ 20 ปีบริบูรณ์)",
  },
  { id: "OUTSTAND", name: "ข้าราชการกรุงเทพมหานครสามัญดีเด่น" },
]);
const id = ref<string>(""); //id ที่ต้องการแก้ไข
const issueDateYear = ref<number>(0); //ปีที่ได้รับ
const declHonorForm = reactive<RequestItemsObject>({
  type: "", //ประเภท
  isDate: "false", //ปี
  issuer: "", //ผู้มีอำนาจลงนาม
  detail: "", //รายละเอียด
  issueDate: null, //ปีที่ได้รับ
  refCommandNo: "", //เลขที่คำสั่ง
  refCommandDate: null, //'เอกสารอ้างอิง (ลงวันที่)'
});

const isEdit = ref<boolean>(false); //สถานะการแก้ไขข้อมูล
const modal = ref<boolean>(false); //แสดง popup ข้อมูลประกาศเกียรติคุณ
const modeView = ref<string>("table"); //การแสดงผล Table,Card
const modalHistory = ref<boolean>(false); //แสดง popup ประวัติแก้ไข

//Table Main
const baseColumns = ref<QTableColumn[]>([
  {
    name: "issueDate",
    align: "left",
    label: "วันที่ได้รับ",
    sortable: true,
    field: "issueDate",
    format(val, row) {
      return row.isDate
        ? date2Thai(row.issueDate).toString()
        : (new Date(row.issueDate).getFullYear() + 543).toString();
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "issuer",
    align: "left",
    label: "ผู้มีอำนาจลงนาม",
    sortable: true,
    field: "issuer",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    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: "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 baseVisibleColumns = ref<string[]>([
  "issuer",
  "detail",
  "issueDate",
  "refCommandNo",
  "refCommandDate",
  "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.profileNewHonorByProfileId(profileId.value, empType.value)
    );
    rowsMain.value = res.data.result;
    serchDataTable();
  } 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.profileNewHonorById(id.value, empType.value)
    : config.API.profileNewHonor(empType.value);
  const method = editStatus ? "patch" : "post";
  const reqBody = {
    ...declHonorForm,
    isUpload: !isEdit.value ? undefined : isUpload.value,
    profileEmployeeId:
      !editStatus && empType.value !== "" ? profileId.value : undefined,
    profileId:
      !editStatus && empType.value === "" ? profileId.value : undefined,
    isDate: declHonorForm.isDate === "true" ? true : false,
    issueDate:
      declHonorForm.isDate === "true"
        ? convertDateToAPI(declHonorForm.issueDate)
        : convertDateToAPI(new Date(`${issueDateYear.value}-01-01`)),
    refCommandDate: convertDateToAPI(declHonorForm.refCommandDate),
  };
  try {
    await http[method](url, reqBody).then(async (res) => {
      if (fileUpload.value) {
        await uploadProfile(editStatus ? id.value : res.data.result);
      }
    });
    await fetchData();
    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.profileNewHonorById(id, empType.value), {
      isUpload: fileUpload.value ? true : false,
      // isDate: declHonorForm.isDate === "true" ? 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;

    issueDateYear.value = new Date(row.issueDate).getFullYear();
    declHonorForm.issuer = row.issuer;
    declHonorForm.detail = row.detail;
    declHonorForm.issueDate = row.issueDate;
    declHonorForm.refCommandNo = row.refCommandNo;
    declHonorForm.refCommandDate = row.refCommandDate;
    declHonorForm.type = row.type;
    declHonorForm.isDate = row.isDate ? "true" : "false";

    isUpload.value = row.isUpload;

    if (isUpload.value) {
      onDownloadFile(row.id, false);
    }
  } else {
    clearData();
  }
}

/** ปิด form ข้อมูลประกาศเกียรติคุณ*/
async function clickClose() {
  clearData();
  modal.value = false;
}

/** fetch ช้อมูลประวัติการแก้ไขรายการข้อมูลประกาศเกียรติคุณ*/
async function clickHistory(row: ResponseObject) {
  historyId.value = row.id;
  modalHistory.value = true;
}

async function fetchDataHistory() {
  showLoader();
  try {
    const res = await http.get(
      config.API.profileNewHonorHisById(historyId.value, empType.value)
    );
    return res.data.result;
  } catch (e) {
    messageError($q, e);
  } finally {
    hideLoader();
  }
}

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

/** เคลียร์ formDฟta*/
function clearData() {
  id.value = "";
  issueDateYear.value = new Date().getFullYear();
  declHonorForm.issuer = "";
  declHonorForm.detail = "";
  declHonorForm.issueDate = new Date();
  declHonorForm.refCommandNo = "";
  declHonorForm.type = "";
  declHonorForm.refCommandDate = null;
  declHonorForm.isDate = "false";

  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.profileNewHonorUpdateDelete(empType.value) + `${rowId}`
      );
      await fetchData();
      success($q, "ลบข้อมูลสำเร็จ");
    } catch (err) {
      messageError($q, err);
    } finally {
      hideLoader();
    }
  });
}

/** ทำงานเมื่อ Components ถูกเรียกใช้งาน*/
onMounted(() => {
  fetchData();
});
</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"
    :grid="modeView === 'card'"
    v-model:pagination="pagination"
    :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-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 && 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 == true"
              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.stop.prevent="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 && checkPermission($route)?.attrIsDelete"
              color="red"
              flat
              dense
              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="row col-12 q-gutter-md q-py-sm text-grey-7">
              <q-radio
                v-model="(declHonorForm.isDate as string)"
                dense
                checked-icon="task_alt"
                unchecked-icon="panorama_fish_eye"
                val="false"
                label="ปี"
              />
              <q-radio
                v-model="(declHonorForm.isDate as string)"
                checked-icon="task_alt"
                unchecked-icon="panorama_fish_eye"
                val="true"
                label="วัน/เดือน/ปี"
                dense
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <datepicker
                autoApply
                year-picker
                v-model="issueDateYear"
                week-start="0"
                menu-class-name="modalfix"
                :locale="'th'"
                :enableTimePicker="false"
                @update:modelValue="
                  (v:number) =>
                    (declHonorForm.issueDate = new Date(
                      `${v}-01-01T00:00:02.010+07:00`
                    ))
                "
                v-if="declHonorForm.isDate === '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="issueDateYear + 543"
                    :rules="[
                    (val:string) =>
                      !!val ||
                      `${'กรุณาเลือกปีที่ได้รับ'}`,
                  ]"
                    :label="`${'ปีที่ได้รับ'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      />
                    </template>
                  </q-input>
                </template>
              </datepicker>
              <datepicker
                autoApply
                borderless
                v-else
                week-start="0"
                menu-class-name="modalfix"
                v-model="declHonorForm.issueDate"
                :locale="'th'"
                :enableTimePicker="false"
                @update:modelValue="
                  (v: Date) =>
                    (issueDateYear = parseInt(
                      v.toString().slice(11, 15)
                    ))
                "
              >
                <template #year="{ year }">
                  {{ year + 543 }}
                </template>
                <template #year-overlay-value="{ value }">
                  {{ parseInt(value + 543) }}
                </template>
                <template #trigger>
                  <q-input
                    dense
                    outlined
                    hide-bottom-space
                    for="inputDatereceive"
                    ref="dateReceivedRef"
                    class="inputgreen"
                    :model-value="date2Thai(declHonorForm.issueDate)"
                    :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
                class="inputgreen"
                v-model="declHonorForm.issuer"
                :label="`${'ผู้มีอำนาจลงนาม'}`"
              />
            </div>
            <div class="col-12">
              <q-select
                outlined
                dense
                label="ประเภท"
                v-model="declHonorForm.type"
                :options="typeOp"
                option-label="name"
                option-value="id"
                class="inputgreen"
                emit-value
                map-options
              >
              </q-select>
            </div>
            <div class="col-12">
              <q-input
                dense
                outlined
                lazy-rules
                hide-bottom-space
                class="inputgreen"
                v-model="declHonorForm.detail"
                :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
                class="inputgreen"
                v-model="declHonorForm.refCommandNo"
                :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
                borderless
                week-start="0"
                menu-class-name="modalfix"
                v-model="declHonorForm.refCommandDate"
                :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"
                    :model-value="
                      declHonorForm.refCommandDate == null
                        ? null
                        : date2Thai(declHonorForm.refCommandDate)
                    "
                    :label="`${'เอกสารอ้างอิง (ลงวันที่)'}`"
                    @clear="declHonorForm.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-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 color="grey-4" />
        <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"
  />
</template>

<style scoped></style>
