<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useQuasar } from "quasar";
import type { QTableProps } from "quasar";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useSpecialTimeStore } from "@/modules/09_leave/stores/SpecialTimeStore";
import { checkPermission } from "@/utils/permissions";

import type {
  DataDateMonthObject,
  DetailData,
} from "@/modules/09_leave/interface/request/specialTime";

import DialogReason from "@/components/Dialogs/PopupReason.vue";
import DialogApprove from "@/modules/09_leave/components/04_SpecialTime/DialogApprove.vue";

const $q = useQuasar(); // show dialog
const mixin = useCounterMixin();
const store = useSpecialTimeStore();
const {
  hideLoader,
  monthYear2Thai,
  messageError,
  showLoader,
  success,
  date2Thai,
  dialogConfirm,
} = mixin;
const emit = defineEmits(["update:change-page"]);
const rows = ref<any[]>([]);
const toDay = ref<Date>(new Date());
const monthToday = toDay.value.getMonth();
const yearToday = toDay.value.getFullYear();

const month = ref<number>(monthToday + 1);
const year = ref<number>(yearToday);

/**ตัวแปรที่ใช้ */
const modalUnapprove = ref<boolean>(false);
const modalApprove = ref<boolean>(false);
const detailData = ref<DetailData[]>([]);
const editCheck = ref<string>("");
const dialogTitle = ref<string>("");
const dialogDesc = ref<string>("");
const name = ref<string>("");
const id = ref<string>("");
const dateDialog = ref<string>("");
const dateFixDialog = ref<string>("");
const dateYear = ref<number>(new Date().getFullYear());

/** Function Date */
const dateMonth = ref<DataDateMonthObject>({
  month: new Date().getMonth(),
  year: new Date().getFullYear(),
});

const total = ref<number>(0);
const totalList = ref<number>(1);
const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});

// ค้นหาในตาราง
const filterKeyword = ref<string>("");
const filterRef = ref<HTMLInputElement | null>(null);
const resetFilter = () => {
  filterKeyword.value = "";
  fetchData();
  if (filterRef.value) {
    filterRef.value.focus();
  }
};

const visibleColumns = ref<String[]>([
  "no",
  "fullname",
  "date",
  "dateFix",
  "timeMorning",
  "timeAfternoon",
  "description",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "center",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullname",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullname",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "date",
    align: "left",
    label: "วันที่ยื่นเรื่อง",
    sortable: true,
    field: "date",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "dateFix",
    align: "left",
    label: "วันที่ขอแก้ไข",
    sortable: true,
    field: "dateFix",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "timeMorning",
    align: "left",
    label: "ช่วงเช้า",
    sortable: true,
    field: "timeMorning",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "timeAfternoon",
    align: "left",
    label: "ช่วงบ่าย",
    sortable: true,
    field: "timeAfternoon",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "description",
    align: "left",
    label: "เหตุผล",
    sortable: true,
    field: "description",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/**
 * ฟังก์ชั่นไม่อนุมัติ
 * @param fullname ชื่อ
 * @param personId personId
 */
async function unapprove(fullname: string, personId: string) {
  id.value = personId;
  dialogTitle.value = " ไม่อนุมัติคำขอ"; // + fullname;
  name.value = fullname;
  modalUnapprove.value = true;
}

/** function openDialog */
function openModal(
  data: any,
  check: string,
  date: string,
  dateFix: string,
  personId: string
) {
  id.value = personId;
  modalApprove.value = true;
  dateDialog.value = date;
  dateFixDialog.value = dateFix;
  editCheck.value = check;
  if (check === "PENDING") {
    detailData.value = data;
  }
}

/** function closeDialog */
function closeDialog() {
  modalUnapprove.value = false;
  modalApprove.value = false;
  editCheck.value = "PENDING";
}

/** API reject */
async function clickSave(reason: string) {
  dialogConfirm($q, async () => {
    showLoader();
    modalUnapprove.value = false;
    const body = {
      reason: reason,
    };
    await http
      .put(config.API.specialTimeReject(id.value), body)
      .then(async () => {
        await fetchData();
        success($q, "บันทึกข้อมูลสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

/**
 * ดึงข้อมูลตามปี
 * @param e ปี
 */
async function updateMonth(e: DataDateMonthObject) {
  if (e != null) {
    dateYear.value = e.year;
    dateYear.value = year.value;
    month.value = dateMonth.value.month + 1;
    year.value = dateMonth.value.year;
    getSearch();
  }
}

//แปลงเดือนเป็นไทย
function monthYearThai(val: any) {
  if (val == null) return "";
  else return monthYear2Thai(val.month, val.year);
}

function updatePagination(newPagination: any) {
  pagination.value.page = 1;
  pagination.value.rowsPerPage = newPagination.rowsPerPage;
}

function getSearch() {
  pagination.value.page = 1;
  fetchData();
}

watch(
  () => pagination.value.rowsPerPage,
  async () => {
    getSearch();
  }
);

/**
 * ฟังชั้นเรียกดูข้อมูล
 */
async function fetchData() {
  showLoader();
  await http
    .get(
      config.API.specialTime() +
        `?year=${year.value}&month=${month.value}&page=${pagination.value.page}&pageSize=${pagination.value.rowsPerPage}&keyword=${filterKeyword.value.trim()}`
    )
    .then(async (res) => {
      let data = res.data.result.data;
      total.value = res.data.result.total;
      totalList.value = Math.ceil(
        res.data.result.total / pagination.value.rowsPerPage
      );
      total.value = res.data.result.total;
      rows.value = [];
      data.map((e: any) => {
        rows.value.push({
          id: e.id,
          fullname: e.fullName,
          date: date2Thai(new Date(e.createdAt), false, true),
          dateFix: date2Thai(new Date(e.checkDate)),
          timeMorning:
            e.startTimeMorning == null
              ? "-"
              : e.checkInEdit == true
              ? e.startTimeMorning + " - " + e.endTimeMorning
              : "-",
          timeAfternoon:
            e.startTimeAfternoon == null
              ? "-"
              : e.checkOutEdit == true
              ? e.startTimeAfternoon + " - " + e.endTimeAfternoon
              : "-",
          startTimeMorning: e.startTimeMorning,
          endTimeMorning: e.endTimeMorning,
          startTimeAfternoon: e.startTimeAfternoon,
          endTimeAfternoon: e.endTimeAfternoon,
          checkIn: e.checkInTime,
          checkOut: e.checkOutTime,
          status: e.status,
          checkInStatus: store.convertStatus(e.checkInStatus),
          checkOutStatus: store.convertStatus(e.checkOutStatus),
          reason: e.reason,
          description: e.description,
          checkInEdit: e.checkInEdit,
          checkOutEdit: e.checkOutEdit,
        });
      });
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
      console.log(month.value);
    });
}

/**Hook */
onMounted(async () => {
  //อัพเดทเป็นวันปัจจุบันเมื่อเข้าหน้านี้
  const toDay = ref<Date>(new Date());
  const monthToday = toDay.value.getMonth();
  const yearToday = toDay.value.getFullYear();
  month.value = monthToday + 1;
  year.value = yearToday;
  await fetchData();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการลงเวลากรณีพิเศษ
  </div>
  <q-card flat bordered class="col-12 q-mt-sm q-pt-sm q-pa-md">
    <div class="row col-12 q-col-gutter-sm q-mb-sm">
      <div class="q-gutter-sm">
        <datepicker
          v-model="dateMonth"
          :locale="'th'"
          autoApply
          month-picker
          :enableTimePicker="false"
          @update:modelValue="updateMonth"
        >
          <template #year="{ year }">{{ year + 543 }}</template>
          <template #year-overlay-value="{ value }">{{
            parseInt(value + 543)
          }}</template>
          <template #trigger>
            <q-input
              :model-value="monthYearThai(dateMonth)"
              dense
              outlined
              hide-bottom-space
              style="width: 130px"
            >
              <template v-slot:prepend>
                <q-icon
                  name="event"
                  class="cursor-pointer"
                  style="color: var(--q-primary)"
                >
                </q-icon>
              </template>
            </q-input>
          </template>
        </datepicker>
      </div>

      <q-space />

      <q-input
        class="col-xs-12 col-sm-3 col-md-2"
        standout
        dense
        v-model="filterKeyword"
        ref="filterRef"
        outlined
        debounce="300"
        placeholder="ค้นหาชื่อ-นามสกุล"
        @keydown.enter.prevent="getSearch()"
      >
        <template v-slot:append>
          <q-icon name="search" />
        </template>
      </q-input>

      <q-select
        v-model="visibleColumns"
        multiple
        outlined
        dense
        options-dense
        :display-value="$q.lang.table.columns"
        emit-value
        map-options
        :options="columns"
        option-value="name"
        style="min-width: 140px"
        class="col-xs-12 col-sm-3 col-md-2"
      />
    </div>

    <div class="col-12">
      <d-table
        :columns="columns"
        :rows="rows"
        row-key="tb-list"
        flat
        bordered
        :paging="false"
        dense
        :visible-columns="visibleColumns"
        :rows-per-page-options="[10, 25, 50, 100]"
        @update:pagination="updatePagination"
      >
        <template v-slot:pagination="scope">
          ทั้งหมด {{ total }} รายการ
          <q-pagination
            v-model="pagination.page"
            active-color="primary"
            color="dark"
            :max="Number(totalList)"
            size="sm"
            boundary-links
            direction-links
            :max-pages="5"
            @update:model-value="fetchData()"
          ></q-pagination>
        </template>
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th auto-width />
            <q-th v-for="col in props.cols" :key="col.name" :props="props">
              <span class="text-weight-medium">{{ col.label }}</span>
            </q-th>
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td auto-width class="text-right">
              <q-btn
                v-if="
                  props.row.status == 'PENDING' &&
                  checkPermission($route)?.attrIsUpdate &&
                  checkPermission($route)?.attrIsGet
                "
                color="orange"
                class="q-px-md"
                dense
                unelevated
                @click="unapprove(props.row.fullname, props.row.id)"
                >ไม่อนุมัติ</q-btn
              >

              <q-btn
                v-if="
                  props.row.status == 'PENDING' &&
                  checkPermission($route)?.attrIsUpdate &&
                  checkPermission($route)?.attrIsGet
                "
                color="primary"
                class="q-px-md q-ml-sm"
                dense
                unelevated
                @click="
                  openModal(
                    props.row,
                    'PENDING',
                    props.row.date,
                    props.row.dateFix,
                    props.row.id
                  )
                "
                >อนุมัติ</q-btn
              >

              <q-badge
                v-if="props.row.status == 'APPROVE'"
                rounded
                outline
                color="green"
                label="อนุมัติ"
              />
              <q-badge
                v-if="props.row.status == 'REJECT'"
                rounded
                outline
                color="red"
                label="ไม่อนุมัติ"
              />
            </q-td>
            <q-td v-for="col in props.cols" :key="col.name" :props="props">
              <div v-if="col.name == 'no'">
                {{
                  (pagination.page - 1) * pagination.rowsPerPage +
                  props.rowIndex +
                  1
                }}
              </div>
              <div
                v-else-if="col.name === 'description'"
                class="table_ellipsis"
              >
                {{ props.row.description }}
              </div>
              <div v-else>
                {{ col.value }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card>

  <DialogReason
    v-model:modal="modalUnapprove"
    :title="dialogTitle"
    :desc="dialogDesc"
    label="เหตุผล"
    :savaForm="clickSave"
  />

  <DialogApprove
    :modal="modalApprove"
    :closeDialog="closeDialog"
    :date="dateDialog"
    :dateFix="dateFixDialog"
    :id="id"
    :editCheck="editCheck"
    :detailData="detailData"
  />
</template>

<style></style>
