<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import dialogHeader from "@/components/DialogHeader.vue";
import type { QTableProps } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useRoute } from "vue-router";
import type { RequestItemsObject } from "@/modules/04_registryNew/interface/request/Training";
import type { ResponseObject } from "@/modules/04_registryNew/interface/response/Training";
import { QForm, useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

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

const route = useRoute();
const id = ref<string>(route.params.id.toString());
const dialog = ref<boolean>(false);
const mode = ref<string>("table");
const columns = ref<QTableProps["columns"]>([
  {
    name: "name",
    align: "left",
    label: "ชื่อโครงการ/หลักสูตรการฝึกอบรม",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "topic",
    align: "left",
    label: "หัวข้อการฝึกอบรม/ดูงาน",
    sortable: true,
    field: "topic",
    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: (v) =>
      v.isDate
        ? date2Thai(v.startDate)
        : new Date(v.startDate).getFullYear() + 543,
    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: (v) =>
      v.isDate ? date2Thai(v.endDate) : new Date(v.endDate).getFullYear() + 543,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "yearly",
    align: "left",
    label: "ปีที่อบรม (พ.ศ.)",
    sortable: true,
    field: "yearly",
    format: (v) => (v !== null ? v + 543 : "-"),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "place",
    align: "left",
    label: "สถานที่ฝึกอบรม/ดูงาน",
    sortable: true,
    field: "place",
    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: "department",
    align: "left",
    label: "หน่วยงานที่รับผิดชอบจัดการฝึกอบรม/ดูงาน",
    sortable: true,
    field: "department",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "numberOrder",
    align: "left",
    label: "เลขที่คำสั่ง/เลขที่หนังสืออนุมัติ",
    sortable: true,
    field: "numberOrder",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateOrder",
    align: "left",
    label: "คำสั่งลงวันที่/หนังสืออนุมัติลงวันที่",
    sortable: true,
    field: "dateOrder",
    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" }),
  },
]);
const historyColumns = ref<QTableProps["columns"]>([
  {
    name: "name",
    align: "left",
    label: "ชื่อโครงการ/หลักสูตรการฝึกอบรม",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "topic",
    align: "left",
    label: "หัวข้อการฝึกอบรม/ดูงาน",
    sortable: true,
    field: "topic",
    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: (v) =>
      v.isDate
        ? date2Thai(v.startDate)
        : new Date(v.startDate).getFullYear() + 543,
    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: (v) =>
      v.isDate ? date2Thai(v.endDate) : new Date(v.endDate).getFullYear() + 543,
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "yearly",
    align: "left",
    label: "ปีที่อบรม (พ.ศ.)",
    sortable: true,
    field: "yearly",
    format: (v) => (v !== null ? v + 543 : "-"),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "place",
    align: "left",
    label: "สถานที่ฝึกอบรม/ดูงาน",
    sortable: true,
    field: "place",
    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: "department",
    align: "left",
    label: "หน่วยงานที่รับผิดชอบจัดการฝึกอบรม/ดูงาน",
    sortable: true,
    field: "department",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "numberOrder",
    align: "left",
    label: "เลขที่คำสั่ง/เลขที่หนังสืออนุมัติ",
    sortable: true,
    field: "numberOrder",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateOrder",
    align: "left",
    label: "คำสั่งลงวันที่/หนังสืออนุมัติลงวันที่",
    sortable: true,
    field: "dateOrder",
    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: "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),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const isDate = ref<string>("false");
const dialogStatus = ref<string>("create");
const historyDialog = ref<boolean>(false);
const editId = ref<string>("");
const keyword = ref<string>("");
const historyKeyword = ref<string>("");
const trainData = reactive<RequestItemsObject>({
  profileId: id.value,
  name: "",
  topic: "",
  yearly: null,
  place: "",
  duration: "",
  department: "",
  numberOrder: "",
  dateOrder: null,
  startDate: new Date(),
  endDate: new Date(),
  startYear: new Date().getFullYear(),
  finishYear: new Date().getFullYear(),
  isDate: isDate.value === "false" ? false : true,
});

const pagination = ref({
  page: 1,
  rowsPerPage: 10,
});

const historyPagination = ref({
  page: 1,
  rowsPerPage: 10,
});

const rows = ref<ResponseObject[]>([]);
const historyRows = ref<ResponseObject[]>([]);

const visibleColumns = ref<string[]>([
  "name", // ชื่อโครงงาน
  "topic", // หัวข้อ
  "yearly", // ปีที่อบรม
  "place", // สถานที่
  "duration", // รวมระยะเวลา
  "department", // หน่วยงานที่รับผิดชอบ
  "numberOrder", // เลขที่คำสั่ง
  "dateOrder", // คำสั่งลงวันที่
  "startDate", // วันเริ่มต้น
  "endDate", // วันสิ้นสุด
]);

const historyVisibleColumns = ref<string[]>([
  "name", // ชื่อโครงงาน
  "topic", // หัวข้อ
  "yearly", // ปีที่อบรม
  "place", // สถานที่
  "duration", // รวมระยะเวลา
  "department", // หน่วยงานที่รับผิดชอบ
  "numberOrder", // เลขที่คำสั่ง
  "dateOrder", // คำสั่งลงวันที่
  "startDate", // วันเริ่มต้น
  "endDate", // วันสิ้นสุด
  "lastUpdateFullName", // แก้ไขโดย
  "lastUpdatedAt", // แก้ไขเมื่อวันที่
]);

async function onSubmit() {
  dialogConfirm(
    $q,
    async () => {
      dialogStatus.value === "create" ? addData() : editData(editId.value);
      closeDialog();
    },
    "ยืนยันการบันทึกข้อมูล",
    "ต้องการยืนยันการบันทึกข้อมูลนี้หรือไม่ ?"
  );
}

function clearForm() {
  isDate.value = "false";
  trainData.name = "";
  trainData.topic = "";
  trainData.yearly = null;
  trainData.place = "";
  trainData.duration = "";
  trainData.department = "";
  trainData.numberOrder = "";
  trainData.dateOrder = new Date();
  trainData.startDate = new Date();
  trainData.endDate = new Date();
}

function editForm(row: any) {
  dialogStatus.value = "edit";
  editId.value = row.id;
  isDate.value = row.isDate ? "true" : "false";
  trainData.name = row.name;
  trainData.topic = row.topic;
  trainData.yearly = row.yearly;
  trainData.place = row.place;
  trainData.duration = row.duration;
  trainData.department = row.department;
  trainData.numberOrder = row.numberOrder;
  trainData.dateOrder = row.dateOrder;
  trainData.startDate = row.startDate;
  trainData.endDate = row.endDate;
  trainData.startYear = +row.startDate.slice(0, 4);
  trainData.finishYear = +row.endDate.slice(0, 4);
  dialog.value = true;
}

async function addData() {
  await http
    .post(config.API.profileNewTraining, {
      ...trainData,
      startYear: undefined,
      finishYear: undefined,
      isDate: isDate.value === "false" ? false : true,
    })
    .then(() => {
      fetchData(id.value);
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function editData(idData: string) {
  await http
    .patch(config.API.profileNewTrainingByTrainingId(idData), {
      ...trainData,
      profileId: undefined,
      startYear: undefined,
      finishYear: undefined,
      isDate: isDate.value === "false" ? false : true,
    })
    .then(() => {
      fetchData(id.value);
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function deleteData(idData: string) {
  dialogRemove($q, () =>
    http
      .delete(config.API.profileNewTrainingByTrainingId(idData))
      .then(() => {
        fetchData(id.value);
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      })
  );
}

function closeDialog() {
  clearForm();
  dialog.value = false;
}
function closeHistoryDialog() {
  historyDialog.value = false;
}

async function fetchData(id: string) {
  showLoader();
  await http
    .get(config.API.profileNewTrainingByProfileId(id))
    .then(async (res) => {
      rows.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function fetchHistoryData(id: string) {
  showLoader();
  await http
    .get(config.API.profileNewTrainingHisByTrainingId(id))
    .then(async (res) => {
      historyRows.value = res.data.result;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

onMounted(async () => {
  await fetchData(id.value);
});
</script>

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

    <q-space />
    <q-input dense outlined v-model="keyword" label="ค้นหา">
      <template v-slot:append>
        <q-icon name="search" />
      </template>
    </q-input>
    <q-select
      v-if="mode === 'table'"
      v-model="visibleColumns"
      multiple
      outlined
      dense
      options-dense
      :display-value="$q.lang.table.columns"
      emit-value
      map-options
      :options="columns"
      option-value="name"
      options-cover
      style="min-width: 150px"
    />

    <q-btn-toggle
      v-model="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
    :filter="keyword"
    :rows-per-page-options="[20, 50, 100]"
    v-model:pagination="pagination"
    class="custom-header-table"
    :visible-columns="visibleColumns"
  >
    <template v-slot:header="props">
      <q-tr :props="props">
        <q-th v-for="col in props.cols" :key="col.name" :props="props">
          <span class="text-weight-medium">{{ col.label }}</span>
        </q-th>
        <q-th auto-width />
      </q-tr>
    </template>
    <template v-slot:body="props" v-if="mode === 'table'">
      <q-tr :props="props" class="cursor-pointer">
        <q-td v-for="col in props.cols" :key="col.id">
          <div>
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
        <q-td auto-width>
          <q-btn
            color="primary"
            flat
            dense
            round
            class="q-mr-xs"
            size="14px"
            icon="mdi-pencil-outline"
            clickable
            @click="
              () => {
                editForm(props.row);
              }
            "
          >
            <q-tooltip>แก้ไขข้อมูล</q-tooltip>
          </q-btn>
          <q-btn
            color="info"
            flat
            dense
            round
            size="14px"
            icon="mdi-history"
            @click="
              () => (fetchHistoryData(props.row.id), (historyDialog = true))
            "
          >
            <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-6 col-md-6 col-lg-6 grid-style-transition"
      >
        <q-card bordered>
          <q-card-actions align="right" class="bg-grey-3">
            <q-btn
              flat
              round
              size="14px"
              color="primary"
              icon="mdi-pencil-outline"
              @click="editForm(props.row)"
            >
              <q-tooltip>แก้ไขข้อมูล</q-tooltip>
            </q-btn>
            <q-btn
              flat
              round
              size="14px"
              color="info"
              icon="history"
              @click="
                () => (fetchHistoryData(props.row.id), (historyDialog = true))
              "
            >
              <q-tooltip>ประวัติแก้ไขการฝึกอบรม/ดูงาน</q-tooltip>
            </q-btn>
          </q-card-actions>
          <q-separator />
          <q-list>
            <div
              v-for="(col, index) in props.cols"
              :key="col.name"
              :style="`background-color: ${index % 2 !== 0 ? '#FAFAFA' : ''}`"
            >
              <div class="row q-pa-sm">
                <div class="col-7 label-color">
                  <div>{{ col.label }}</div>
                </div>
                <div class="col">
                  <div>{{ col.value }}</div>
                </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()">
        <dialog-header
          :tittle="
            dialogStatus == 'edit'
              ? 'แก้ไขการฝึกอบรม/ดูงาน'
              : 'เพิ่มการฝึกอบรม/ดูงาน'
          "
          :close="closeDialog"
        />
        <q-separator color="grey-4" />
        <q-card-section style="max-height: 55vh" class="scroll">
          <div class="row q-mb-sm q-gutter-sm">
            <div class="col">
              <q-input
                outlined
                v-model="trainData.name"
                label="ชื่อโครงการ/หลักสูตรการฝึกอบรม"
                bg-color="white"
                dense
                class="inputgreen"
                :rules="[
                  (val) =>
                    !!val || `${'กรุณากรอกชื่อโครงการ/หลักสูตรการฝึกอบรม'}`,
                ]"
                hide-bottom-space
              />
            </div>
            <div class="col">
              <q-input
                outlined
                class="inputgreen"
                v-model="trainData.topic"
                label="หัวข้อการฝึกอบรม/ดูงาน"
                bg-color="white"
                dense
                :rules="[
                  (val) => !!val || `${'กรุณากรอกหัวข้อการฝึกอบรม/ดูงาน'}`,
                ]"
                hide-bottom-space
              />
            </div>
          </div>
          <q-card flat bordered class="q-px-sm q-my-sm q-pb-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="ปี"
                dense
              />
              <q-radio
                v-model="isDate"
                checked-icon="task_alt"
                unchecked-icon="panorama_fish_eye"
                val="true"
                label="วัน/เดือน/ปี"
                dense
              />
            </div>
            <div v-if="isDate === 'false'" class="row q-gutter-sm">
              <div class="col">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="trainData.startYear"
                  :locale="'th'"
                  autoApply
                  year-picker
                  :enableTimePicker="false"
                  @update:modelValue="
                  (v:number) =>
                    (trainData.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="trainData.startYear + 543"
                      :rules="[
                        (val) =>
                          !!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="trainData.finishYear"
                  :locale="'th'"
                  autoApply
                  year-picker
                  :enableTimePicker="false"
                  @update:modelValue="
                  (v:number) =>
                    (trainData.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="trainData.finishYear + 543"
                      :rules="[
                        (val) =>
                          !!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-gutter-sm">
              <div class="col">
                <datepicker
                  menu-class-name="modalfix"
                  v-model="trainData.startDate"
                  :locale="'th'"
                  autoApply
                  :enableTimePicker="false"
                  week-start="0"
                  @update:modelValue="
                  (v: Date) =>
                    (trainData.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
                      dense
                      class="inputgreen"
                      :model-value="date2Thai(trainData.startDate)"
                      :rules="[
                        (val) =>
                          !!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="trainData.endDate"
                  :locale="'th'"
                  autoApply
                  :enableTimePicker="false"
                  week-start="0"
                  @update:modelValue="
                  (v: Date)  =>
                    (trainData.finishYear = 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(trainData.endDate)"
                      :rules="[
                        (val) =>
                          !!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-mb-sm q-gutter-sm">
            <div class="col">
              <datepicker
                menu-class-name="modalfix"
                v-model="trainData.yearly"
                :locale="'th'"
                autoApply
                year-picker
                :enableTimePicker="false"
                @update:modelValue="trainData.yearly"
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    dense
                    outlined
                    class="inputgreen"
                    clearable
                    @clear="() => (trainData.yearly = null)"
                    hide-bottom-space
                    :model-value="
                      !!trainData.yearly ? trainData.yearly + 543 : null
                    "
                    :label="`${'ปีงบประมาณ'}`"
                    @update:modelValue="trainData.yearly = null"
                  >
                    <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">
              <q-input
                outlined
                v-model="trainData.place"
                label="สถานที่ฝึกอบรม/ดูงาน"
                bg-color="white"
                class="inputgreen"
                dense
                :rules="[
                  (val) => !!val || `${'กรุณากรอกสถานที่ฝึกอบรม/ดูงาน'}`,
                ]"
                hide-bottom-space
              />
            </div>
          </div>
          <div class="row q-mb-sm q-gutter-sm">
            <div class="col">
              <q-input
                outlined
                class="inputgreen"
                v-model="trainData.duration"
                label="รวมระยะเวลาในการฝึกอบรม/ดูงาน"
                bg-color="white"
                dense
              />
            </div>
            <div class="col">
              <q-input
                outlined
                class="inputgreen"
                v-model="trainData.department"
                label="หน่วยงานที่รับผิดชอบจัดการฝึกอบรม/ดูงาน"
                bg-color="white"
                dense
              />
            </div>
          </div>
          <div class="row q-mb-sm q-gutter-sm">
            <div class="col">
              <q-input
                class="inputgreen"
                outlined
                v-model="trainData.numberOrder"
                label="เลขที่คำสั่ง/เลขที่หนังสืออนุมัติ"
                bg-color="white"
                dense
              />
            </div>
            <div class="col">
              <datepicker
                menu-class-name="modalfix"
                v-model="trainData.dateOrder"
                :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
                    dense
                    class="inputgreen"
                    clearable
                    @clear="() => (trainData.dateOrder = null)"
                    @update:modelValue="trainData.dateOrder = null"
                    :model-value="date2Thai(trainData.dateOrder)"
                    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-section>
        <q-separator color="grey-4" />
        <q-card-actions align="right">
          <q-btn
            dense
            unelevated
            label="บันทึก"
            id="onSubmit"
            type="submit"
            color="public"
            class="q-px-md"
          >
            <q-tooltip>บันทึกข้อมูล</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>

  <q-dialog v-model="historyDialog" class="dialog" persistent>
    <q-card style="min-width: 80%">
      <dialog-header
        tittle="ประวัติแก้ไขการฝึกอบรม/ดูงาน"
        :close="closeHistoryDialog"
      />
      <q-separator color="grey-4" />
      <q-card-section style="max-height: 60vh" class="scroll">
        <div class="row q-gutter-sm q-mb-sm">
          <q-space />
          <q-input
            dense
            outlined
            bg-color="white"
            v-model="historyKeyword"
            label="ค้นหา"
          >
            <template v-slot:append>
              <q-icon name="search" />
            </template>
          </q-input>

          <q-select
            v-model="historyVisibleColumns"
            multiple
            outlined
            dense
            bg-color="white"
            options-dense
            :display-value="$q.lang.table.columns"
            emit-value
            map-options
            :options="historyColumns"
            option-value="name"
            options-cover
            style="min-width: 150px"
          />
        </div>
        <d-table
          ref="table"
          :columns="historyColumns"
          :rows="historyRows"
          row-key="name"
          flat
          :filter="historyKeyword"
          v-model:pagination="historyPagination"
          bordered
          :paging="true"
          dense
          :rows-per-page-options="[10, 25, 50, 100]"
          class="custom-header-table"
          :visible-columns="historyVisibleColumns"
        >
          <template v-slot:header="props">
            <q-tr :props="props">
              <q-th v-for="col in props.cols" :key="col.name" :props="props">
                <span class="text-weight-medium">{{ col.label }}</span>
              </q-th>
              <q-th auto-width />
            </q-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props" class="cursor-pointer">
              <q-td v-for="col in props.cols" :key="col.id">
                <div>
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </q-card-section>
    </q-card>
  </q-dialog>
</template>

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

.label-color {
  color: #747474cc;
}

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