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

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

import type { QTableColumn } from "quasar";
import type {
  DataOptionEducation,
  DataOptionEducationLevel,
} from "@/modules/04_registryPerson/interface/index/Main";
import type { RequestItemsObject } from "@/modules/04_registryPerson/interface/request/Education";
import type {
  ResponseObject,
  DataEducationLevel,
} from "@/modules/04_registryPerson/interface/response/Education";

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

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

const id = ref<string>(route.params.id.toString()); //id profile
const empType = ref<string>(pathRegistryEmp(route.name?.toString() ?? ""));
const dialog = ref<boolean>(false); //แสดง popup ข้อมูลประวัติการศึกษา
const dialogStatus = ref<string>("create"); //สถานะข้อมูลประวัติการศึกษา
const mode = ref<string>("table"); //การแสดงของ Table card

/** props*/
const isLeave = defineModel<boolean>("isLeave", {
  required: true,
});
const baseColumns = ref<QTableColumn[]>([
  {
    name: "educationLevel",
    align: "left",
    label: "ระดับการศึกษา",
    sortable: true,
    field: "educationLevel",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "institute",
    align: "left",
    label: "สถานศึกษา",
    sortable: true,
    field: "institute",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "startDate",
    align: "left",
    label: "ตั้งแต่",
    sortable: true,
    field: "startDate",
    format(val, row) {
      return row.startDate
        ? row.isDate
          ? date2Thai(row.startDate)
          : (new Date(row.startDate).getFullYear() + 543).toString()
        : "-";
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "endDate",
    align: "left",
    label: "ถึง",
    sortable: true,
    field: "endDate",
    format(val, row) {
      return row.endDate
        ? row.isDate
          ? date2Thai(row.endDate)
          : (new Date(row.endDate).getFullYear() + 543).toString()
        : "-";
    },
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "finishDate",
    align: "left",
    label: "วันที่สำเร็จการศึกษา",
    sortable: true,
    field: "finishDate",
    format: (v) => date2Thai(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "isEducation",
    align: "left",
    label: "เป็นวุฒิการศึกษาในตำแหน่ง",
    sortable: true,
    field: "isEducation",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => (v === true ? "ใช่" : "ไม่ใช่"),
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "isHigh",
    align: "left",
    label: "วุฒิการศึกษาสูงสุด",
    sortable: true,
    field: "isHigh",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => (v === true ? "ใช่" : v === false ? "ไม่ใช่" : "-"),
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "degree",
    align: "left",
    label: "วุฒิการศึกษา",
    sortable: true,
    field: "degree",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a
        .toString()
        .localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "field",
    align: "left",
    label: "สาขาวิชา/ทาง",
    sortable: true,
    field: "field",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "fundName",
    align: "left",
    label: "ทุน",
    sortable: true,
    field: "fundName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "gpa",
    align: "left",
    label: "เกรดเฉลี่ย",
    sortable: true,
    field: "gpa",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "country",
    align: "left",
    label: "ประเทศ",
    sortable: true,
    field: "country",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "other",
    align: "left",
    label: "ข้อมูลการติดต่อ",
    sortable: true,
    field: "other",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "duration",
    align: "left",
    label: "ระยะเวลา",
    sortable: true,
    field: "duration",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "durationYear",
    align: "left",
    label: "ระยะเวลาหลักสูตร (ปี)",
    sortable: true,
    field: "durationYear",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    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",
    format: (v) => date2Thai(v, false, true),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const baseVisibleColumns = ref<string[]>([
  "educationLevel",
  "institute",
  "degree",
  "field",
  "gpa",
  "country",
  "duration",
  "durationYear",
  "other",
  "fundName",
  "isEducation",
  "isHigh",
  "endDate",
  "startDate",
  "finishDate",
  "note",
  "lastUpdateFullName",
  "lastUpdatedAt",
]);

/** Table*/
const keyword = ref<string>("");
const rows = ref<ResponseObject[]>([]);
const rowsMain = ref<ResponseObject[]>([]);
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: "",
});

/** Table ประวัติแก้ไขประวัติการศึกษา*/
const historyColumns = ref<QTableColumn[]>(baseColumns.value);
const historyVisibleColumns = ref<string[]>(baseVisibleColumns.value);

const editId = ref<string>(""); //id ที่ต้องการแก้ไข
const isDate = ref<string>("false");

const educationOption = ref<DataOptionEducation[]>([
  { label: "ใช่", value: true },
  { label: "ไม่ใช่", value: false },
]);
const educationOptionFilter = ref<DataOptionEducation[]>([
  { label: "ใช่", value: true },
  { label: "ไม่ใช่", value: false },
]);

const educationLevelOption = ref<DataOptionEducationLevel[]>([]);
const educationLevelOptionFilter = ref<DataOptionEducationLevel[]>([]);

const historyDialog = ref<boolean>(false);
const educationData = reactive<RequestItemsObject>({
  isDate: isDate.value === "false" ? false : true,
  profileId: id.value,
  educationLevel: "",
  institute: "",
  startYear: new Date().getFullYear(),
  endYear: new Date().getFullYear(),
  finishDate: null,
  startDate: new Date(),
  endDate: new Date(),
  isEducation: null,
  isHigh: null,
  degree: "",
  field: "",
  fundName: "",
  gpa: "",
  country: "",
  other: "",
  duration: "",
  durationYear: null,
  note: "",
  educationLevelId: "",
  positionPath: "",
  positionPathId: "",
});

const modalSort = ref<boolean>(false);
const dataSort = ref<ResponseObject[]>([]);

/** function ยืนยันการบันทึกข้อมูล*/
function onSubmit() {
  dialogConfirm(
    $q,
    async () => {
      // showLoader();
      const isEdit = dialogStatus.value === "create" ? false : true;

      console.log("isEdit", isEdit);
      const url = isEdit
        ? config.API.profileNewEducationByEducationId(
            editId.value,
            empType.value
          )
        : config.API.profileNewEducation(empType.value);

      const method = isEdit ? http.patch : http.post;

      const body = {
        ...educationData,
        startYear: undefined,
        endYear: undefined,
        isDate: isDate.value === "false" ? false : true,
        profileId: isEdit
          ? undefined
          : empType.value === ""
          ? id.value
          : undefined,
        profileEmployeeId: isEdit
          ? undefined
          : empType.value !== ""
          ? id.value
          : undefined,
        durationYear: isEdit
          ? educationData.durationYear === ""
            ? null
            : educationData.durationYear
          : educationData.durationYear,
        finishDate: convertDateToAPI(educationData.finishDate),
        startDate: convertDateToAPI(educationData.startDate),
        endDate: convertDateToAPI(educationData.endDate),
      };

      await method(url, body)
        .then(async () => {
          await fetchData(id.value);
          success($q, "บันทึกข้อมูลสำเร็จ");
          closeDialog();
        })
        .catch((err) => {
          messageError($q, err);
        })
        .finally(() => {
          hideLoader();
        });
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}

/**
 * function ค้นหา คำใน option
 * @param val คำค้นหา
 * @param update function
 * @param refData type select
 */
function filterSelector(val: string, update: Function, refData: string) {
  switch (refData) {
    case "educationOption":
      update(() => {
        educationOption.value = educationOptionFilter.value.filter(
          (v: DataOptionEducation) => v.label.indexOf(val) > -1
        );
      });
      break;
    case "educationLevelOption":
      update(() => {
        educationLevelOption.value = educationLevelOptionFilter.value.filter(
          (v: DataOptionEducationLevel) => v.label.indexOf(val) > -1
        );
      });
      break;
    default:
      break;
  }
}

/** function เคลียร์ formData*/
function clearForm() {
  isDate.value = "false";
  educationData.educationLevel = "";
  educationData.institute = "";
  educationData.startYear = new Date().getFullYear();
  educationData.endYear = new Date().getFullYear();
  educationData.finishDate = null;
  educationData.startDate = new Date();
  educationData.endDate = new Date();
  educationData.isEducation = null;
  educationData.isHigh = false;
  educationData.degree = "";
  educationData.field = "";
  educationData.fundName = "";
  educationData.gpa = "";
  educationData.country = "";
  educationData.other = "";
  educationData.duration = "";
  educationData.durationYear = null;
  educationData.note = "";
}

/**
 * function แก้ไขข้อมูลประวัติการศึกษา
 * @param row ข้อมูลประวัติการศึกษา
 */
function editForm(row: any) {
  dialogStatus.value = "edit";
  editId.value = row?.id;
  isDate.value = row.isDate ? "true" : "false";

  educationData.educationLevel = row.educationLevel;
  educationData.institute = row.institute;
  educationData.finishDate = row.finishDate;
  educationData.startDate = row.startDate;
  educationData.endDate = row.endDate;
  educationData.isEducation = row.isEducation;
  educationData.isHigh = row.isHigh ? true : false;
  educationData.degree = row.degree;
  educationData.field = row.field;
  educationData.fundName = row.fundName;
  educationData.gpa = row.gpa;
  educationData.country = row.country;
  educationData.other = row.other;
  educationData.duration = row.duration;
  educationData.durationYear = row.durationYear;
  educationData.note = row.note;
  educationData.startYear =
    row.isDate == "true"
      ? row.startDate.slice(0, 4)
      : new Date(row.startDate).getFullYear();
  educationData.endYear =
    row.isDate == "true"
      ? row.endDate.slice(0, 4)
      : new Date(row.endDate).getFullYear();
  dialog.value = true;
}

/** function ปิด popup มูลประวัติการศึกษา*/
function closeDialog() {
  clearForm();
  dialog.value = false;
}

/**
 * function fetch ข้อมูลประวัตืการศึกษา
 * @param id บุคคล
 */
async function fetchData(id: string) {
  showLoader();
  await http
    .get(config.API.profileNewEducationByProfileId(id, empType.value))
    .then(async (res) => {
      rows.value = await res.data.result;
      rowsMain.value = await res.data.result;
      dataSort.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function fetch ข้อมูลระดับการศึกษา*/
function fetchEducationLevel() {
  http
    .get(config.API.orgEducationLevel)
    .then(async (res) => {
      res.data.result.map((r: DataEducationLevel) => {
        educationLevelOption.value.push({
          value: r.id,
          label: r.name,
        });
      });
      educationLevelOptionFilter.value = educationLevelOption.value;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

const historyId = ref<string>("");
/**
 * function fetch ประวัติการแก้ไขประวัติการศึกษา
 * @param id  ประวัติการศึกษา
 */
function onOpenHistoryData(id: string) {
  historyId.value = id;
  historyDialog.value = true;
}

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

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

/** ฟังก์ค้นหาข้อมูลรายการประวัติการศึกษา */
function serchDataTable() {
  rows.value = onSearchDataTable(
    keyword.value,
    rowsMain.value,
    columns.value ? columns.value : []
  );
}

/** ทำงานเมื่อ Components ถูกเรียกใช้งาน*/
onMounted(async () => {
  await fetchData(id.value);
  fetchEducationLevel();
});
</script>

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

    <q-btn
      v-if="
        isLeave == false &&
        checkPermission($route)?.attrIsUpdate &&
        empType === ''
      "
      round
      flat
      dense
      color="blue"
      icon="mdi-sort"
      @click="modalSort = true"
    >
      <q-tooltip>จัดลำดับข้อมูล</q-tooltip></q-btn
    >

    <q-space />
    <q-input
      dense
      outlined
      v-model="keyword"
      label="ค้นหา"
      @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="mode"
      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: mode === 'table' ? '#787B7C' : '#C9D3DB',
          }"
        />
      </template>

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

  <d-table
    :grid="mode === 'card'"
    ref="table"
    :columns="columns"
    :rows="rows"
    row-key="name"
    flat
    bordered
    :paging="true"
    dense
    class="custom-header-table"
    :visible-columns="visibleColumns"
    v-model:pagination="pagination"
  >
    <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="mode === 'table'">
      <q-tr :props="props">
        <q-td auto-width>
          <q-btn
            color="deep-purple"
            flat
            dense
            round
            icon="mdi-history"
            @click="() => onOpenHistoryData(props.row.id)"
          >
            <q-tooltip>ประวัติแก้ไขประวัติการศึกษา</q-tooltip>
          </q-btn>
          <q-btn
            v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
            flat
            dense
            round
            icon="edit"
            color="edit"
            @click="
              () => {
                editForm(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.id"
          :class="props.row.isEntry ? 'text-grey' : ''"
        >
          <div>
            {{ col.value === "" || col.value === null ? "-" : col.value }}
          </div>
        </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 align="right" class="bg-grey-3">
            <q-btn
              dense
              flat
              round
              color="deep-purple"
              icon="mdi-history"
              @click="() => onOpenHistoryData(props.row.id)"
            >
              <q-tooltip>ประวัติแก้ไขประวัติการศึกษา</q-tooltip>
            </q-btn>
            <q-btn
              v-if="isLeave == false && checkPermission($route)?.attrIsUpdate"
              dense
              flat
              round
              color="edit"
              icon="edit"
              @click="editForm(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="dialog" class="dialog" persistent>
    <q-card>
      <q-form @submit.prevent greedy @validation-success="onSubmit()">
        <DialogHeader
          :tittle="
            dialogStatus == 'edit'
              ? 'แก้ไขข้อมูลประวัติการศึกษา'
              : 'เพิ่มข้อมูลประวัติการศึกษา'
          "
          :close="closeDialog"
        />

        <q-separator />
        <q-card-section>
          <div class="row q-col-gutter-sm">
            <div class="col-6">
              <q-select
                outlined
                dense
                emit-value
                option-value="label"
                option-label="label"
                map-options
                bg-color="white"
                v-model="educationData.educationLevel"
                :options="educationLevelOption"
                input-debounce="0"
                use-input
                hide-selected
                fill-input
                @filter="(inputValue:string,
                    doneFn:Function) => filterSelector(inputValue, doneFn,'educationLevelOption'
                    ) "
                :rules="[(val:string) => !!val || `${'กรุณาเลือกระดับการศึกษา'}`]"
                label="ระดับการศึกษา"
                class="inputgreen"
                hide-bottom-space
              />
            </div>
            <div class="col-6">
              <q-input
                outlined
                v-model="educationData.institute"
                label="สถานศึกษา"
                bg-color="white"
                dense
                class="inputgreen"
                :rules="[(val:string) => !!val || `${'กรุณากรอกสถานศึกษา'}`]"
                hide-bottom-space
              />
            </div>
          </div>
          <q-card flat bordered class="q-px-md q-pb-md q-my-sm borderCard">
            <div class="row col-12 q-gutter-md q-py-sm text-grey-7">
              <q-radio
                v-model="isDate"
                checked-icon="task_alt"
                unchecked-icon="panorama_fish_eye"
                val="false"
                label="ปี"
                class="inputgreen"
                dense
              />
              <q-radio
                v-model="isDate"
                checked-icon="task_alt"
                unchecked-icon="panorama_fish_eye"
                val="true"
                class="inputgreen"
                label="วัน/เดือน/ปี"
                dense
              />
            </div>
            <div v-if="isDate === 'false'" class="row q-col-gutter-sm">
              <div class="col">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="educationData.startYear"
                  :locale="'th'"
                  autoApply
                  year-picker
                  :enableTimePicker="false"
                  @update:modelValue="
                  (v:number) =>
                    (educationData.startDate = new Date(
                      `${v}-01-01T00:00:02.010+07:00`
                    ))
                "
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      dense
                      outlined
                      class="inputgreen"
                      hide-bottom-space
                      :model-value="educationData.startYear + 543"
                      :rules="[
                        (val:string) => !!val || `${'กรุณาเลือกปีที่เริ่มต้นศึกษา'}`,
                      ]"
                      :label="`${'ปีที่เริ่มต้นศึกษา'}`"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
              <div class="col">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="educationData.endYear"
                  :locale="'th'"
                  autoApply
                  year-picker
                  :enableTimePicker="false"
                  @update:modelValue="
                  (v:number) =>
                    (educationData.endDate = new Date(
                      `${v}-01-01T00:00:02.010+07:00`
                    ))
                "
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      dense
                      class="inputgreen"
                      outlined
                      hide-bottom-space
                      :model-value="educationData.endYear + 543"
                      :rules="[
                        (val:string) => !!val || `${'กรุณาเลือกปีที่จบการศึกษา'}`,
                      ]"
                      :label="`${'ปีที่จบการศึกษา'}`"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          style="color: var(--q-primary)"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
            </div>
            <div v-if="isDate === 'true'" class="row q-col-gutter-sm">
              <div class="col">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="educationData.startDate"
                  :locale="'th'"
                  autoApply
                  :enableTimePicker="false"
                  week-start="0"
                  @update:modelValue="
                  (v: Date) =>
                    (educationData.startYear = 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
                      outlined
                      class="inputgreen"
                      dense
                      :model-value="date2Thai(educationData.startDate)"
                      :rules="[
                        (val:string) => !!val || `${'กรุณาเลือกวันที่เริ่มต้นศึกษา'}`,
                      ]"
                      hide-bottom-space
                      :label="`${'วันที่เริ่มต้นศึกษา'}`"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          color="primary"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
              <div class="col">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="educationData.endDate"
                  :locale="'th'"
                  autoApply
                  :enableTimePicker="false"
                  week-start="0"
                  @update:modelValue="
                  (v: Date)  =>
                    (educationData.endYear = 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
                      outlined
                      dense
                      class="inputgreen"
                      :model-value="date2Thai(educationData.endDate)"
                      :rules="[
                        (val:string) => !!val || `${'กรุณาเลือกวันที่จบการศึกษา'}`,
                      ]"
                      hide-bottom-space
                      :label="`${'วันที่จบการศึกษา'}`"
                    >
                      <template v-slot:prepend>
                        <q-icon
                          name="event"
                          class="cursor-pointer"
                          color="primary"
                        >
                        </q-icon>
                      </template>
                    </q-input>
                  </template>
                </datepicker>
              </div>
            </div>
          </q-card>
          <div class="row q-col-gutter-sm">
            <div class="col-6">
              <datepicker
                menu-class-name="modalfix"
                v-model="educationData.finishDate"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                week-start="0"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    outlined
                    bg-color="white"
                    dense
                    class="inputgreen"
                    :model-value="date2Thai(educationData.finishDate)"
                    hide-bottom-space
                    :label="`${'วันที่สำเร็จการศึกษา'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        color="primary"
                      >
                      </q-icon>
                    </template>
                    <template v-if="educationData.finishDate" v-slot:append>
                      <q-icon
                        name="cancel"
                        @click.stop.prevent="educationData.finishDate = null"
                        class="cursor-pointer"
                      />
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-6">
              <q-select
                outlined
                dense
                emit-value
                map-options
                bg-color="white"
                v-model="educationData.isEducation"
                :options="educationOption"
                option-value="value"
                class="inputgreen"
                option-label="label"
                input-debounce="0"
                use-input
                hide-selected
                fill-input
                @filter="(inputValue:string,
                    doneFn:Function) => filterSelector(inputValue, doneFn,'educationOption'
                    ) "
                label="เป็นวุฒิการศึกษาในตำแหน่ง"
                hide-bottom-space
                clearable
              />
            </div>

            <div class="col-6">
              <q-input
                outlined
                v-model="educationData.degree"
                label="วุฒิการศึกษา"
                class="inputgreen"
                bg-color="white"
                dense
                hide-bottom-space
              />
            </div>
            <div class="col-6">
              <q-input
                outlined
                class="inputgreen"
                v-model="educationData.field"
                label="สาขาวิชา/ทาง"
                bg-color="white"
                dense
                hide-bottom-space
              />
            </div>

            <div class="col-6">
              <q-input
                outlined
                v-model="educationData.fundName"
                label="ทุน"
                class="inputgreen"
                bg-color="white"
                dense
                hide-bottom-space
              />
            </div>
            <div class="col-6">
              <q-input
                outlined
                class="inputgreen"
                v-model="educationData.gpa"
                label="เกรดเฉลี่ย"
                bg-color="white"
                dense
                mask="#.##"
                hide-bottom-space
              />
            </div>

            <div class="col-6">
              <q-input
                outlined
                class="inputgreen"
                v-model="educationData.country"
                label="ประเทศ"
                bg-color="white"
                dense
                hide-bottom-space
              />
            </div>
            <div class="col-6">
              <q-input
                outlined
                class="inputgreen"
                v-model="educationData.other"
                label="ข้อมูลติดต่อ"
                bg-color="white"
                dense
                hide-bottom-space
              />
            </div>

            <div class="col-6">
              <q-input
                outlined
                class="inputgreen"
                v-model="educationData.duration"
                label="ระยะเวลา"
                bg-color="white"
                dense
                hide-bottom-space
              />
            </div>
            <div class="col-6">
              <q-input
                outlined
                class="inputgreen"
                v-model="educationData.durationYear"
                label="ระยะเวลาหลักสูตร (ปี)"
                bg-color="white"
                type="number"
                dense
                hide-bottom-space
              />
            </div>

            <div class="col-12">
              <q-checkbox
                keep-color
                color="primary"
                v-model="educationData.isHigh"
                label="วุฒิการศึกษาสูงสุด"
              />
            </div>

            <div class="col-12">
              <q-input
                outlined
                class="inputgreen"
                v-model="educationData.note"
                label="หมายเหตุ"
                bg-color="white"
                dense
                type="textarea"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />

        <q-card-actions align="right">
          <q-btn id="onSubmit" type="submit" label="บันทึก" color="public">
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <!-- ประวัติแก้ไขประวัติการศึกษา -->
  <DialogHistory
    v-model:modal="historyDialog"
    :columns="historyColumns"
    :visible-columns="historyVisibleColumns"
    :title="`ประวัติแก้ไขประวัติการศึกษา`"
    :fetch-data="fetchDataHistory"
  />

  <DialogSortEducation
    v-model:modal="modalSort"
    :data-sort="dataSort"
    :fetch-data="fetchData"
  />
</template>

<style scoped>
.borderCard {
  border: 1px solid #d0d0d0;
}

.bg-color {
  background-color: #fafafa;
}
</style>
