<script setup lang="ts">
import { ref, onMounted, watch } 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 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 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);

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.directorList(
        pagination.value.page,
        pagination.value.rowsPerPage,
        filterKeyword.value.trim(),
        mainStore.pathDirector(route.name as string)
      )
    )
    .then((res) => {
      const data = res.data.result.data;
      totalList.value = Math.ceil(
        res.data.result.total / pagination.value.rowsPerPage
      );
      total.value = res.data.result.total;
      dataStore.fetchData(data);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/**
 * ลบข้อมูล
 * @param id ไอดีของข้อมูล
 */
function clickDelete(id: string) {
  dialogRemove($q, async () => deleteData(id), `ลบข้อมูล`);
}

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

function resetFilter() {
  filterKeyword.value = "";
  if (filterRef.value) {
    filterRef.value.focus();
    getSearch();
  }
}

function filterFn() {
  getSearch();
}

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 updatePagination(newPagination: any) {
  pagination.value.page = 1;
  pagination.value.rowsPerPage = newPagination.rowsPerPage;
}

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

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

/**เมื่อเริ่มโหลดหน้า
 * ส่งข้อมูลจำลองไปยัง store
 */
onMounted(() => {
  getList();
  // get ข้อมูลแล้วโยนใส่ store
});
</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>
        <q-btn
          v-if="checkPermission($route)?.attrIsCreate"
          @click="$router.push(`/discipline/director/add`)"
          flat
          dense
          round
          color="add"
          icon="mdi-plus"
        >
          <q-tooltip>เพิ่มรายชื่อกรรมการ</q-tooltip>
        </q-btn>
      </div>
      <q-space />

      <q-input
        class="col-xs-12 col-sm-3 col-md-2"
        standout
        dense
        v-model="filterKeyword"
        ref="filterRef"
        outlined
        placeholder="ค้นหา"
        @keydown.enter.prevent="filterFn"
      >
        <template v-slot:append>
          <q-icon name="search" />
        </template>
      </q-input>

      <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"
        
        style="min-width: 140px"
        class="col-xs-12 col-sm-3 col-md-2"
      />
    </div>

    <div class="col-12">
      <d-table
        :columns="dataStore.columns"
        :rows="dataStore.rows"
        row-key="tb-list"
        flat
        bordered
        :paging="true"
        dense
        :rows-per-page-options="[10, 25, 50, 100]"
        @update:pagination="updatePagination"
        :visible-columns="dataStore.visibleColumns"
      >
        <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>
        <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'">
                {{
                  (pagination.page - 1) * pagination.rowsPerPage +
                  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>
      </d-table>
    </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>
