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

import config from "@/app.config";
import http from "@/plugins/http";
import router from "@/router";
import { useCounterMixin } from "@/stores/mixin";
import { useInvestigateFactStore } from "@/modules/11_discipline/store/InvestigateFactStore";
import { checkPermission } from "@/utils/permissions";

const $q = useQuasar(); //ใช้ noti quasar
const mixin = useCounterMixin();
const dataInvestigate = useInvestigateFactStore();
const { messageError, showLoader, hideLoader } = mixin;

const option = ref<any[]>(dataInvestigate.statusOptions);

/** ค้นหาข้อมูลในตาราง */
const filterKeyword = ref<string>("");
const filterRef = ref<HTMLInputElement | null>(null);
const statusFilter = ref<string>("NEW");
const toptitle = ref<number>(0);

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

const attrs = ref<any>(useAttrs());

/** ล้างค่า Input  */
function resetFilter() {
  filterKeyword.value = "";
  if (filterRef.value) {
    filterRef.value.focus();
    getList();
  }
}

/** ดึงข้อมูลบสวน */
async function getList() {
  showLoader();
  await http
    .get(
      config.API.investigateMain(
        pagination.value.page,
        pagination.value.rowsPerPage,
        filterKeyword.value.trim(),
        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;
      dataInvestigate.fecthList(data);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ไปหน้าแก้ไข
 * @param id ไอดีเฉพาะ รายบุคคล
 */
async function editPage(id: string) {
  dataInvestigate.tabMenu = await "investigatefacts";
  router.push(`/discipline/investigatefacts/${id}`);
}
/**
 * ไปหน้าแก้ไข
 * @param id ไอดีเฉพาะ รายบุคคล
 */
async function detailPage(id: string) {
  dataInvestigate.tabMenu = await "investigatefacts";
  router.push(`/discipline-detail/investigatefacts/${id}`);
}

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

function updatePagination(newPagination: any) {
  pagination.value.page = 1;
  pagination.value.rowsPerPage = newPagination.rowsPerPage;
}

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

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

/**เมื่อเริ่มโหลดหน้า
 * ส่งข้อมูลจำลองไปยัง store
 */
onMounted(async () => {
  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">
      <div class="col-xs-12 col-sm-4 col-md-3">
        <q-select
          v-model="statusFilter"
          label="สถานะ"
          dense
          outlined
          emit-value
          map-options
          hide-selected
          fill-input
          option-label="name"
          option-value="id"
          :options="option"
          @update:model-value="getSerach()"
          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 = dataInvestigate.statusOptions),
                  (statusFilter = 'ALL'),
                  getSerach()
              "
              class="cursor-pointer"
            />
          </template>
        </q-select>
      </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="getSerach()"
      >
        <template v-slot:append>
          <q-icon  name="search" />
        </template>
      </q-input>

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

    <div class="col-12">
      <d-table
        ref="table"
        :columns="dataInvestigate.columns"
        :rows="dataInvestigate.rows"
        row-key="interrogated"
        flat
        bordered
        :paging="true"
        dense
        class="custom-header-table"
        v-bind="attrs"
        :visible-columns="dataInvestigate.visibleColumns"
        :rows-per-page-options="[10, 25, 50, 100]"
        @update:pagination="updatePagination"
      >
        <template v-slot:header="props">
          <q-tr :props="props">
            <q-th auto-width></q-th>
            <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-th auto-width />
          </q-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td auto-width>
              <q-btn
                v-if="checkPermission($route)?.attrIsGet"
                flat
                dense
                round
                color="info"
                icon="mdi-eye"
                @click="detailPage(props.row.id)"
              >
                <q-tooltip>รายละเอียด</q-tooltip>
              </q-btn>
              <q-btn
                v-if="
                  checkPermission($route)?.attrIsGet &&
                  checkPermission($route)?.attrIsUpdate
                "
                flat
                dense
                round
                color="edit"
                icon="edit"
                @click="editPage(props.row.id)"
              >
                <q-tooltip>แก้ไขข้อมูล</q-tooltip>
              </q-btn>
            </q-td>
            <q-td v-for="col in props.cols" :key="col.name" :props="props">
              <div v-if="col.name == 'no'">
                {{
                  (pagination.page - 1) * pagination.rowsPerPage +
                  props.rowIndex +
                  1
                }}
              </div>
              <div v-else-if="col.name === 'title'" class="table_ellipsis">
                {{ props.row.title }}
              </div>
              <div v-else>
                {{ col.value }}
              </div>
            </q-td>
            <q-td
              auto-width
              style="font-size: 14px; width: 10%"
              @click="editPage(props.row.id)"
            >
              {{ props.row.active }}
            </q-td>
          </q-tr>
        </template>
        <template v-slot:pagination="scope">
          ทั้งหมด {{ total }} รายการ
          <q-pagination
            v-model="pagination.page"
            active-color="primary"
            color="dark"
            :max="Number(totalList)"
            size="sm"
            boundary-links
            direction-links
            :max-pages="5"
            @update:model-value="getList()"
          ></q-pagination>
        </template>
      </d-table>
    </div>
  </q-card>
</template>
