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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";

import type { Pagination } from "@/modules/05_placement/interface/index/Main";
import type { MainData } from "@/modules/05_placement/interface/index/Survey";

const $q = useQuasar();
const mixin = useCounterMixin();
const { showLoader, hideLoader, messageError, date2Thai } = mixin;

const year = ref<number | null>(new Date().getFullYear()); //ปีงบประมาณ

const rows = ref<MainData[]>([]);
const filterKeyword = ref<string>("");
const total = ref<number>(0);
const totalList = ref<number>(1);
/** หัวตาราง */
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    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: "position",
    align: "left",
    label: "ตำแหน่ง",
    sortable: true,
    field: "position",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "answer1",
    align: "left",
    label: "ความคิดเห็น",
    sortable: true,
    field: "answer1",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "answer2",
    align: "left",
    label: "ปัญหาและอุปสรรค",
    sortable: true,
    field: "answer2",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "answer3",
    align: "left",
    label: "ความพึงพอใจ",
    sortable: true,
    field: "answer3",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format(val, row) {
      return date2Thai(row.createdAt, false, true);
    },
  },
]);
const visibleColumns = ref<string[]>([
  "no",
  "fullname",
  "position",
  "answer1",
  "answer2",
  "answer3",
  "createdAt",
]);
const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 10,
  rowsPerPage: 10,
});

async function getData() {
  showLoader();
  await http
    .get(config.API.probationSurvey, {
      params: {
        year: year.value,
        keyword: filterKeyword.value,
        page: pagination.value.page,
        pageSize: pagination.value.rowsPerPage,
      },
    })
    .then(async (res) => {
      const data = await res.data.result.data;
      totalList.value = Math.ceil(
        res.data.result.total / pagination.value.rowsPerPage
      );
      total.value = res.data.result.total;
      rows.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

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

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

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

<template>
  <q-card flat>
    <div class="row q-col-gutter-sm">
      <div class="col-12">
        <div class="row q-col-gutter-sm">
          <div>
            <datepicker
              menu-class-name="modalfix"
              v-model="year"
              style="width: 150px"
              :locale="'th'"
              autoApply
              year-picker
              :enableTimePicker="false"
              @update:model-value="getData()"
            >
              <template #year="{ year }">{{ year + 543 }}</template>
              <template #year-overlay-value="{ value }">{{
                parseInt(value + 543)
              }}</template>
              <template #trigger>
                <q-input
                  dense
                  outlined
                  hide-bottom-space
                  :model-value="year === null ? 'ทั้งหมด' : Number(year) + 543"
                  :label="`${'ปีพ.ศ.'}`"
                >
                </q-input>
              </template>
            </datepicker>
          </div>

          <q-space />
          <q-input
            standout
            dense
            v-model="filterKeyword"
            ref="filterRef"
            outlined
            placeholder="ค้นหาจากชื่อ - นามสกุล /ตำแหน่ง"
            @keydown.enter.prevent="getData()"
            style="width: 350px"
          >
            <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"
          />
        </div>
      </div>
      <div class="col-12">
        <d-table
          ref="table"
          :columns="columns"
          :rows="rows"
          row-key="personal_id"
          flat
          :visible-columns="visibleColumns"
          bordered
          :paging="true"
          dense
          :rows-per-page-options="[10, 25, 50, 100]"
          @update:pagination="updatePagination"
        >
          <template v-slot:pagination="scope">
            ทั้งหมด {{ total.toLocaleString() }} รายการ
            <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="getData()"
            ></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-tr>
          </template>
          <template v-slot:body="props">
            <q-tr :props="props">
              <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>
                  {{ col.value ? col.value : "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </d-table>
      </div>
    </div>
  </q-card>
</template>
