useA
<script setup lang="ts">
import type { QTableProps } from "quasar";
import { ref, onMounted, reactive } from "vue";
import { useQuasar } from "quasar";
import { useRouter } from "vue-router";

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useAppealComplainStore } from "@/modules/07_appealComplain/store";
import { calculateFiscalYear } from "@/utils/functions";

import type { PropsTable } from "@/interface/PropsTable";
import type { FormType } from "@/modules/07_appealComplain/interface/response/mainType";
import type { DataOption } from "@/modules/07_appealComplain/interface/index/main";

const $q = useQuasar();
const router = useRouter();
const mixin = useCounterMixin();
const dataStore = useAppealComplainStore();
const { messageError } = mixin;

const filterKeyword = ref<string>("");
const type = ref<DataOption[]>([
  { id: "ALL", name: "ทั้งหมด" },
  ...dataStore.typeOptions,
]);

const isload = ref<boolean>(false);
const pagination = ref<PropsTable.Pagination>({
  sortBy: "",
  descending: true,
  page: 1,
  rowsPerPage: 10,
  rowsNumber: 0,
});
const formData = reactive<FormType>({
  type: "ALL",
  status: "ALL",
  year: calculateFiscalYear(new Date()),
});
const visibleColumns = ref<string[]>([
  "no",
  "title",
  "type",
  "year",
  "caseType",
  "caseNumber",
  "fullname",
  "citizenId",
  "lastUpdatedAt",
  "status",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "left",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:5px;",
  },
  {
    name: "title",
    align: "left",
    label: "เรื่องที่อุทธรณ์/ร้องทุกข์",
    sortable: true,
    field: "title",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:15%;",
  },
  {
    name: "type",
    align: "left",
    label: "ประเภท",
    sortable: false,
    field: "type",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:15%;",
  },
  {
    name: "year",
    align: "left",
    label: "ปีงบประมาณ",
    sortable: false,
    field: "year",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "caseType",
    align: "left",
    label: "ประเภทคดี",
    sortable: true,
    field: "caseType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "caseNumber",
    align: "left",
    label: "คดีเลขที่",
    sortable: true,
    field: "caseNumber",
    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: "citizenId",
    align: "left",
    label: "รหัสบัตรประชาชน",
    sortable: true,
    field: "citizenId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px; width:10%;",
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "status",
    align: "left",
    label: "สถานะของคำร้อง",
    sortable: false,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

//นำข้อมูลมาแสดง
async function getData() {
  isload.value = true;
  const params = new URLSearchParams({
    status: formData.status,
    type: formData.type,
    year: String(formData.year),
    page: String(pagination.value.page),
    pageSize: String(pagination.value.rowsPerPage),
    keyword: filterKeyword.value,
  });

  if (pagination.value.sortBy) {
    params.append("sortBy", pagination.value.sortBy);
    params.append("descending", String(pagination.value.descending));
  }

  await http
    .get(config.API.appealMainList() + `?${params.toString()}`)
    .then(async (res) => {
      const result = res.data.result;
      pagination.value.rowsNumber = result.total;
      dataStore.fetchAppealComplain(result.data);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      isload.value = false;
    });
}

/**
 * กดเพื่อย้อนกลับ
 */
function clickBack() {
  router.push(`/`);
}

/** ดึงข้อมูลเมื่อมีการปรับฟิลเตอร์ */
function dataUpdate() {
  getSearch();
}

/** ดึงข้อมูลจาก keyword*/
function filterFn() {
  getSearch();
}

/**
 * เปิดหน้าแก้ไข
 * @param id id ของ บุคคล
 */
function editPage(id: string) {
  router.push(`/appeal-complain/${id}`);
}

function redirectToPageadd() {
  router.push(`/appeal-complain/add`);
}

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

/**
 * ฟังก์ชันรับ request จากตาราง เมื่อมีการเปลี่ยน pagination
 * @param requestProps ข้อมูลการร้องขอจากตาราง
 */
function onTableRequest(requestProps: PropsTable.RequestProps) {
  const newPagination = requestProps?.pagination || requestProps;
  if (!newPagination?.page || !newPagination?.rowsPerPage) return;
  pagination.value = { ...newPagination };
  getData();
}

/**
 * เรียกฟังก์ชันทั้งหมดตอนเรียกใช้ไฟล์นี้
 */
onMounted(async () => {
  dataStore.visibleColumns = visibleColumns.value;
  dataStore.columns = columns.value;

  await getData();
});
</script>

<template>
  <div class="col-12 row justify-center">
    <div class="col-xs-12 col-sm-12 col-md-11">
      <div class="toptitle text-white col-12 row items-center">
        <q-btn
          icon="mdi-arrow-left"
          unelevated
          round
          dense
          flat
          color="primary"
          class="q-mr-sm"
          @click="clickBack"
        />
        อุทธรณ์/ร้องทุกข์
      </div>
      <div class="col-12">
        <q-card bordered class="q-pa-md">
          <q-btn
            id="addComplaints"
            for="addComplaints"
            flat
            round
            color="primary"
            icon="mdi-plus"
            @click="redirectToPageadd()"
          >
            <q-tooltip>เพิ่มการอุทธรณ์/ร้องทุกข์</q-tooltip>
          </q-btn>

          <div class="row col-12 q-col-gutter-sm q-mb-sm">
            <div class="col-xs-12 col-md-2">
              <datepicker
                v-model="formData.year"
                class="col-2"
                :locale="'th'"
                autoApply
                year-picker
                :enableTimePicker="false"
                @update:model-value="dataUpdate"
              >
                <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(formData.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-md-2">
              <q-select
                v-model="formData.type"
                label="ประเภท"
                dense
                outlined
                emit-value
                map-options
                option-label="name"
                option-value="id"
                :options="type"
                @update:model-value="dataUpdate"
              />
            </div>
            <div class="col-xs-12 col-md-2">
              <q-select
                v-model="formData.status"
                label="สถานะ"
                dense
                outlined
                emit-value
                map-options
                option-label="name"
                option-value="id"
                :options="dataStore.statusOptions"
                @update:model-value="getSearch"
              />
            </div>
            <q-space />

            <q-input
              class="col-xs-12 col-sm-3 col-md-2"
              id="filterTable"
              for="filterTable"
              dense
              outlined
              v-model="filterKeyword"
              label="ค้นหา"
              debounce="300"
              @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="(filterKeyword = ''), getSearch()"
                />
              </template>
            </q-input>

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

            <div class="col-12">
              <d-table
                flat
                bordered
                dense
                :rows="dataStore.rows"
                :columns="dataStore.columns"
                :visible-columns="dataStore.visibleColumns"
                :rows-per-page-options="[10, 25, 50, 100]"
                @request="onTableRequest"
                v-model:pagination="pagination"
                :loading="isload"
              >
                <template v-slot:header="props">
                  <q-tr :props="props">
                    <q-th
                      v-for="col in props.cols"
                      :key="col.name"
                      :props="props"
                      style="color: #000000; font-weight: 500"
                    >
                      <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.stop.prevent="editPage(props.row.id)"
                    >
                      <div v-if="col.name == 'no'">
                        {{ props.rowIndex + 1 }}
                      </div>

                      <div v-else>
                        {{ col.value ? col.value : "-" }}
                      </div>
                    </q-td>
                  </q-tr>
                </template>

                <template #item="props">
                  <div class="q-pa-xs col-xs-12 col-sm-6 col-md-4 col-lg-3">
                    <q-card bordered flat>
                      <q-list @click.stop.prevent="editPage(props.row.id)">
                        <q-item v-for="col in props.cols" :key="col.name">
                          <q-item-section>
                            <q-item-label caption>{{ col.label }}</q-item-label>

                            <q-item-label v-if="col.name === 'no'">
                              {{ props.rowIndex + 1 }}
                            </q-item-label>

                            <q-item-label v-else>{{ col.value }}</q-item-label>
                          </q-item-section>
                        </q-item>
                      </q-list>
                    </q-card>
                  </div>
                </template>
              </d-table>
            </div>
          </div>
        </q-card>
      </div>
    </div>
  </div>
</template>

<style lang="scss"></style>
