<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

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

/** importComponents*/
import DialogReason from "@/components/Dialogs/PopupReason.vue";
import DialogApprove from "@/modules/09_leave/components/4_specialTime/DialogApprove.vue";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";
import { useSpecialTimeStore } from "@/modules/09_leave/stores/SpecialTimeStore";

const dataSpecialTime = useSpecialTimeStore();
const $q = useQuasar(); // show dialog
const mixin = useCounterMixin();

const { hideLoader, monthYear2Thai, messageError, showLoader, success } = mixin;

const emit = defineEmits(["update:change-page"]);

/**ตัวแปรที่ใช้ */
const modalUnapprove = ref(false);
const modalApprove = ref(false);
const detailData = ref<any>();
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());

/**
 * ฟังก์ชั่นไม่อนุมัติ
 * @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;
  console.log(personId);
  modalApprove.value = true;
  dateDialog.value = date;
  dateFixDialog.value = dateFix;
  editCheck.value = check;
  if (check === "PENDING") {
    detailData.value = data;
  }
}

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

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

// paging
const pageSize = ref<number>(10);

// Pagination - initial pagination
const initialPagination = ref<any>({
  sortBy: null,
  descending: false,
  page: 1,
  rowsPerPage: pageSize, // set ตาม page หลักส่งมา
});

// Pagination - page & change page & get new data
const currentPage = ref<number>(1);
watch(
  [() => currentPage.value, () => initialPagination.value.rowsPerPage],
  async () => {
    dataSpecialTime.page = currentPage.value;
    await dataSpecialTime.fetchData();
  }
);

// Pagination - update rowsPerPage
async function updatePagination(initialPagination: any) {
  currentPage.value = 1;
  dataSpecialTime.pageSize = initialPagination.rowsPerPage;
  dataSpecialTime.page = 1; // set current page เป็น 1 เสมอเมื่อเปลี่ยน per row
}

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

/** function ค้นหาข้อมูลแล้วอัปเดท*/
function filterFn() {
  updatePagination(filterKeyword.value);
  console.log(filterKeyword.value);
  dataSpecialTime.filter = filterKeyword.value;
  dataSpecialTime.pageSize = pageSize.value;
  dataSpecialTime.fetchData();
}

/** Function Date */
const dateMonth = ref<any>({
  month: new Date().getMonth(),
  year: new Date().getFullYear(),
});
const updateMonth = async (e: DataDateMonthObject) => {
  // console.log(dateMonth.value);
  if (e != null) {
    dateYear.value = e.year;
    dateYear.value = dataSpecialTime.year;
    dataSpecialTime.month = dateMonth.value.month + 1;
    dataSpecialTime.year = dateMonth.value.year;
    // filterKeyword.value = "";
    await dataSpecialTime.fetchData();
    console.log(dateMonth);
  }
};

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

//แปลงเดือนเป็นไทย
const monthYearThai = (val: any) => {
  if (val == null) return "";
  else return monthYear2Thai(val.month, val.year);
};
</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="filterFn"
      >
        <template v-slot:append>
          <q-icon v-if="filterKeyword == ''" name="search" />
          <q-icon
            v-if="filterKeyword !== ''"
            name="clear"
            class="cursor-pointer"
            @click="resetFilter"
          />
        </template>
      </q-input>

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

    <div class="col-12">
      <d-table
        :columns="dataSpecialTime.columns"
        :rows="dataSpecialTime.rows"
        row-key="tb-list"
        flat
        bordered
        :paging="false"
        dense
        :visible-columns="dataSpecialTime.visibleColumns"
        :rows-per-page-options="[10, 25, 50, 100]"
        v-model:pagination="initialPagination"
        @update:pagination="updatePagination"
      >
        <template v-slot:pagination="scope">
          ทั้งหมด {{ dataSpecialTime.total }} รายการ
          <q-pagination
            v-model="currentPage"
            active-color="primary"
            color="dark"
            :max-pages="5"
            size="sm"
            boundary-links
            direction-links
            :max="Number(dataSpecialTime.maxPage)"
          ></q-pagination>
        </template>
        <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.name" :props="props">
              <div v-if="col.name == 'no'">
                {{
                  (dataSpecialTime.page - 1) * dataSpecialTime.pageSize +
                  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-td auto-width>
              <q-btn
                v-if="props.row.status == 'PENDING'"
                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'"
                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-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>
