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

import config from "@/app.config";
import http from "@/plugins/http";
import { useRoute } from "vue-router";
import { checkPermission } from "@/utils/permissions";
import { useCounterMixin } from "@/stores/mixin";
import { useDisciplineDirectorDataStore } from "@/modules/11_discipline/store/DirectorStore";
import { useDisciplineMainStore } from "@/modules/11_discipline/store/Main";
import { usePagination } from "@/composables/usePagination";

import type { DirectorRowsResponse } from "@/modules/11_discipline/interface/response/director";

import DialogTotal from "@/modules/11_discipline/components/6_BasicInformation/Director/DialogInvestigateTotal.vue";
import DialogEdit from "@/modules/11_discipline/components/6_BasicInformation/Director/DialogEdit.vue";

const $q = useQuasar();
const dataStore = useDisciplineDirectorDataStore();
const mainStore = useDisciplineMainStore();
const route = useRoute();
const mixin = useCounterMixin();
const { messageError, showLoader, hideLoader, dialogRemove, success } = mixin;
const { pagination, params, onRequest } = usePagination("", getList);

const titleInvestigate = ref<string>("");
const personalId = ref<string>("");

const modalDetail = ref<boolean>(false);
const isEdit = ref<boolean>(false);
const modalEdit = ref<boolean>(false);
const type = ref<string>("");
const dataPopUp = ref<DirectorRowsResponse>();
/**
 * ค้นหาในตาราง
 */
const filterKeyword = ref<string>("");
const filterRef = ref<HTMLInputElement | null>(null);

async function getList() {
  showLoader();
  await http
    .get(
      config.API.directorListMain +
        `${mainStore.pathDirector(route.name as string)}`,
      {
        params: {
          ...params.value,
          keyword: filterKeyword.value.trim(),
        },
      }
    )
    .then((res) => {
      const result = res.data.result;
      pagination.value.rowsNumber = result.total;
      dataStore.fetchData(result.data);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ลบข้อมูล
 * @param id ไอดีของข้อมูล
 */
function clickDelete(id: string) {
  dialogRemove($q, async () => {
    showLoader();
    await http
      .delete(config.API.directorbyId(id))
      .then(async () => {
        await getList();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(async () => {
        hideLoader();
      });
  });
}

function openDetail(data: DirectorRowsResponse, typeChange: string) {
  if (typeChange == "investigate") {
    titleInvestigate.value = `รายการสืบสวนข้อเท็จจริงของ ${data.fullName}`;
  } else if (typeChange == "disciplinary") {
    titleInvestigate.value = `รายการสอบสวนความผิดทางวินัยของ ${data.fullName}`;
  }
  dataPopUp.value = data;
  modalDetail.value = true;
  type.value = typeChange;
}

function closeDetail() {
  modalDetail.value = false;
}

function onEdit(id: string, check: boolean) {
  modalEdit.value = true;
  personalId.value = id;
  isEdit.value = check;
}

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

/**เมื่อเริ่มโหลดหน้า
 * ส่งข้อมูลจำลองไปยัง store
 */
onMounted(() => {
  getList();
});
</script>
<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการชื่อกรรมการ
  </div>
  <q-card flat bordered>
    <div class="col-12 q-pa-md q-col-gutter-sm">
      <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 items-center">
              <q-btn
                v-if="checkPermission($route)?.attrIsCreate"
                @click="$router.push(`/discipline/director/add`)"
                flat
                dense
                round
                color="primary"
                icon="mdi-plus"
              >
                <q-tooltip>เพิ่มรายชื่อกรรมการ</q-tooltip>
              </q-btn>
            </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-7">
                <q-input
                  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-5">
                <q-select
                  v-model="dataStore.visibleColumns"
                  multiple
                  outlined
                  dense
                  options-dense
                  :display-value="$q.lang.table.columns"
                  emit-value
                  map-options
                  :options="dataStore.columns"
                  option-value="name"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="col-12">
        <p-table
          :columns="dataStore.columns"
          :rows="dataStore.rows"
          row-key="tb-list"
          flat
          bordered
          :paging="true"
          dense
          :rows-per-page-options="[10, 25, 50, 100]"
          :visible-columns="dataStore.visibleColumns"
          v-model:pagination="pagination"
          @request="onRequest"
        >
          <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
                  v-if="checkPermission($route)?.attrIsGet"
                  dense
                  flat
                  round
                  color="info"
                  @click="onEdit(props.row.id, false)"
                  icon="mdi-eye"
                >
                  <q-tooltip>รายละเอียด</q-tooltip>
                </q-btn>
                <q-btn
                  v-if="
                    checkPermission($route)?.attrIsUpdate &&
                    checkPermission($route)?.attrIsGet
                  "
                  dense
                  flat
                  round
                  color="edit"
                  @click="onEdit(props.row.id, true)"
                  icon="edit"
                >
                  <q-tooltip>แก้ไขข้อมูล</q-tooltip>
                </q-btn>
                <q-btn
                  v-if="checkPermission($route)?.attrIsDelete"
                  dense
                  flat
                  round
                  color="red"
                  @click="clickDelete(props.row.id)"
                  icon="mdi-delete"
                >
                  <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 == 'totalInvestigate' &&
                    props.row.totalInvestigate > 0
                  "
                  :class="
                    checkPermission($route)?.attrIsGet
                      ? 'text-blue cursor-pointer'
                      : ''
                  "
                  @click="
                    checkPermission($route)?.attrIsGet
                      ? openDetail(props.row, 'investigate')
                      : ''
                  "
                >
                  {{ props.row.totalInvestigate }}
                </div>
                <div
                  v-else-if="
                    col.name == 'totalDisciplinary' &&
                    props.row.totalDisciplinary > 0
                  "
                  :class="
                    checkPermission($route)?.attrIsGet
                      ? 'text-blue cursor-pointer'
                      : ''
                  "
                  @click="
                    checkPermission($route)?.attrIsGet
                      ? openDetail(props.row, 'disciplinary')
                      : ''
                  "
                >
                  {{ props.row.totalDisciplinary }}
                </div>
                <div v-else>
                  {{ col.value ?? "-" }}
                </div>
              </q-td>
            </q-tr>
          </template>
        </p-table>
      </div>
    </div>
  </q-card>

  <DialogTotal
    :modal="modalDetail"
    :title="titleInvestigate"
    :close="closeDetail"
    :type="type"
    :data-list="dataPopUp"
  />

  <DialogEdit
    v-model:modal="modalEdit"
    v-model:personal-id="personalId"
    :is-edit="isEdit"
    :get-list="getList"
  />
</template>
