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

import type { DateFilter } from "@/modules/09_leave/interface/request/leave";
import type { DataOption } from "@/modules/09_leave/interface/index/Main";

/** importStores*/
import { useLeavelistDataStore } from "@/modules/09_leave/stores/LeaveStore";
import { useCounterMixin } from "@/stores/mixin";

const leaveStore = useLeavelistDataStore();
const mixin = useCounterMixin();
const $q = useQuasar();

const { messageError } = mixin;

const props = defineProps({
  rowsPerPage: {
    type: Number,
    require: true,
  },
});

const emit = defineEmits(["update:querySting"]);

/** formFilter*/
// const filter = reactive<DateFilter>({
//   year: new Date().getFullYear(), //*ปีในการยื่นขอใบลา(ใช้เป็น คศ.)
//   type: "00000000-0000-0000-0000-000000000000", //*Id ประเภทการลา
//   status: "ALL", //*สถานะการของลา
//   keyword: "", //keyword ค้นหา
// });

/**
 * function update ข้อมูลการค้นหา  (QuerySting)
 * @param newPage หน้า
 * @param pageSize ข้อมูลต่อแถว
 * @param dateFilter ข้อมูล Filter
 */
function updateQuerySting(
  newPage: number,
  pageSize: number,
  dateFilter: DateFilter
) {
  // ส่ง event ไปยัง parent component เพื่ออัพเดทค่า props
  emit("update:querySting", newPage, pageSize, dateFilter);
}

/** function ค้นหาข้อมูลใน Table*/
async function filterListLeave() {
  updateQuerySting(1, 0, leaveStore.filter);
}

/** Option*/
const optionTypeMain = ref<DataOption[]>([]);
const optionType = ref<DataOption[]>([]);
const optionStatus = ref<DataOption[]>([
  {
    id: "ALL",
    name: "ทั้งหมด",
  },
  {
    id: "NEW",
    name: "ใหม่",
  },
  {
    id: "PENDING",
    name: "กำลังดำเนินการ",
  },
  {
    id: "APPROVE",
    name: "อนุมัติ",
  },
  {
    id: "REJECT",
    name: "ไม่อนุมัติ",
  },
]);
const optionStatus2 = ref<DataOption[]>([
  {
    id: "ALL",
    name: "ทั้งหมด",
  },
  {
    id: "NEW",
    name: "ใหม่",
  },
  {
    id: "APPROVE",
    name: "อนุมัติ",
  },
  {
    id: "REJECT",
    name: "ไม่อนุมัติ",
  },
]);

const optionStatusMain = ref<DataOption[]>(
  leaveStore.tabMenu == "1" ? optionStatus.value : optionStatus2.value
);

/** function เรียกข้อมูลสถานะ*/
async function fetchOption() {
  await http
    .get(config.API.leaveType())
    .then((res) => {
      const data = res.data.result;
      leaveStore.leaveType = data;
      optionTypeMain.value = [
        { id: "00000000-0000-0000-0000-000000000000", name: "ทั้งหมด" },
      ];
      const option = data.map((e: DataOption) => ({
        id: e.id,
        name: e.name,
      }));
      optionTypeMain.value.push(...option);
      optionType.value = optionTypeMain.value;
    })
    .catch((err) => {
      messageError($q, err);
    });
}

/**
 * ฟังก์ชั่นค้นหาข้อมูลของ Option Filter
 * @param val คำที่ค้นหา
 * @param update Function
 * @param name ประเภทของ Select
 */
function filterOption(val: string, update: any, name: string) {
  update(() => {
    const needle = val.toLowerCase();
    if (name === "type") {
      optionType.value = optionTypeMain.value.filter(
        (v: any) => v.name.toLowerCase().indexOf(needle) > -1
      );
    } else if (name === "status") {
      optionStatus.value = optionStatusMain.value.filter(
        (v: any) => v.name.toLowerCase().indexOf(needle) > -1
      );
    }
  });
}

onMounted(async () => {
  await fetchOption();
});
</script>

<template>
  <div class="row col-12 q-col-gutter-sm q-mb-sm">
    <div class="col-xs-12 col-sm-3 col-md-2">
      <datepicker
        menu-class-name="modalfix"
        v-model="leaveStore.filter.year"
        class="col-2"
        :locale="'th'"
        autoApply
        year-picker
        :enableTimePicker="false"
        @update:model-value="filterListLeave"
      >
        <template #year="{ year }">{{ year + 543 }}</template>
        <template #year-overlay-value="{ value }">{{
          parseInt(value + 543)
        }}</template>
        <template #trigger>
          <q-input
            dense
            lazy-rules
            outlined
            :model-value="Number(leaveStore.filter.year) + 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-xs-12 col-sm-3 col-md-2">
      <q-select
        for="selectType"
        emit-value
        map-options
        outlined
        dense
        v-model="leaveStore.filter.type"
        :options="optionType"
        option-value="id"
        option-label="name"
        label="ประเภทการลา"
        @update:model-value="filterListLeave"
        use-input
        @filter="
            (inputValue:any, doneFn:Function) =>
            filterOption(inputValue, doneFn, 'type')
          "
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
          </q-item>
        </template></q-select
      >
    </div>
    <div class="col-xs-12 col-sm-3 col-md-2">
      <q-select
        for="selectStatus"
        emit-value
        map-options
        outlined
        dense
        v-model="leaveStore.filter.status"
        :options="optionStatus"
        option-value="id"
        option-label="name"
        label="สถานะ"
        @update:model-value="filterListLeave"
        use-input
        @filter="
            (inputValue:any, doneFn:Function) =>
            filterOption(inputValue, doneFn, 'status')
          "
      >
        <template v-slot:no-option>
          <q-item>
            <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
          </q-item>
        </template></q-select
      >
    </div>
    <q-space />
    <div class="col-xs-12 col-sm-3 col-md-2">
      <q-input
        for="filterTable"
        dense
        outlined
        v-model="leaveStore.filter.keyword"
        label="ค้นหา"
        @keydown.enter.prevent="filterListLeave"
      />
    </div>
    <div class="col-xs-12 col-sm-3 col-md-2">
      <q-select
        for="visibleColumns"
        v-model="leaveStore.visibleColumns"
        multiple
        outlined
        dense
        options-dense
        :display-value="$q.lang.table.columns"
        emit-value
        map-options
        :options="leaveStore.columns"
        option-value="name"
        options-cover
      />
    </div>
  </div>
</template>
