<script setup lang="ts">
import { ref, reactive, watch, 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: "startDate",
    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",
    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",
    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",
    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 trainData = reactive<RequestItemsObject>({
  name: "",
  topic: "",
  yearly: new Date().getFullYear(),
  place: "",
  duration: "",
  department: "",
  numberOrder: "",
  dateOrder: new Date(),
  startDate: new Date(),
  endDate: new Date(),
  startYear: new Date().getFullYear(),
  finishYear: new Date().getFullYear(),
});

const formFilter = reactive({
  page: 1,
  pageSize: 10,
  keyword: "",
});

const pagination = ref({
  page: formFilter.page,
  rowsPerPage: formFilter.pageSize,
});
const historyFormFilter = reactive({
  page: 1,
  pageSize: 10,
  keyword: "",
});

const historyPagination = ref({
  page: historyFormFilter.page,
  rowsPerPage: historyFormFilter.pageSize,
});

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", // วันสิ้นสุด
]);

function validateForm() {
  onSubmit();
}

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 = new Date().getFullYear();
  trainData.place = "";
  trainData.duration = "";
  trainData.department = "";
  trainData.numberOrder = "";
  trainData.dateOrder = new Date();
  trainData.startDate = new Date();
  trainData.endDate = new Date();
}

async function addData() {
  await http
    .post(config.API.profileNewTraining, {
      profileId: id.value,
      name: trainData.name,
      topic: trainData.topic ? trainData.topic : "",
      yearly: trainData.yearly,
      place: trainData.place ? trainData.place : "",
      duration: trainData.duration ? trainData.duration : "",
      department: trainData.department ? trainData.department : "",
      numberOrder: trainData.numberOrder ? trainData.numberOrder : "",
      dateOrder: trainData.dateOrder,
      startDate: trainData.startDate,
      endDate: trainData.endDate,
      isDate: isDate.value === "true" ? true : false,
      isActive: 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), {
      profileId: id.value,
      name: trainData.name,
      topic: trainData.topic ? trainData.topic : "",
      yearly: trainData.yearly,
      place: trainData.place ? trainData.place : "",
      duration: trainData.duration ? trainData.duration : "",
      department: trainData.department ? trainData.department : "",
      numberOrder: trainData.numberOrder ? trainData.numberOrder : "",
      dateOrder: trainData.dateOrder,
      startDate: trainData.startDate,
      endDate: trainData.endDate,
      isDate: isDate.value === "true" ? true : false,
      isActive: true,
    })
    .then(() => {
      fetchData(id.value);
      success($q, "บันทึกข้อมูลสำเร็จ");
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

async function deleteData(idData: string) {
  await http
    .delete(config.API.profileNewTrainingByTrainingId(idData))
    .then(() => {
      fetchData(id.value);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}
function closeDialog() {
  clearForm();
  dialog.value = false;
}
function closeHistoryDialog() {
  historyDialog.value = false;
}

watch(
  () => isDate.value,
  () => {
    if (isDate.value === "false") {
      console.log(trainData.startDate);
      trainData.startYear = +trainData.startDate.toString().slice(11, 15);
      trainData.finishYear = +trainData.endDate.toString().slice(11, 15);
      trainData.startDate = new Date(trainData.startYear + "-01-01");
      trainData.endDate = new Date(trainData.finishYear + "-01-01");
    } else {
      trainData.startDate = new Date(trainData.startYear + "-01-01");
      trainData.endDate = new Date(trainData.finishYear + "-01-01");
    }
  }
);

watch(
  () => trainData.startYear,
  () => {
    if (isDate.value === "false") {
      trainData.startDate = new Date(trainData.startYear + "-01-01");
    }
  }
);
watch(
  () => trainData.finishYear,
  () => {
    if (isDate.value === "false") {
      trainData.endDate = new Date(trainData.finishYear + "-01-01");
    }
  }
);

watch(
  () => trainData.startDate,
  () => {
    if (isDate.value === "true") {
      trainData.startYear = +trainData.startDate.toString().slice(11, 15);
    }
  }
);
watch(
  () => trainData.endDate,
  () => {
    if (isDate.value === "true") {
      trainData.finishYear = +trainData.endDate.toString().slice(11, 15);
    }
  }
);

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;
      console.log(historyRows.value);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

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

<template>
  <q-toolbar style="padding: 0px">
    <q-btn
      round
      flat
      color="primary"
      icon="add"
      size="16px"
      @click="
        () => {
          dialogStatus = 'create';
          clearForm;
          dialog = true;
        }
      "
    >
      <q-tooltip>เพิ่มข้อมูล</q-tooltip></q-btn
    >

    <q-space />
    <q-input
      dense
      outlined
      v-model="formFilter.keyword"
      label="ค้นหา"
      class="q-mr-sm"
    >
      <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"
      class="q-mr-sm"
    />

    <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>
  </q-toolbar>

  <d-table
    :grid="mode === 'card'"
    ref="table"
    :columns="columns"
    :rows="rows"
    row-key="name"
    flat
    bordered
    :paging="true"
    dense
    :filter="formFilter.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 v-if="col.name === 'startDate' || col.name === 'endDate'">
            <div v-if="props.row.isDate">{{ date2Thai(col.value) }}</div>
            <div v-else>
              {{ +col.value.slice(0, 4) + 543 }}
            </div>
          </div>
          <div v-else-if="col.name === 'dateOrder'">
            {{ date2Thai(col.value) }}
          </div>
          <div v-else-if="col.name === 'yearly'">{{ col.value + 543 }}</div>
          <div v-else>
            {{ col.value ? col.value : "-" }}
          </div>
        </q-td>
        <q-td auto-width>
          <q-btn
            color="edit"
            flat
            dense
            round
            class="q-mr-xs"
            size="14px"
            icon="edit"
            clickable
            @click="
              () => {
                dialogStatus = 'edit';
                editId = props.row.id;
                isDate = props.row.isDate ? 'true' : 'false';
                trainData.name = props.row.name;
                trainData.topic = props.row.topic;
                trainData.yearly = props.row.yearly;
                trainData.place = props.row.place;
                trainData.duration = props.row.duration;
                trainData.department = props.row.department;
                trainData.numberOrder = props.row.numberOrder;
                trainData.dateOrder = props.row.dateOrder;
                trainData.startDate = props.row.startDate;
                trainData.endDate = props.row.endDate;
                trainData.startYear = +props.row.startDate.slice(0, 4);
                trainData.finishYear = +props.row.endDate.slice(0, 4);
                dialog = true;
              }
            "
          >
            <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-btn
            color="red"
            flat
            dense
            round
            size="12px"
            icon="mdi-delete"
            clickable
            @click.stop="
              dialogRemove($q, async () => await deleteData(props.row.id))
            "
            v-close-popup
          >
            <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
              color="primary"
              icon="edit"
              @click="
                dialogStatus = 'edit';
                editId = props.row.id;
                isDate = props.row.isDate ? 'true' : 'false';
                trainData.name = props.row.name;
                trainData.topic = props.row.topic;
                trainData.yearly = props.row.yearly;
                trainData.place = props.row.place;
                trainData.duration = props.row.duration;
                trainData.department = props.row.department;
                trainData.numberOrder = props.row.numberOrder;
                trainData.dateOrder = props.row.dateOrder;
                trainData.startDate = props.row.startDate;
                trainData.endDate = props.row.endDate;
                trainData.startYear = +props.row.startDate.slice(0, 4);
                trainData.finishYear = +props.row.endDate.slice(0, 4);
                dialog = true;
              "
            >
              <q-tooltip>แก้ไขข้อมูล</q-tooltip>
            </q-btn>
            <q-btn
              flat
              round
              color="blue"
              icon="history"
              @click="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
                v-if="col.name === 'startDate' || col.name === 'endDate'"
                class="row q-pa-sm"
              >
                <div class="col-7 label-color">
                  <div>{{ col.label }}</div>
                </div>
                <div class="col">
                  <div v-if="props.row.isDate">
                    {{ date2Thai(col.value) }}
                  </div>
                  <div v-else>{{ +col.value.slice(0, 4) + 543 }}</div>
                </div>
              </div>
              <div v-else-if="col.name === 'dateOrder'" class="row q-pa-sm">
                <div class="col-7 label-color">
                  <div>{{ col.label }}</div>
                </div>
                <div class="col">
                  <div>{{ date2Thai(col.value) }}</div>
                </div>
              </div>
              <div v-else-if="col.name === 'yearly'" class="row q-pa-sm">
                <div class="col-7 label-color">
                  <div>{{ col.label }}</div>
                </div>
                <div class="col">
                  <div>{{ col.value + 543 }}</div>
                </div>
              </div>

              <div v-else 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 style="min-width: 40%" class="bg-white">
      <q-form @submit.prevent greedy @validation-success="validateForm">
        <q-card-section class="flex justify-between" style="padding: 0">
          <dialog-header
            :tittle="dialogStatus == 'edit' ? 'แก้ไขข้อมูล' : 'เพิ่มข้อมูล'"
            :close="closeDialog"
          />
        </q-card-section>
        <q-separator color="grey-4" />
        <div class="col">
          <q-card-section class="row q-gutter-sm">
            <div class="col">
              <q-input
                outlined
                v-model="trainData.name"
                label="ชื่อโครงการ/หลักสูตรการฝึกอบรม"
                bg-color="white"
                dense
                :rules="[
                  (val) =>
                    !!val || `${'กรุณากรอกชื่อโครงการ/หลักสูตรการฝึกอบรม'}`,
                ]"
                hide-bottom-space
              />
            </div>
            <div class="col">
              <q-input
                outlined
                v-model="trainData.topic"
                label="หัวข้อการฝึกอบรม/ดูงาน"
                bg-color="white"
                dense
                :rules="[
                  (val) => !!val || `${'กรุณากรอกหัวข้อการฝึกอบรม/ดูงาน'}`,
                ]"
                hide-bottom-space
              />
            </div>
          </q-card-section>
          <q-card flat bordered class="q-px-sm q-mx-md q-mb 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="trainData.startYear"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      dense
                      lazy-rules
                      outlined
                      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="trainData.finishYear"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      dense
                      lazy-rules
                      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"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      outlined
                      dense
                      lazy-rules
                      :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"
                >
                  <template #year="{ year }">{{ year + 543 }}</template>
                  <template #year-overlay-value="{ value }">{{
                    parseInt(value + 543)
                  }}</template>
                  <template #trigger>
                    <q-input
                      outlined
                      dense
                      lazy-rules
                      :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>
          <q-card-section class="row q-gutter-sm q-pt-sm q-py-none">
            <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
                    lazy-rules
                    outlined
                    hide-bottom-space
                    :model-value="trainData.yearly + 543"
                    :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">
              <q-input
                outlined
                v-model="trainData.place"
                label="สถานที่ฝึกอบรม/ดูงาน"
                bg-color="white"
                dense
                :rules="[
                  (val) => !!val || `${'กรุณากรอกสถานที่ฝึกอบรม/ดูงาน'}`,
                ]"
                hide-bottom-space
              />
            </div>
          </q-card-section>
          <q-card-section class="row q-gutter-sm q-pt-sm q-pb-none">
            <div class="col">
              <q-input
                outlined
                v-model="trainData.duration"
                label="รวมระยะเวลาในการฝึกอบรม/ดูงาน"
                bg-color="white"
                dense
              />
            </div>
            <div class="col">
              <q-input
                outlined
                v-model="trainData.department"
                label="หน่วยงานที่รับผิดชอบจัดการฝึกอบรม/ดูงาน"
                bg-color="white"
                dense
              />
            </div>
          </q-card-section>
          <q-card-section class="row q-gutter-sm q-pt-sm q-pb-none">
            <div class="col">
              <q-input
                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
                    lazy-rules
                    :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>
          </q-card-section>
        </div>
        <q-card-actions align="right">
          <q-btn
            id="onSubmit"
            type="submit"
            dense
            unelevated
            label="บันทึก"
            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: 70%" class="bg-white">
      <q-form @submit.prevent greedy @validation-success="validateForm">
        <q-card-section class="flex justify-between" style="padding: 0">
          <dialog-header
            tittle="ประวัติแก้ไขประวัติการศึกษา"
            :close="closeHistoryDialog"
          />
        </q-card-section>
        <q-separator color="grey-4" />
        <q-card-section>
          <q-toolbar style="padding: 0px" class="text-primary q-mb-sm">
            <q-space />
            <q-input
              dense
              outlined
              bg-color="white"
              v-model="historyFormFilter.keyword"
              label="ค้นหา"
              class="q-mr-sm"
            >
              <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="columns"
              option-value="name"
              options-cover
              style="min-width: 150px"
            />
          </q-toolbar>
          <d-table
            ref="table"
            :columns="columns"
            :rows="historyRows"
            row-key="name"
            flat
            :filter="historyFormFilter.keyword"
            v-model:pagination="historyPagination"
            bordered
            :paging="true"
            dense
            :rows-per-page-options="[20, 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
                    v-if="col.name === 'startDate' || col.name === 'endDate'"
                  >
                    <div v-if="props.row.isDate">
                      {{ date2Thai(col.value) }}
                    </div>
                    <div v-else>
                      {{ +col.value.slice(0, 4) + 543 }}
                    </div>
                  </div>
                  <div v-else-if="col.name === 'dateOrder'">
                    {{ date2Thai(col.value) }}
                  </div>
                  <div v-else-if="col.name === 'yearly'">
                    {{ col.value + 543 }}
                  </div>
                  <div v-else>
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
        </q-card-section>
      </q-form>
    </q-card>
  </q-dialog>
</template>

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

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

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