<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 { useDisciplineMainStore } from "@/modules/11_discipline/store/Main";
import { checkPermission } from "@/utils/permissions";
import { usePagination } from "@/composables/usePagination";

import DialogSearchAdvanced from "@/modules/11_discipline/components/DialogSearchAdvanced.vue";

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

const $q = useQuasar(); //ใช้ noti quasar
const store = useDisciplineMainStore();
const mixin = useCounterMixin();
const dataInvestigate = useInvestigateFactStore();
const { messageError, showLoader, hideLoader, convertDateToAPI } = mixin;
const { pagination, params, onRequest } = usePagination("", getList);

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

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

/** ดึงข้อมูลบสวน */
async function getList() {
  const body = {
    ...params.value,
    keyword: filterKeyword.value.trim(),
    status: statusFilter.value,
    ...(store.formInvestigateFacts.respondentType && {
      respondentType: store.formInvestigateFacts.respondentType,
    }),
    ...(store.formInvestigateFacts.offenseDetails && {
      offenseDetails: store.formInvestigateFacts.offenseDetails,
    }),
    ...(store.formInvestigateFacts.investigationDetail && {
      investigationDetail: store.formInvestigateFacts.investigationDetail,
    }),
    ...(store.formInvestigateFacts.investigationDate?.[0] && {
      investigationDateStart: convertDateToAPI(
        store.formInvestigateFacts.investigationDate[0]
      ),
    }),
    ...(store.formInvestigateFacts.investigationDate?.[1] && {
      investigationDateEnd: convertDateToAPI(
        store.formInvestigateFacts.investigationDate[1]
      ),
    }),
    ...(store.formInvestigateFacts.dateReceived?.[0] && {
      dateReceivedStart: convertDateToAPI(
        store.formInvestigateFacts.dateReceived[0]
      ),
    }),
    ...(store.formInvestigateFacts.dateReceived?.[1] && {
      dateReceivedEnd: convertDateToAPI(
        store.formInvestigateFacts.dateReceived[1]
      ),
    }),
    ...(store.formInvestigateFacts.investigationStatusResult && {
      investigationStatusResult:
        store.formInvestigateFacts.investigationStatusResult,
    }),
  };
  showLoader();
  await http
    .post(config.API.investigateMain(), body)
    .then(async (res) => {
      const result = res.data.result;
      pagination.value.rowsNumber = result.total;
      await dataInvestigate.fecthList(result.data);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

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

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

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

onMounted(() => {
  getList();
});
</script>

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการสืบสวนข้อเท็จจริง
  </div>

  <q-card flat bordered>
    <div class="row col-12 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">
            <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="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 = dataInvestigate.statusOptions),
                      (statusFilter = 'ALL'),
                      getSearch()
                  "
                  class="cursor-pointer"
                />
              </template>
            </q-select>
          </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
                  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"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="col-12">
        <p-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]"
          @request="onRequest"
          v-model:pagination="pagination"
        >
          <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 && 
                    props.row.statusMain != 'SEND_DISCIPLINARY'
                  "
                  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'">
                  {{ 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>
        </p-table>
      </div>
    </div>
  </q-card>
</template>
