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

import Table from "@/modules/12_evaluatePersonal/components/Table.vue";
import { useCounterMixin } from "@/stores/mixin";
import { useEvalutuonStore } from "@/modules/12_evaluatePersonal/store/Evaluate";
import type { Pagination } from "@/modules/03_recruiting/interface/index/Main";

const $q = useQuasar(); // show dialog
const router = useRouter();
//search data table
const mixin = useCounterMixin();
const store = useEvalutuonStore();
const { showLoader, hideLoader, messageError } = mixin;
const attrs = ref<any>(useAttrs());

function Detailpage(id: string) {
  router.push(`/evaluate/detail/${id}`);
}

const currentPage = ref<number>(1);
const maxPage = ref<number>(0);
const page = ref<number>(1);
const total = ref<number>(0);
const filter = ref<string>("");
const pageSize = ref<number>(10);

/**
 *pagination ของตาราง
 */
const initialPagination = ref<any>({
  sortBy: null,
  descending: false,
  page: 1,
  rowsPerPage: pageSize,
});

// Pagination - update rowsPerPage
async function updatePagination(initialPagination: any) {
  currentPage.value = 1;
  pageSize.value = initialPagination.rowsPerPage;
  page.value = 1; // set current page เป็น 1 เสมอเมื่อเปลี่ยน per row
}
// Pagination - page & change page & get new data
watch(
  [
    () => currentPage.value,
    () => (pageSize.value = initialPagination.value.rowsPerPage),
  ],
  async () => {
    getList();
  }
);
// Pagination - page & change page & get new data
watch(
  [() => currentPage.value, () => initialPagination.value.rowsPerPage],
  async () => {
    page.value = currentPage.value;
    await getList();
  }
);
watch(
  () => initialPagination.value.rowsPerPage,
  () => {
    pageSize.value = initialPagination.value.rowsPerPage;
    currentPage.value = 1;
    getList();
  }
);

/**
 * filter function
 */
const filterRef = ref<HTMLInputElement | null>(null);
function filterFn() {
  updatePagination(filter.value);
  pageSize.value = initialPagination.value.rowsPerPage;
  getList();
}
const resetFilter = () => {
  filter.value = "";
  getList();
  if (filterRef.value) {
    filterRef.value.focus();
  }
};

function getList() {
  showLoader();
  http
    .get(
      config.API.evaluationMain(currentPage.value, pageSize.value, filter.value)
    )
    .then(async (res) => {
      const data = res.data.result.data;
      total.value = res.data.result.total;
      console.log(res.data.result.total);
      maxPage.value = await Math.ceil(total.value / pageSize.value);
      maxPage.value = maxPage.value < 1 ? 1 : maxPage.value;
      console.log(total.value);
      console.log(pageSize.value);
      console.log(maxPage.value);

      store.fetchData(data);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**เมื่อเริ่มโหลดหน้า
 * ส่งข้อมูลจำลองไปยัง store
 */
onMounted(async () => {
  getList();
});
</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">
      <q-space />
      <q-input
        class="col-xs-12 col-sm-3 col-md-2"
        id="filterTable"
        for="filterTable"
        dense
        outlined
        v-model="filter"
        label="ค้นหา"
        debounce="300"
        @keydown.enter.prevent="filterFn"
      >
        <template v-slot:append>
          <q-icon v-if="filter == ''" name="search" />
          <q-icon
            v-if="filter !== ''"
            name="clear"
            class="cursor-pointer"
            @click="resetFilter"
          />
        </template>
      </q-input>

      <q-select
        id="visibleColumns"
        for="visibleColumns"
        v-model="store.visibleColumns"
        multiple
        outlined
        dense
        options-dense
        :display-value="$q.lang.table.columns"
        emit-value
        map-options
        :options="store.columns"
        option-value="name"
        options-cover
        class="col-xs-12 col-sm-3 col-md-2"
      />
    </div>
    <div>
      <d-table
        ref="table"
        :columns="store.columns"
        :rows="store.rows"
        row-key="interrogated"
        flat
        bordered
        :paging="false"
        dense
        class="custom-header-table"
        :visible-columns="store.visibleColumns"
        v-model:pagination="initialPagination"
        :rows-per-page-options="[10, 25, 50, 100]"
        @update:pagination="updatePagination"
      >
        <template v-slot:pagination="scope">
          ทั้งหมด {{ total }} รายการ
          <q-pagination
            v-model="currentPage"
            active-color="primary"
            color="dark"
            :max="Number(maxPage)"
            size="sm"
            boundary-links
            direction-links
          ></q-pagination>
        </template>
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th auto-width></q-th>
            <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-th>
          </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'">
                {{ (page - 1) * rowsPerPage + props.rowIndex + 1 }}
              </div>
              <div v-else>
                {{ col.value }}
              </div>
            </q-td> -->
            <q-td auto-width>
              <q-icon
                v-if="props.row.isDefault === true"
                name="mdi-bookmark"
                size="xs"
                color="primary"
              >
                <q-tooltip>เวลา Default</q-tooltip>
              </q-icon>
            </q-td>
            <q-td
              v-for="col in props.cols"
              :key="col.name"
              :props="props"
              @click="Detailpage(props.row.id)"
            >
              <div v-if="col.name == 'no'">
                {{ (page - 1) * pageSize + props.rowIndex + 1 }}
              </div>
              <div v-else>
                {{ col.value }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card>
</template>

<style></style>
