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

import { useRequestEditStore } from "@/modules/04_registryPerson/stores/RequestEdit";
import { useCounterMixin } from "@/stores/mixin";
import { useRouter, useRoute } from "vue-router";
import { usePagination } from "@/composables/usePagination";
import config from "@/app.config";
import http from "@/plugins/http";

/** importType*/
import type { QTableProps } from "quasar";
import type {
  DataOption,
  Request,
} from "@/modules/04_registryPerson/interface/index/Main";
import type { DataRequest } from "@/modules/04_registryPerson/interface/response/Main";

const $q = useQuasar();
const router = useRouter();
const route = useRoute();
const store = useRequestEditStore();
const { showLoader, hideLoader, messageError, date2Thai } = useCounterMixin();
const { pagination, params, onRequest } = usePagination("", fetchListRequset);

const routerName = ref<string>(route.name as string);
//Table
const rows = ref<DataRequest[]>([]); //รายการข้อมูลคำร้องขอแก้ไขทะเบียนประวัติ
const columns = ref<QTableProps["columns"]>([
  {
    name: "createdAt",
    align: "left",
    label: "วันที่ยื่นขอ",
    sortable: false,
    field: "createdAt",
    format: (v) => (v ? date2Thai(v, false, true) : "-"),
    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: "topic",
    align: "left",
    label: "ชื่อเรื่อง",
    sortable: true,
    field: "topic",
    format: (v) => (v ? v : "-"),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "detail",
    align: "left",
    label: "รายละเอียด",
    sortable: true,
    field: "detail",
    format: (v) => (v ? v : "-"),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "status",
    align: "left",
    label: "สถานะคำร้อง",
    sortable: false,
    field: "status",
    format: (v) => store.convertStatus(v),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "remark",
    align: "left",
    label: "หมายเหตุ",
    sortable: true,
    field: "remark",
    format: (v) => (v ? v : "-"),
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>([
  "createdAt",
  "fullname",
  "topic",
  "detail",
  "status",
  "remark",
]);

//ตัวแปร
const status = ref<string>("PENDING"); //ค้นหาตามสถานะ
const keyword = ref<string>(""); //คำค้นหา
const statusOption = ref<DataOption[]>(store.optionStatus); //รายการสถานะ
const requestId = ref<string>(""); //id รายการแก้ไข

/** function fetch รายการคำร้องขอแก้ไขทะเบียนประวัติ*/
async function fetchListRequset() {
  showLoader();
  await http
    .get(
      config.API.requestEditByType(
        routerName.value == "registryNewRequestEditEMP" ? "-employee" : ""
      ) + `admin`,
      {
        params: {
          ...params.value,
          status: status.value,
          keyword: keyword.value.trim(),
        },
      }
    )
    .then((res) => {
      const data = res.data.result;
      pagination.value.rowsNumber = data.total;
      rows.value = data.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** function เลือกสถานะคำร้อง*/
function updateStatusValue() {
  pagination.value.page = 1;
  // fetch รายการคำร้องขอแก้ไขทะเบียนประวัติ
  fetchListRequset();
}

/** function เคลียร์ สถานะคำร้อง*/
function clearStatus() {
  status.value = "";
  statusOption.value = store.optionStatus;
}

/**
 * function ค้นหาคำใน select  สถานะคำร้อง
 * @param val คำค้น
 * @param update Function
 */
function filterOption(val: string, update: Function) {
  update(() => {
    statusOption.value = store.optionStatus.filter(
      (v: DataOption) => v.name.indexOf(val) > -1
    );
  });
}

/**
 * funciton  แก่ไขคำร้อง
 * @param id รายการคำร้อง
 */
function onclickEdit(data: Request) {
  requestId.value = data.id;
  store.profileId = data.profileId;
  if (routerName.value === "registryNewRequestEditEMP") {
    router.push(`/registry-employee/request-edit/personal/${data.id}`);
  } else {
    router.push(`/registry-officer/request-edit/personal/${data.id}`);
  }
}

/**  HooK lifecycle ทำงานเมื่อมีการเรียกใช้งาน Componenets */
onMounted(() => {
  fetchListRequset();
});
</script>

<template>
  <q-card class="q-pa-md">
    <div class="row q-mb-sm q-col-gutter-sm">
      <div class="col-xs-12 col-sm-3 col-md-3">
        <q-select
          style="min-width: 250px"
          v-model="status"
          label="สถานะคำร้อง"
          dense
          outlined
          emit-value
          map-options
          option-label="name"
          option-value="id"
          hide-selected
          fill-input
          :options="statusOption"
          @update:model-value="updateStatusValue"
          :clearable="status !== ''"
          @clear="clearStatus"
          use-input
          @filter="(inputValue:string,
          doneFn:Function) => filterOption(inputValue, doneFn
          ) "
        >
          <template v-slot:no-option>
            <q-item>
              <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
            </q-item>
          </template>
        </q-select>
      </div>
      <q-space />
      <q-input
        v-model="keyword"
        outlined
        dense
        label="ค้นหา"
        style="min-width: 250px"
        @keydown.enter.prevent="updateStatusValue()"
      >
        <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 class="col-12">
      <p-table
        :columns="columns"
        :rows="rows"
        row-key="id"
        :rows-per-page-options="[10, 25, 50, 100]"
        :paging="true"
        :visible-columns="visibleColumns"
        @request="onRequest"
        v-model:pagination="pagination"
      >
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th auto-width />
            <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 auto-width>
              <q-btn
                icon="edit"
                round
                dense
                flat
                color="edit
                "
                @click.prevent="onclickEdit(props.row)"
              >
                <q-tooltip>แก้ไขสถานะคำร้อง</q-tooltip>
              </q-btn>
            </q-td>
            <q-td v-for="col in props.cols" :key="col.name" :props="props">
              {{ col.value ? col.value : "-" }}
            </q-td>
          </q-tr>
        </template>
      </p-table>
    </div>
  </q-card>
</template>

<style scoped></style>
