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

// importStroe
import { useCounterMixin } from "@/stores/mixin";
import { useComplainstDataStore } from "@/modules/11_discipline/store/ComplaintsStore";

// impoet Components
import TableComplaint from "@/modules/11_discipline/components/1_Complaint/TableComplaint.vue";

import config from "@/app.config";
import http from "@/plugins/http";
import { checkPermission } from "@/utils/permissions";

const $q = useQuasar();
const mixin = useCounterMixin();

const { showLoader, messageError, hideLoader } = mixin;
const router = useRouter();

/** stoer */
const complainstStore = useComplainstDataStore();
const { fetchComplainst } = complainstStore;
const filterRef = ref<HTMLInputElement | null>(null);
const filterTable = ref<string>("");
const filterKeyword = ref<string>("");

const toptitle = ref<number>(0);
const statusFilter = ref<string>("NEW");
const option = ref<any[]>(complainstStore.statusOptions);

const total = ref<number>(0);
const totalList = ref<number>(1);
const pagination = ref({
  sortBy: "createdAt",
  descending: true,
  page: 1,
  rowsPerPage: 10,
});

/** ดึงข้อมูล เรื่องร้องเรียน */
async function getList() {
  showLoader();
  await http
    .get(
      config.API.complaintList(
        pagination.value.page,
        pagination.value.rowsPerPage,
        filterKeyword.value,
        statusFilter.value
      )
    )
    //
    .then((res) => {
      totalList.value = Math.ceil(
        res.data.result.total / pagination.value.rowsPerPage
      );
      total.value = res.data.result.total;
      toptitle.value = res.data.result.total;
      const data = res.data.result.data;
      fetchComplainst(data);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ไปยังหน้าเพิ่มข้อมูล */
function redirectToPageadd() {
  router.push(`/discipline/complaints/add`);
}

/** ล้างค่าใน input */
function resetFilter() {
  filterKeyword.value = "";
  pagination.value.page = 1;
  if (filterRef.value) {
    filterRef.value.focus();
    getList();
  }
}

/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update function
 */
function filterOptionFn(val: string, update: Function) {
  statusFilter.value = "";
  update(() => {
    option.value = complainstStore.statusOptions.filter(
      (e: any) => e.name.search(val) !== -1
    );
  });
}

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

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

/** เรียกใช้งาน ฟังชั่น ตอนเริ่มโหลดหน้า */
onMounted(async () => {
  await 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-pa-md">
    <div class="row col-12 q-col-gutter-sm q-mb-sm items-center">
      <div class="col-4">
        <q-select
          v-model="statusFilter"
          label="สถานะ"
          dense
          outlined
          emit-value
          map-options
          option-label="name"
          option-value="id"
          :options="option"
          @update:model-value="getSearch()"
          use-input
          @filter="filterOptionFn"
        >
          <template v-slot:no-option>
            <q-item>
              <q-item-section class="text-grey"> ไม่มีข้อมูล </q-item-section>
            </q-item>
          </template>
          <template v-if="statusFilter !== 'ALL'" v-slot:append>
            <q-icon
              name="cancel"
              @click.stop.prevent="
                (option = complainstStore.statusOptions),
                  (statusFilter = 'ALL'),
                  getSearch()
              "
              class="cursor-pointer"
            />
          </template>
        </q-select>
      </div>
      <div>
        <q-btn
          v-if="checkPermission($route)?.attrIsCreate"
          id="addComplaints"
          for="addComplaints"
          dense
          flat
          round
          color="primary"
          icon="mdi-plus"
          @click="redirectToPageadd()"
          ><q-tooltip>เพิ่มเรื่องร้องเรียน </q-tooltip></q-btn
        >
      </div>
      <q-space />

      <q-input
        for="#search"
        class="col-xs-12 col-sm-3 col-md-2"
        standout
        dense
        v-model="filterKeyword"
        ref="filterRef"
        outlined
        placeholder="ค้นหา"
        @keydown.enter.prevent="getSearch()"
      >
        <template v-slot:append>
          <q-icon v-if="filterKeyword == ''" name="search" />
          <q-icon
            v-if="filterKeyword !== ''"
            name="clear"
            class="cursor-pointer"
            @click="resetFilter"
          />
        </template>
      </q-input>

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

    <div class="col-12">
      <TableComplaint
        :filter-table="filterTable"
        v-model:pagination="pagination"
        v-model:total="total"
        v-model:total-list="totalList"
        :toptitle="toptitle"
        :get-list="getList"
      />
    </div>
  </q-card>
</template>

<style scoped></style>
