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

// importStroe
import config from "@/app.config";
import http from "@/plugins/http";

import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import { useComplainstDataStore } from "@/modules/11_discipline/store/ComplaintsStore";
import { useDisciplineMainStore } from "@/modules/11_discipline/store/Main";
import { usePagination } from "@/composables/usePagination";

import type { DataOption } from "@/modules/11_discipline/interface/index/Main";

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

const $q = useQuasar();
const router = useRouter();
const store = useDisciplineMainStore();
const mixin = useCounterMixin();
const complainstStore = useComplainstDataStore();
const { fetchComplainst } = complainstStore;
const { showLoader, messageError, hideLoader, convertDateToAPI } = mixin;
const { pagination, params, onRequest } = usePagination("", getList);

const filterKeyword = ref<string>("");
const statusFilter = ref<string>("NEW");
const option = ref<DataOption[]>(complainstStore.statusOptions);

/** ดึงข้อมูล เรื่องร้องเรียน */
async function getList() {
  const body = {
    ...params.value,
    keyword: filterKeyword.value.trim(),
    status: statusFilter.value,
    ...(store.formComplaint.dateReceived?.[0] && {
      dateReceivedStart: convertDateToAPI(store.formComplaint.dateReceived[0]),
    }),
    ...(store.formComplaint.dateReceived?.[1] && {
      dateReceivedEnd: convertDateToAPI(store.formComplaint.dateReceived[1]),
    }),
    ...(store.formComplaint.respondentType && {
      respondentType: store.formComplaint.respondentType,
    }),
    ...(store.formComplaint.offenseDetails && {
      offenseDetails: store.formComplaint.offenseDetails,
    }),
    ...(store.formComplaint.levelConsideration && {
      levelConsideration: store.formComplaint.levelConsideration,
    }),
    ...(store.formComplaint.dateConsideration?.[0] && {
      dateConsiderationStart: convertDateToAPI(
        store.formComplaint.dateConsideration[0]
      ),
    }),
    ...(store.formComplaint.dateConsideration?.[1] && {
      dateConsiderationEnd: convertDateToAPI(
        store.formComplaint.dateConsideration[1]
      ),
    }),
  };
  showLoader();
  await http
    .post(config.API.complaintList(), body)
    .then(async (res) => {
      const result = res.data.result;
      pagination.value.rowsNumber = result.total;
      await fetchComplainst(result.data);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

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

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

/** เรียกใช้งาน ฟังชั่น ตอนเริ่มโหลดหน้า */
onMounted(async () => {
  await getList();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการเรื่องร้องเรียน
  </div>
  <q-card flat bordered>
    <div class="row q-col-gutter-sm q-pa-md">
      <div class="col-12">
        <div class="row q-col-gutter-sm">
          <div class="col-xs-12 col-sm-3 col-md-4 col-lg-2">
            <div class="row q-col-gutter-sm items-center">
              <div class="col-xs-11">
                <q-select
                  v-model="statusFilter"
                  label="สถานะ"
                  dense
                  outlined
                  emit-value
                  map-options
                  option-label="name"
                  option-value="id"
                  hide-selected
                  fill-input
                  :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
                class="col-xs justify-center row"
                v-if="checkPermission($route)?.attrIsCreate"
              >
                <q-btn
                  id="addComplaints"
                  for="addComplaints"
                  dense
                  flat
                  round
                  color="primary"
                  icon="mdi-plus"
                  @click="redirectToPageadd()"
                  ><q-tooltip>เพิ่มเรื่องร้องเรียน </q-tooltip></q-btn
                >
              </div>
            </div>
          </div>

          <q-space />

          <div class="col-xs-12 col-sm-8 col-md-6 col-lg-4">
            <div class="row q-col-gutter-sm items-center">
              <div class="col justify-center row">
                <DialogSearchAdvanced :get-data="() => getSearch()" />
              </div>
              <div class="col-7">
                <q-input
                  for="#search"
                  standout
                  dense
                  v-model="filterKeyword"
                  ref="filterRef"
                  outlined
                  placeholder="ค้นหาเรื่องร้องเรียน"
                  @keydown.enter.prevent="getSearch()"
                >
                  <template v-slot:append>
                    <q-icon name="search" />
                  </template>
                </q-input>
              </div>

              <div class="col-4">
                <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"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="col-12">
        <TableComplaint
          v-model:pagination="pagination"
          :on-request="onRequest"
        />
      </div>
    </div>
  </q-card>
</template>

<style scoped></style>
