<!-- card การลา -->
<template>
  <q-card flat bordered class="col-12 q-px-lg q-py-md">
    <q-form ref="myForm">
      <ProfileTable
        :rows="rows"
        :columns="columns"
        :filter="filter"
        :visible-columns="visibleColumns"
        v-model:inputfilter="filter"
        v-model:inputvisible="visibleColumns"
        :add="clickAdd"
        :addleave="clickAddLeave"
        name="การลา"
        icon="mdi-calendar-account"
        iconAdd="mdi-calendar-account"
        :statusEdit="statusEdit"
      >
        <template #columns="props">
          <q-tr :props="props">
            <q-td
              v-for="col in props.cols"
              :key="col.name"
              :props="props"
              class="cursor-pointer"
              @click="selectData(props)"
            >
              <div v-if="col.name == 'no'">
                {{ props.rowIndex + 1 }}
              </div>
              <div
                v-else-if="col.name == 'dateStartLeave'"
                class="table_ellipsis"
              >
                {{
                  dateThaiRange([
                    props.row.dateStartLeave,
                    props.row.dateEndLeave,
                  ])
                }}
              </div>
              <div v-else-if="col.name == 'status'" class="table_ellipsis">
                {{ statusLeave(col.value) }}
                <!-- {{ col.value }} -->
              </div>
              <div
                v-else-if="
                  col.name == 'numLeave' ||
                  col.name == 'sumLeave' ||
                  col.name == 'totalLeave'
                "
                class="table_ellipsis"
              >
                {{ col.value == null ? "" : col.value.toLocaleString("en-US") }}
              </div>
              <div v-else class="table_ellipsis">
                {{ col.value }}
              </div>
            </q-td>
            <q-td auto-width>
              <q-btn
                color="info"
                flat
                dense
                round
                size="14px"
                icon="mdi-history"
                @click="clickHistory(props.row)"
              />
            </q-td>
          </q-tr>
        </template>
      </ProfileTable>
    </q-form>
  </q-card>
  <!-- popup Add Edit Leave -->
  <q-dialog v-model="modalAdd" persistent>
    <q-card style="width: 600px">
      <q-form ref="myFormAdd">
        <DialogHeader tittle="การลา" :close="clickCloseLeave" />
        <q-separator />
        <q-card-section class="q-p-sm">
          <div
            class="row col-12 items-center q-col-gutter-x-xs q-col-gutter-y-xs"
          >
            <div class="col-xs-6 col-sm-6 col-md-6">
              <selector
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="typeLeave"
                :rules="[(val:string) => !!val || `${'กรุณาเลือกประเภทการลา'}`]"
                hide-bottom-space
                :label="`${'ประเภทการลา'}`"
                @update:modelValue="clickEditRowType"
                emit-value
                map-options
                option-label="name"
                :options="typeLeaveOption"
                option-value="id"
                use-input
                input-debounce="0"
                @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'typeLeaveOption'
                      ) "
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <datepicker
                menu-class-name="modalfix"
                :readonly="!edit"
                v-model="dateRange"
                :locale="'th'"
                autoApply
                :enableTimePicker="false"
                @update:modelValue="clickEditRow"
                week-start="0"
                range
              >
                <template #year="{ year }">{{ year + 543 }}</template>
                <template #year-overlay-value="{ value }">{{
                  parseInt(value + 543)
                }}</template>
                <template #trigger>
                  <q-input
                    :class="getClass(edit)"
                    :outlined="edit"
                    dense
                    :borderless="!edit"
                    :model-value="dateThaiRange(dateRange)"
                    :rules="[(val:string) => !!val || `${'กรุณาเลือกวัน เดือน ปีที่ลา'}`]"
                    hide-bottom-space
                    :label="`${'วัน เดือน ปีที่ลา'}`"
                  >
                    <template v-slot:prepend>
                      <q-icon
                        name="event"
                        class="cursor-pointer"
                        :style="
                          edit
                            ? 'color: var(--q-primary)'
                            : 'color: var(--q-grey)'
                        "
                      >
                      </q-icon>
                    </template>
                  </q-input>
                </template>
              </datepicker>
            </div>
            <div class="col-xs-3 col-sm-3 col-md-3">
              <q-input
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="numLeave"
                type="number"
                :rules="[(val:string) => !!val || `${'กรุณากรอกจำนวนวันที่ลา'}`]"
                hide-bottom-space
                :label="`${'จำนวนวันที่ลา'}`"
                @update:modelValue="clickEditRow"
              />
            </div>
            <div class="col-xs-3 col-sm-3 col-md-3">
              <q-input
                :class="getClass(false)"
                :outlined="true"
                dense
                lazy-rules
                :readonly="false"
                :borderless="false"
                disable
                v-model="numUsedLeave"
                type="number"
                :rules="[(val:string) => !!val || `${'กรุณากรอกจำนวนวันที่ลามาแล้ว'}`]"
                hide-bottom-space
                :label="`${'จำนวนวันที่ลามาแล้ว'}`"
                @update:modelValue="clickEditRow"
              />
            </div>
            <div class="col-xs-6 col-sm-6 col-md-6">
              <selector
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="statLeave"
                :rules="[(val:string) => !!val || `${'กรุณาเลือกสถานะการลา'}`]"
                hide-bottom-space
                :label="`${'สถานะการลา'}`"
                @update:modelValue="clickEditRow"
                emit-value
                map-options
                option-label="name"
                :options="statLeaveOption"
                option-value="id"
                use-input
                input-debounce="0"
                @filter="(inputValue:string,
                      doneFn:Function) => filterSelector(inputValue, doneFn,'statLeaveOption'
                      ) "
              />
            </div>
            <div class="col-xs-12 col-sm-12 col-md-12">
              <q-input
                :class="getClass(edit)"
                :outlined="edit"
                dense
                lazy-rules
                :readonly="!edit"
                :borderless="!edit"
                v-model="reason"
                type="textarea"
                :rules="[(val:string) => !!val || `${'กรุณากรอกเหตุผล'}`]"
                hide-bottom-space
                :label="`${'เหตุผล'}`"
                @update:modelValue="clickEditRow"
              />
            </div>
          </div>
        </q-card-section>
        <q-separator />
        <DialogFooter
          :cancel="clickCancel"
          :edit="clickEdit"
          :save="clickSave"
          :validate="validateData"
          :clickNext="clickNext"
          :clickPrevious="clickPrevious"
          :clickDelete="clickDelete"
          v-model:editvisible="edit"
          v-model:next="next"
          v-model:previous="previous"
          v-model:modalEdit="modalEdit"
        />
      </q-form>
    </q-card>
  </q-dialog>
  <!-- popup Edit window-->
  <q-dialog v-model="modal" persistent>
    <q-card style="width: 600px">
      <q-form ref="myForm">
        <DialogHeader tittle="การลา" :close="clickClose" />
        <q-separator />
        <q-card-section>
          <div class="col-xs-12 col-sm-12 col-md-12">
            <data-table
              :rows="rowsTotal"
              :columns="columnsTotal"
              :filter="filterTotal"
              :visible-columns="visibleColumnsTotal"
              v-model:inputfilter="filterTotal"
              v-model:inputvisible="visibleColumnsTotal"
              :nornmalData="true"
            >
              <template #columns="props">
                <q-tr :props="props" class="cursor-pointer">
                  <q-td
                    v-for="col in props.cols"
                    :key="col.name"
                    :props="props"
                  >
                    <div v-if="col.name == 'no'">
                      {{ props.rowIndex + 1 }}
                    </div>
                    <div
                      v-else-if="
                        col.name == 'numLeave' ||
                        col.name == 'sumLeave' ||
                        col.name == 'totalLeave'
                      "
                      class="table_ellipsis"
                    >
                      {{
                        col.value == null
                          ? ""
                          : col.value.toLocaleString("en-US")
                      }}
                    </div>
                    <div v-else>
                      {{ col.value }}
                    </div>
                  </q-td>
                </q-tr>
              </template>
            </data-table>
          </div>
        </q-card-section>
        <q-separator />
      </q-form>
    </q-card>
  </q-dialog>
  <HistoryTable
    :rows="rowsHistory"
    :columns="columnsHistory"
    :filter="filterHistory"
    :visible-columns="visibleColumnsHistory"
    v-model:modal="modalHistory"
    v-model:inputfilter="filterHistory"
    v-model:inputvisible="visibleColumnsHistory"
    v-model:tittle="tittleHistory"
  >
    <template #columns="props">
      <q-tr :props="props">
        <q-td v-for="col in props.cols" :key="col.name" :props="props">
          <div v-if="col.name == 'no'">
            {{ props.rowIndex + 1 }}
          </div>
          <div v-else-if="col.name == 'dateStartLeave'" class="table_ellipsis">
            {{
              dateThaiRange([props.row.dateStartLeave, props.row.dateEndLeave])
            }}
          </div>

          <div
            v-else-if="
              col.name == 'numLeave' ||
              col.name == 'sumLeave' ||
              col.name == 'totalLeave'
            "
            class="table_ellipsis"
          >
            {{ col.value == null ? "" : col.value.toLocaleString("en-US") }}
          </div>
          <div v-else-if="col.name == 'status'" class="table_ellipsis">
            {{ statusLeave(col.value) }}
          </div>
          <div v-else class="table_ellipsis">
            {{ col.value }}
          </div>
        </q-td>
      </q-tr>
    </template>
  </HistoryTable>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { useCounterMixin } from "@/stores/mixin";
import { useComponentProfileDataStore } from "@/components/information/store/store";

import ProfileTable from "@/components/information/Table.vue";
import DialogHeader from "@/components/information/DialogHeader.vue";
import DialogFooter from "@/components/information/DialogFooter.vue";
import { useQuasar } from "quasar";
import type {
  RequestItemsObject,
  RequestItemsTotalObject,
  DataProps,
} from "@/components/information/interface/request/Leave";
import type {
  ResponseObject,
  ResponseTotalObject,
} from "@/components/information/interface/response/Leave";
import type {
  DataOption,
  DataOptionLeave,
} from "@/components/information/interface/index/Main";
import HistoryTable from "@/components/TableHistory.vue";
import http from "@/plugins/http";
import config from "@/app.config";
import type { QTableProps } from "quasar";

const props = defineProps({
  statusEdit: {
    type: Boolean,
    required: true,
  },
});

const $q = useQuasar();
const store = useComponentProfileDataStore();
const { profileData, changeProfileColumns } = store;
const mixin = useCounterMixin();
const {
  date2Thai,
  success,
  messageError,
  statusLeave,
  dialogMessage,
  dateToISO,
  showLoader,
  hideLoader,
} = mixin;
const route = useRoute();

const typeLeave = ref<string>("");
const typeLeaveOption = ref<DataOptionLeave[]>([]);
const typeLeaveOptionFilter = ref<DataOptionLeave[]>([]);

const statLeave = ref<string>("");
const statLeaveOption = ref<DataOption[]>([
  { id: "approve", name: "ผ่านการอนุมัติ" },
  { id: "reject", name: "ไม่ผ่านการอนุมัติ" },
  { id: "cancel", name: "ยกเลิก" },
  { id: "waitting", name: "รออนุมัติ" },
]);
const statLeaveOptionFilter = ref<DataOption[]>([
  { id: "approve", name: "ผ่านการอนุมัติ" },
  { id: "reject", name: "ไม่ผ่านการอนุมัติ" },
  { id: "cancel", name: "ยกเลิก" },
  { id: "waitting", name: "รออนุมัติ" },
]);
const dateRange = ref<[Date, Date]>([new Date(), new Date()]); //วันที่ ลา
const numLeave = ref<number>(0); //วันที่ ลา
const numUsedLeave = ref<number>(0); //วันที่ ลา
const reason = ref<string>(""); //เหตุผล
const id = ref<string>("");
// const year = ref<number>(0);
// const sickDay = ref<number>();
// const personalDay = ref<number>();
// const maternityDay = ref<number>();
// const wifeDay = ref<number>();
// const restDay = ref<number>();
// const ordainDay = ref<number>();
// const absentDay = ref<number>();
// const studyDay = ref<number>();
// const agencyDay = ref<number>();
// const coupleDay = ref<number>();
// const therapyDay = ref<number>();
const myFormAdd = ref<any>(); //form data input
const myForm = ref<any>(); //form data input
const edit = ref<boolean>(true); //เช็คการกดปุ่มแก้ไขใน dialog
const modal = ref<boolean>(false); //modal add detail
const modalEdit = ref<boolean>(false); //modal ที่แสดงใช้สำหรับแก้ไขหรือไม่

const modalAdd = ref<boolean>(false); //modal add detail
// const rawItem = ref<RequestItemsObject>(); //ข้อมูลเดิมที่เลือกใน row นั้น
const rowIndex = ref<number>(0); //indexข้อมูลเดิมที่เลือกใน row นั้น
const previous = ref<boolean>(); //แสดงปุ่มดูข้อมูลก่อนหน้า
const next = ref<boolean>(); //แสดงปุ่มดูข้อมูลต่อไป
const editRow = ref<boolean>(false); //เช็คมีการแก้ไขข้อมูล
const rowsHistory = ref<RequestItemsObject[]>([]); //select data history
const tittleHistory = ref<string>("ประวัติแก้ไขการลา"); //
const filterHistory = ref<string>(""); //search data table history
const modalHistory = ref<boolean>(false); //modal ประวัติการแก้ไขข้อมูล
const checkValidate = ref<boolean>(false); //validate data ผ่านหรือไม่
const profileId = ref<string>(
  route.params.id ? route.params.id.toString() : ""
);
const rows = ref<RequestItemsObject[]>([]);
const filterTotal = ref<string>("");
const rowsTotal = ref<RequestItemsTotalObject[]>([]); //select data history
const filter = ref<string>(""); //search data table
const visibleColumns = ref<String[]>([]);
profileData.leave.columns.length == 0
  ? (visibleColumns.value = [
      "no",
      "typeLeave",
      "dateStartLeave",
      "numLeave",
      "sumLeave",
      "totalLeave",
      "status",
      "reason",
    ])
  : (visibleColumns.value = profileData.leave.columns);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "typeLeave",
    align: "left",
    label: "ประเภทการลา",
    sortable: true,
    field: "typeLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateStartLeave",
    align: "left",
    label: "วัน เดือน ปี ที่ลา",
    sortable: true,
    field: "dateStartLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "numLeave",
    align: "right",
    label: "จำนวนวันลา",
    sortable: true,
    field: "numLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "sumLeave",
    align: "right",
    label: "ลามาแล้ว",
    sortable: true,
    field: "sumLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "totalLeave",
    align: "right",
    label: "รวมเป็น",
    sortable: true,
    field: "totalLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "status",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "reason",
    align: "right",
    label: "เหตุผล",
    sortable: true,
    field: "reason",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const columnsHistory = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: true,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "typeLeave",
    align: "left",
    label: "ประเภทการลา",
    sortable: true,
    field: "typeLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "dateStartLeave",
    align: "left",
    label: "วัน เดือน ปี ที่ลา",
    sortable: true,
    field: "dateStartLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "numLeave",
    align: "right",
    label: "จำนวนวันลา",
    sortable: true,
    field: "numLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "sumLeave",
    align: "right",
    label: "ลามาแล้ว",
    sortable: true,
    field: "sumLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "totalLeave",
    align: "right",
    label: "รวมเป็น",
    sortable: true,
    field: "totalLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "status",
    align: "left",
    label: "สถานะ",
    sortable: true,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "reason",
    align: "left",
    label: "เหตุผล",
    sortable: true,
    field: "reason",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);
const visibleColumnsHistory = ref<String[]>([
  "no",
  "typeLeave",
  "dateStartLeave",
  "numLeave",
  "sumLeave",
  "totalLeave",
  "status",
  "reason",
]);
const visibleColumnsTotal = ref<String[]>([
  "typeLeave",
  "limitLeave",
  "totalLeave",
  "remainLeave",
]);
const columnsTotal = ref<QTableProps["columns"]>([
  {
    name: "typeLeave",
    align: "left",
    label: "ประเภทการลา",
    sortable: true,
    field: "typeLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "limitLeave",
    align: "right",
    label: "จำนวนวันที่ได้รับ",
    sortable: true,
    field: "limitLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "totalLeave",
    align: "right",
    label: "จำนวนวันที่ใช้",
    sortable: true,
    field: "totalLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "remainLeave",
    align: "right",
    label: "จำนวนวันที่เหลือ",
    sortable: true,
    field: "remainLeave",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

watch(visibleColumns, async (count: String[], prevCount: String[]) => {
  await changeProfileColumns("leave", count);
});

onMounted(async () => {
  await fetchData();
});

const fetchData = async () => {
  rows.value = [];
  if (profileId.value) {
    showLoader();
    await http
      .get(config.API.profileLeaveId(profileId.value))
      .then((res) => {
        const data = res.data.result;
        data.map((e: ResponseObject) => {
          rows.value.push({
            id: e.id,
            typeLeave: e.typeLeave,
            dateStartLeave: new Date(e.dateStartLeave),
            dateEndLeave: new Date(e.dateEndLeave),
            numLeave: e.numLeave,
            sumLeave: e.sumLeave,
            totalLeave: e.totalLeave,
            status: e.status,
            reason: e.reason,
            typeLeaveId: e.typeLeaveId,
          });
        });
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  }
};

const filterSelector = (val: any, update: Function, filtername: string) => {
  switch (filtername) {
    case "typeLeaveOption":
      update(() => {
        typeLeaveOption.value = typeLeaveOptionFilter.value.filter(
          (v: DataOptionLeave) =>
            v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
        );
      });
      break;
    case "statLeaveOption":
      update(() => {
        statLeaveOption.value = statLeaveOptionFilter.value.filter(
          (v: DataOption) =>
            v.name.toLowerCase().indexOf(val.toLowerCase()) > -1
        );
      });
      break;
    default:
      break;
  }
};

const clickHistory = async (row: RequestItemsObject) => {
  modalHistory.value = true;
  showLoader();
  await http
    .get(config.API.profileLeaveHisId(row.id))
    .then((res) => {
      let data = res.data.result;
      rowsHistory.value = [];
      data.map((e: ResponseObject) => {
        rowsHistory.value.push({
          id: e.id,
          typeLeave: e.typeLeave,
          dateStartLeave: new Date(e.dateStartLeave),
          dateEndLeave: new Date(e.dateEndLeave),
          numLeave: e.numLeave,
          sumLeave: e.sumLeave,
          totalLeave: e.totalLeave,
          status: e.status,
          reason: e.reason,
          typeLeaveId: e.typeLeaveId,
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
};

const clickEditRowType = () => {
  const filter = typeLeaveOptionFilter.value.filter(
    (v: DataOptionLeave) => v.id == typeLeave.value
  );
  if (filter.length > 0) {
    numUsedLeave.value = filter[0].totalLeave;
  }
};

/**
 * เช็คว่ามีการแก้ไขข้อมูล
 */
const clickEditRow = () => {
  editRow.value = true;
};

// /**
//  * กดดูข้อมูลก่อนหน้า
//  */
const clickPrevious = async () => {
  edit.value = false;
  rowIndex.value -= 1;
  await getData();
  await checkRowPage();
};

// /**
//  * กดดูข้อมูลต่อไป
//  */
const clickNext = async () => {
  edit.value = false;
  rowIndex.value += 1;
  await getData();
  await checkRowPage();
};

// /**
//  * กดดูข้อมูลต่อไป
//  */
const getData = () => {
  const row = rows.value[rowIndex.value];
  //   year.value = row.year;
  //   sickDay.value = row.sickDay;
  //   personalDay.value = row.personalDay;
  //   maternityDay.value = row.maternityDay;
  //   wifeDay.value = row.wifeDay;
  //   restDay.value = row.restDay;
  //   ordainDay.value = row.ordainDay;
  //   absentDay.value = row.absentDay;
  //   studyDay.value = row.studyDay;
  //   agencyDay.value = row.agencyDay;
  //   coupleDay.value = row.coupleDay;
  //   therapyDay.value = row.therapyDay;
  id.value = row.id;
  typeLeave.value = row.typeLeaveId;
  statLeave.value = row.status;
  reason.value = row.reason;
  dateRange.value = [new Date(row.dateStartLeave), new Date(row.dateEndLeave)];
  numLeave.value = row.numLeave;
  numUsedLeave.value = row.sumLeave;
};

// /**
//  * เช็คปุ่มดูข้อมูล ย้อน กับ ต่อไป ว่าต้องแสดงไหม
//  */
const checkRowPage = () => {
  editRow.value = false;
  next.value = true;
  previous.value = true;
  if (rowIndex.value + 1 >= rows.value.length) {
    next.value = false;
  }
  if (rowIndex.value - 1 < 0) {
    previous.value = false;
  }
};

// /**
//  * กดปุ่มแก้ไขใน dialog
//  */
const clickEdit = () => {
  editRow.value = false;
  next.value = false;
  previous.value = false;
};

/**
 * กดปุ่มเพิ่มด้านบน table
 */
const clickAdd = async () => {
  editRow.value = false;
  await addData();
};

const clickAddLeave = async () => {
  editRow.value = false;
  edit.value = true;
  modalAdd.value = true;
  modalEdit.value = false;
  typeLeave.value = "";
  statLeave.value = "";
  reason.value = "";
  dateRange.value = [new Date(), new Date()];
  numLeave.value = 0;
  numUsedLeave.value = 0;
  await clickTotal();
  if (rowsTotal.value.length > 0) {
    let data: DataOptionLeave[] = [];
    rowsTotal.value.map((e: ResponseTotalObject) => {
      data.push({
        id: e.typeLeaveId,
        name: e.typeLeave,
        totalLeave: e.totalLeave,
      });
    });
    typeLeaveOption.value = data;
    typeLeaveOptionFilter.value = data;
  }
  //   await addData();
};

/**
 * ฟังก์ชันปุ่มยกเลิกการแก้ไขข้อมูล
 */
const clickCancel = async () => {
  if (editRow.value == true) {
    dialogMessage(
      $q,
      `ข้อมูลมีการแก้ไข`,
      `ยืนยันที่จะปิดโดยไม่บันทึกใช่หรือไม่?`,
      "info",
      "ยืนยัน",
      "public",
      () => {
        edit.value = false;
      },
      undefined
    );
  } else {
    edit.value = false;
    await checkRowPage();
  }
};

// /**
//  * กดบันทึกใน dialog
//  */
const clickSave = async () => {
  myFormAdd.value.validate().then(async (result: boolean) => {
    if (result) {
      if (modalEdit.value) {
        await editData();
      } else {
        await saveData();
      }
    }
  });
};

// /**
//  * บันทึกเพิ่มข้อมูล
//  */
const saveData = async () => {
  const sum = Number(numLeave.value) + Number(numUsedLeave.value);

  if (profileId.value) {
    showLoader();
    await http
      .post(config.API.profileLeaveId(profileId.value), {
        dateStartLeave: dateToISO(dateRange.value[0]),
        dateEndLeave: dateToISO(dateRange.value[1]),
        numLeave: numLeave.value,
        sumLeave: numUsedLeave.value,
        totalLeave: sum,
        status: statLeave.value,
        reason: reason.value,
        typeLeaveId: typeLeave.value,
      })
      .then((res) => {
        success($q, "บันทึกข้อมูลสำเร็จ");
        modalAdd.value = false;
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        await fetchData();
      });
  }
};

// /**
//  * บันทึกแก้ไขข้อมูล
//  */
const editData = async () => {
  const sum = Number(numLeave.value) + Number(numUsedLeave.value);

  showLoader();
  await http
    .put(config.API.profileLeaveId(id.value), {
      dateStartLeave: dateToISO(dateRange.value[0]),
      dateEndLeave: dateToISO(dateRange.value[1]),
      numLeave: numLeave.value,
      sumLeave: numUsedLeave.value,
      totalLeave: sum,
      status: statLeave.value,
      reason: reason.value,
      typeLeaveId: typeLeave.value,
    })
    .then((res) => {
      success($q, "บันทึกข้อมูลสำเร็จ");
      modalAdd.value = false;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await fetchData();
    });
};

const deleteData = async () => {
  showLoader();
  await http
    .delete(config.API.profileLeaveId(id.value))
    .then((res) => {
      success($q, "ลบข้อมูลสำเร็จ");
      modalAdd.value = false;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      await fetchData();
    });
};

// /**
//  * ลบลบข้อมูล
//  */
const clickDelete = async () => {
  dialogMessage(
    $q,
    `ลบข้อมูล`,
    `ต้องการทำการลบข้อมูลนี้ใช่หรือไม่?`,
    "delete",
    "ยืนยัน",
    "red",
    async () => {
      await deleteData();
    },
    async () => {
      await fetchData();
    }
  );
};
const clickCloseLeave = async () => {
  if (editRow.value == true) {
    dialogMessage(
      $q,
      `ข้อมูลมีการแก้ไข`,
      `ยืนยันที่จะปิดโดยไม่บันทึกใช่หรือไม่?`,
      "info",
      "ยืนยัน",
      "public",
      () => {
        modalAdd.value = false;
        next.value = false;
        previous.value = false;
      },
      undefined
    );
  } else {
    modalAdd.value = false;
    next.value = false;
    previous.value = false;
  }
};

/**
 * กดปิด dialog
 */
const clickClose = async () => {
  if (editRow.value == true) {
    dialogMessage(
      $q,
      `ข้อมูลมีการแก้ไข`,
      `ยืนยันที่จะปิดโดยไม่บันทึกใช่หรือไม่?`,
      "info",
      "ยืนยัน",
      "primary",
      () => {
        modal.value = false;
        next.value = false;
        previous.value = false;
      },
      undefined
    );
  } else {
    modal.value = false;
    next.value = false;
    previous.value = false;
  }
};

// /**
//  * กดเลือกข้อมูลที่จะแก้ไข
//  * @param props ค่า props ใน row ที่เลือก
//  */
const selectData = async (props: DataProps) => {
  modalEdit.value = true;
  //   modal.value = true;
  modalAdd.value = true;
  edit.value = false;
  rowIndex.value = props.rowIndex;
  id.value = props.row.id;

  typeLeave.value = props.row.typeLeaveId;
  statLeave.value = props.row.status;
  reason.value = props.row.reason;
  dateRange.value = [
    new Date(props.row.dateStartLeave),
    new Date(props.row.dateEndLeave),
  ];
  numLeave.value = props.row.numLeave;
  numUsedLeave.value = props.row.sumLeave;
  await clickTotal();
  if (rowsTotal.value.length > 0) {
    let data: DataOptionLeave[] = [];
    rowsTotal.value.map((e: ResponseTotalObject) => {
      data.push({
        id: e.typeLeaveId,
        name: e.typeLeave,
        totalLeave: e.totalLeave,
      });
    });
    typeLeaveOption.value = data;
    typeLeaveOptionFilter.value = data;
  }
  await checkRowPage();
};

/**
 * กดปุ่มเพิ่มบน table
 */
const addData = async () => {
  //   modalEdit.value = false;
  modal.value = true;
  //   edit.value = true;
  await clickTotal();
};

// /**
//  * ฟังก์ชันปุ่มยกเลิกการแก้ไขข้อมูล
//  */
// const clickCancel = async () => {
//   if (editRow.value == true) {
//     $q.dialog({
//       title: `ข้อมูลมีการแก้ไข`,
//       message: `ยืนยันยกเลิกการแก้ไขใช่หรือไม่?`,
//       cancel: "ยกเลิก",
//       ok: "ยืนยัน",
//       persistent: true,
//     }).onOk(async () => {
//       edit.value = false;
//       await checkRowPage();
//       await getData();
//     });
//   } else {
//     edit.value = false;
//     await checkRowPage();
//   }
// };

// /**
//  * เช็คว่ามีการแก้ไขข้อมูล
//  */
// const clickEditRow = () => {
//   editRow.value = true;
// };

/**
 * ฟังชั้นดูข้อมูลประวัติแก้ไขข้อมูลที่เลือก
 * @param row ข้อมูล row ที่ดูประวัติการแก้ไข
 */
const clickTotal = async () => {
  rowsTotal.value = [];
  if (profileId.value) {
    showLoader();
    await http
      .get(config.API.profileLeaveTotalId(profileId.value))
      .then((res) => {
        let data = res.data.result;
        data.map((e: ResponseTotalObject) => {
          rowsTotal.value.push({
            typeLeaveId: e.typeLeaveId,
            totalLeave: e.totalLeave,
            limitLeave: e.limitLeave,
            remainLeave: e.remainLeave,
            typeLeave: e.typeLeave,
          });
        });
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  }
};

// /**
//  * validate input ใน dialog
//  */
const validateData = async () => {
  checkValidate.value = true;
  await myFormAdd.value.validate().then((result: boolean) => {
    if (result == false) {
      checkValidate.value = false;
    }
  });
};

// /**
//  * class จัดรูปแบบแสดงระหว่างข้อมูลที่แก้ไขหรือแสดงเฉยๆ
//  * @param val ข้อมูล input สำหรับแก้ไขหรือไม่
//  */
// const getClass = (val: boolean) => {
//   return {
//     "full-width inputgreen cursor-pointer": val,
//     "full-width cursor-pointer": !val,
//   };
// };

/**
 * แปลงช่วงวันที่ถ้า2ค่าเป็นวันเดียวกันจะโชววันเดียวแต่ถ้าไม่เท่ากันจะแสดงเป็นช่วง
 * @param val ช่วงวันที่
 */
const dateThaiRange = (val: [Date, Date]) => {
  if (val === null) {
  } else if (date2Thai(val[0]) === date2Thai(val[1])) {
    return `${date2Thai(val[0])}`;
  } else {
    return `${date2Thai(val[0])} - ${date2Thai(val[1])} `;
  }
};

/**
 * class จัดรูปแบบแสดงระหว่างข้อมูลที่แก้ไขหรือแสดงเฉยๆ
 * @param val ข้อมูล input สำหรับแก้ไขหรือไม่
 */
const getClass = (val: boolean) => {
  return {
    "full-width inputgreen cursor-pointer": val,
    "full-width cursor-pointer": !val,
  };
};
</script>
<style lang="scss">
.modalfix {
  position: fixed !important;
}
</style>
