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

/**importType*/
import type {
  ItemsMenu,
  NewPagination,
} from "@/modules/15_development/interface/index/Main";
import type { FormQueryListProject } from "@/modules/15_development/interface/request/Main";
import type { ResListProject } from "@/modules/15_development/interface/response/Main";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";

/** use*/
const $q = useQuasar();
const router = useRouter();
const { showLoader, hideLoader, messageError } = useCounterMixin();

/** หัวตาราง */
const columns = ref<QTableProps["columns"]>([
  {
    name: "year",
    align: "left",
    label: "ปีงบประมาณ ",
    sortable: true,
    field: "year",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px ; width:10%",
    format: (val) => val + 543,
  },
  {
    name: "projectName",
    align: "left",
    label: "ชื่อโครงการ/กิจกรรม/หลักสูตร",
    sortable: true,
    field: "projectName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px;width:45% ",
  },

  {
    name: "org",
    align: "left",
    label: "หน่วยงานที่รับผิดชอบ",
    sortable: true,
    field: "org",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px ; width:45% ",
  },
]);
const visibleColumns = ref<string[]>(["year", "projectName", "org"]);

/** เมนูดาวน์โหลด*/
const itemDownload = ref<ItemsMenu[]>([
  {
    label: "ดาวน์โหลด 1",
    value: "",
    icon: "mdi-file-pdf-box",
    color: "green",
  },
  {
    label: "ดาวน์โหลด 2",
    value: "",
    icon: "mdi-file-table",
    color: "red",
  },
  {
    label: "ดาวน์โหลด 3",
    value: "",
    icon: "mdi-file-word",
    color: "blue",
  },
]);

/** formQuery*/
const formQuery = reactive<FormQueryListProject>({
  year: new Date().getFullYear(),
  page: 1,
  pageSize: 10,
  keyword: "",
});
const totalList = ref<number>(1); //จำนวนข้อมูลรายการ
const rows = ref<ResListProject[]>([]); // ข้อมูลรายการ

/** funciton  fetch รายการโครงการ*/
function fetchListProject() {
  showLoader();
  http
    .get(
      config.API.developmentMain +
        `?page=${formQuery.page}&pageSize=${formQuery.pageSize}&keyword=${formQuery.keyword}&year=${formQuery.year}`
    )
    .then((res) => {
      const data = res.data.result.data;
      totalList.value = Math.ceil(res.data.result.total / formQuery.pageSize);
      rows.value = data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 *  funciotn redirect to page เพิ่มหริอแก้ไข รายการโครงการ
 * @param status สถานะแก่ไข
 * @param id รายการโครงการ
 */
function onClickAddOrView(status: boolean = false, id: string = "") {
  status ? router.push(`/development/${id}`) : router.push("/development/add");
}

/**
 * function updatePagination
 * @param newPagination ข้อมูล Pagination ใหม่
 */
function updatePagination(newPagination: NewPagination) {
  formQuery.page = 1;
  formQuery.pageSize = newPagination.rowsPerPage;
}

/** callbackFunction ทำเมื่อมีการอัปเดท pageSize*/
watch(
  () => formQuery.pageSize,
  () => {
    fetchListProject();
  }
);

onMounted(() => {
  fetchListProject();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการโครงการ/หลักสูตรการฝึกอบรมที่หน่วยงานของกรุงเทพมหานครเป็นผู้จัด
  </div>
  <q-card flat bordered class="q-pa-md">
    <q-toolbar style="padding: 0px">
      <datepicker
        menu-class-name="modalfix"
        v-model="formQuery.year"
        :locale="'th'"
        autoApply
        year-picker
        :enableTimePicker="false"
        @update:model-value="fetchListProject"
      >
        <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(formQuery.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>
      <q-btn
        flat
        round
        dense
        icon="add"
        color="primary"
        @click="onClickAddOrView()"
      >
        <q-tooltip>เพิ่ม</q-tooltip>
      </q-btn>
      <q-space />
      <div class="row q-gutter-sm">
        <q-btn
          flat
          round
          color="blue"
          icon="mdi-arrow-down-bold-circle-outline"
        >
          <q-menu>
            <q-list style="min-width: 100px" dense>
              <q-item clickable v-close-popup v-for="items in itemDownload">
                <q-item-section avatar>
                  <q-icon :color="items.color" :name="items.icon" />
                </q-item-section>
                <q-item-section :class="`text-${items.color}`">{{
                  items.label
                }}</q-item-section>
              </q-item>
            </q-list>
          </q-menu>
          <q-tooltip>ดาวน์โหลด</q-tooltip>
        </q-btn>

        <q-input
          standout
          dense
          v-model="formQuery.keyword"
          ref="filterRef"
          outlined
          placeholder="ค้นหา"
          @keyup.enter="fetchListProject"
        >
          <template v-slot:append>
            <q-icon v-if="formQuery.keyword == ''" name="search" />
            <q-icon
              v-if="formQuery.keyword !== ''"
              name="clear"
              class="cursor-pointer"
              @click="(formQuery.keyword = ''), fetchListProject()"
            />
          </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"
          options-cover
          style="min-width: 150px"
        />
      </div>
    </q-toolbar>

    <div class="col-12">
      <d-table
        for="table"
        ref="table"
        :columns="columns"
        :rows="rows"
        row-key="id"
        flat
        bordered
        dense
        class="custom-header-table"
        :rows-per-page-options="[10, 25, 50, 100]"
        :visible-columns="visibleColumns"
        @update:pagination="updatePagination"
      >
        <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" class="cursor-pointer">
            <q-td
              v-for="col in props.cols"
              :key="col.name"
              :props="props"
              @click="onClickAddOrView(true, props.row.id)"
            >
              <div class="table_ellipsis">
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
          </q-tr>
        </template>
        <template v-slot:pagination="scope">
          <q-pagination
            v-model="formQuery.page"
            active-color="primary"
            color="dark"
            :max="Number(totalList)"
            size="sm"
            boundary-links
            direction-links
            :max-pages="5"
            @update:model-value="fetchListProject"
          ></q-pagination>
        </template>
      </d-table>
    </div>
  </q-card>
</template>

<style scoped></style>
