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

import http from "@/plugins/http";
import config from "@/app.config";
import { useRouter } from "vue-router";
import { useQuasar } from "quasar";
import { useCounterMixin } from "@/stores/mixin";
import { useAppealComplainStore } from "@/modules/11_discipline/store/AppealComplainStore";
import { checkPermission } from "@/utils/permissions";

import type { QTableProps } from "quasar";
import type { RowList } from "@/modules/11_discipline/interface/response/appealComplain";
import type { DataOption } from "@/modules/11_discipline/interface/index/Main";

import DialogStatus from "@/modules/11_discipline/components/8_AppealComplain/dialog/DialogEditStatus.vue";

const $q = useQuasar();
const router = useRouter();
const mixin = useCounterMixin();
const { showLoader, messageError, hideLoader, dialogConfirm } = mixin;

const modalStatusEdit = ref<boolean>(false);
/** stoer */
const dataStore = useAppealComplainStore();
const { fetchAppealComplain } = dataStore;
const type = ref<DataOption[]>([
  { id: "ALL", name: "ทั้งหมด" },
  ...dataStore.typeOptions,
]);

const filterKeyword = ref<string>("");
const dataRow = ref<RowList[]>([]);

const formData = reactive<any>({
  type: "ALL",
  status: "NEW",
  year: new Date().getFullYear().toString(),
});

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

const visibleColumns = ref<string[]>([
  "no",
  "type",
  "title",
  "fullname",
  "citizenId",
  "year",
  "caseType",
  "caseNumber",
  "description",
  "lastUpdatedAt",
  "status",
]);

// หัวตาราง
const columns = ref<QTableProps["columns"]>([
  {
    name: "no",
    align: "center",
    label: "ลำดับ",
    sortable: false,
    field: "no",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "type",
    align: "left",
    label: "ประเภท",
    sortable: true,
    field: "type",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "title",
    align: "left",
    label: "เรื่องอุทธรณ์/ร้องทุกข์",
    sortable: true,
    field: "title",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "fullname",
    align: "left",
    label: "ชื่อ-นามสกุล",
    sortable: true,
    field: "fullname",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "citizenId",
    align: "left",
    label: "เลขประจำตัวประชาชน",
    sortable: true,
    field: "citizenId",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "year",
    align: "left",
    label: "ปีงบประมาณ",
    sortable: true,
    field: "year",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "caseType",
    align: "left",
    label: "ประเภทคดี",
    sortable: true,
    field: "caseType",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "caseNumber",
    align: "left",
    label: "คดีเลขที่",
    sortable: true,
    field: "caseNumber",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "description",
    align: "left",
    label: "รายละเอียด",
    sortable: true,
    field: "description",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "lastUpdatedAt",
    align: "left",
    label: "วันที่แก้ไข",
    sortable: true,
    field: "lastUpdatedAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "status",
    align: "left",
    label: "สถานะของคำร้อง",
    sortable: false,
    field: "status",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);

/** ไปยังหน้าเพิ่มข้อมูล */
function redirectToPageDetail(id: string) {
  dataStore.rowsAdd = [];
  router.push(`/discipline-appealcomplain-detail/${id}`);
}

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

/** เปิดหน้า แก้ไข */
function editPage(id: string) {
  router.push(`/discipline-appealcomplain/${id}`);
}

/** ดึงข้อมูลเมื่อ กด enter */
function filterFn() {
  getSearch();
}

/** ปิด pop up */
function close() {
  modalStatusEdit.value = false;
}

/** ดึงข้อมูลเริ่มต้น */
async function getData() {
  showLoader();
  await http
    .get(
      config.API.appealMainList(
        formData.status,
        formData.type,
        formData.year,
        pagination.value.page,
        pagination.value.rowsPerPage,
        filterKeyword.value
      )
    )
    .then((res) => {
      totalList.value = Math.ceil(
        res.data.result.total / pagination.value.rowsPerPage
      );
      total.value = res.data.result.total;
      fetchAppealComplain(res.data.result.data);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

/** update status */
function dataUpdate() {
  getSearch();
}

/** set ปี ทั้งหมด */
function yearAll() {
  formData.year = 0;
  getSearch();
}

/** ฟังชั่น เคลียฟิลเตอร์ */
function resetFilter() {
  filterKeyword.value = "";
  getSearch();
}
const option = ref<any[]>(dataStore.statusOptions);
const optionType = ref<any[]>(type.value);
/**
 * function ค้นหาข้อมูลใน option
 * @param val คำค้นหา
 * @param update function
 */
function filterOptionFn(val: string, update: Function) {
  update(() => {
    option.value = dataStore.statusOptions.filter(
      (e: any) => e.name.search(val) !== -1
    );
  });
}

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

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

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

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

/** เรียกใช้งาน ฟังชั่น ตอนเริ่มโหลดหน้า */
onMounted(async () => {
  getData();
  dataStore.visibleColumns = visibleColumns.value;
  dataStore.columns = columns.value;
});
</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 q-mb-sm q-col-gutter-sm">
      <div>
        <q-btn
          v-if="checkPermission($route)?.attrIsCreate"
          id="addComplaints"
          for="addComplaints"
          dense
          flat
          round
          color="primary"
          icon="mdi-plus"
          @click="redirectToPageadd()"
          ><q-tooltip>เพิ่มการอุทธรณ์/ร้องทุกข์</q-tooltip></q-btn
        >
      </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="filterFn"
      >
        <template v-slot:append>
          <q-icon name="search" />
        </template>
      </q-input>

      <q-select
        id="visibleColumns"
        for="visibleColumns"
        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 row q-mb-sm">
      <q-card bordered class="col-12 filter-card q-pa-sm">
        <div class="row col-12 q-col-gutter-sm">
          <div class="col-2">
            <datepicker
              menu-class-name="modalfix"
              v-model="formData.year"
              class="col-2"
              :locale="'th'"
              autoApply
              year-picker
              :enableTimePicker="false"
              @update:model-value="dataUpdate"
            >
              <template #year="{ year }">{{ year + 543 }}</template>
              <template #year-overlay-value="{ value }">{{
                parseInt(value + 543)
              }}</template>
              <template #trigger>
                <q-input
                  dense
                  outlined
                  :model-value="
                    formData.year === 0
                      ? 'ทั้งหมด'
                      : Number(formData.year) + 543
                  "
                  :label="`${'ปีงบประมาณ'}`"
                >
                  <template v-if="formData.year" v-slot:append>
                    <q-icon
                      name="cancel"
                      @click.stop.prevent="yearAll"
                      class="cursor-pointer"
                    />
                  </template>
                  <template v-slot:prepend>
                    <q-icon
                      name="event"
                      class="cursor-pointer"
                      style="color: var(--q-primary)"
                    >
                    </q-icon>
                  </template>
                </q-input>
              </template>
            </datepicker>
          </div>
          <div class="col-2">
            <q-select
              v-model="formData.type"
              label="ประเภท"
              dense
              outlined
              emit-value
              map-options
              hide-selected
              fill-input
              option-label="name"
              option-value="id"
              :options="optionType"
              @update:model-value="dataUpdate"
              use-input
              @filter="filterOptionFnType"
            >
              <template v-if="formData.type !== 'ALL'" v-slot:append>
                <q-icon
                  name="cancel"
                  @click.stop.prevent="
                    (optionType = type), (formData.type = 'ALL'), dataUpdate()
                  "
                  class="cursor-pointer"
                />
              </template>
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    ไม่มีข้อมูล
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
          <div class="col-3">
            <q-select
              v-model="formData.status"
              label="สถานะ"
              dense
              outlined
              emit-value
              hide-selected
              fill-input
              map-options
              option-label="name"
              option-value="id"
              :options="option"
              @update:model-value="dataUpdate"
              use-input
              @filter="filterOptionFn"
            >
              <template v-if="formData.status !== 'ALL'" v-slot:append>
                <q-icon
                  name="cancel"
                  @click.stop.prevent="
                    (option = dataStore.statusOptions),
                      (formData.status = 'ALL'),
                      dataUpdate()
                  "
                  class="cursor-pointer"
                />
              </template>
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey">
                    ไม่มีข้อมูล
                  </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
        </div>
      </q-card>
    </div>

    <div class="col-12">
      <d-table
        ref="table"
        :columns="dataStore.columns"
        :rows="dataStore.rows"
        row-key="id"
        flat
        bordered
        :paging="true"
        dense
        class="custom-header-table"
        :visible-columns="dataStore.visibleColumns"
        :rows-per-page-options="[10, 25, 50, 100]"
        @update:pagination="updatePagination"
      >
        <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="getData"
          ></q-pagination>
        </template>
        <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-tr>
        </template>
        <template v-slot:body="props">
          <q-tr :props="props">
            <q-td auto-width>
              <q-btn
                v-if="checkPermission($route)?.attrIsGet"
                id="addComplaints"
                for="addComplaints"
                dense
                flat
                round
                color="info"
                icon="mdi-eye"
                @click="redirectToPageDetail(props.row.id)"
                ><q-tooltip>รายละเอียดการอุทธรณ์/ร้องทุกข์</q-tooltip></q-btn
              >
              <q-btn
                v-if="
                  checkPermission($route)?.attrIsUpdate &&
                  checkPermission($route)?.attrIsGet
                "
                id="addComplaints"
                for="addComplaints"
                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-if="col.name === 'description'"
                class="table_ellipsis"
              >
                {{ props.row.description ? props.row.description : "-" }}
              </div>
              <div v-else>
                {{ col.value ?? "-" }}
              </div>
            </q-td>
          </q-tr>
        </template>
      </d-table>
    </div>
  </q-card>

  <DialogStatus :modal="modalStatusEdit" :data="dataRow" :close="close" />
</template>

<style scoped>
.filter-card {
  background-color: #f1f1f1b0;
}
</style>
