<script setup lang="ts">
import { ref, onMounted, watch, reactive } from "vue";
import { useRouter } from "vue-router";
import { useQuasar } from "quasar";
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";
// importStroe
import { useCounterMixin } from "@/stores/mixin";
import { useAppealComplainStore } from "@/modules/11_discipline/store/AppealComplainStore";

// impoet Components
import DialogStatus from "@/modules/11_discipline/components/8_AppealComplain/dialog/DialogEditStatus.vue";
import config from "@/app.config";
import http from "@/plugins/http";

const $q = useQuasar();
const mixin = useCounterMixin();

const { showLoader, messageError, hideLoader, dialogConfirm } = mixin;
const router = useRouter();
const modalStatusEdit = ref<boolean>(false);
/** stoer */
const dataStore = useAppealComplainStore();
const { fetchAppealComplain } = dataStore;
const type = ref<DataOption[]>([
  { id: "ALL", name: "ทั้งหมด" },
  ...dataStore.typeOptions,
]);
const filterTable = ref<string>("");
const filterKeyword = ref<string>("");

const dataRow = ref<RowList[]>([]);
const currentPage = ref<number>(1);
const maxPage = ref<number>(1);
const page = ref<number>(1);
const rowsPerPage = ref<number>(10);

/**
 *pagination ของตาราง
 */
const pagination = ref({
  descending: false,
  page: page.value,
  rowsPerPage: rowsPerPage.value,
});

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

const visibleColumns = ref<string[]>([
  "no",
  "type",
  "title",
  "fullname",
  "citizenId",
  "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: "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",
  },
]);

watch(
  () => currentPage.value,
  () => {
    rowsPerPage.value = pagination.value.rowsPerPage;
    getData();
  }
);

watch(
  () => pagination.value.rowsPerPage,
  () => {
    rowsPerPage.value = pagination.value.rowsPerPage;
    currentPage.value = 1;
    getData();
  }
);

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

function editPage(id: string) {
  router.push(`/discipline-appealcomplain/${id}`);
}
function filterFn() {
  console.log("enter", filterKeyword.value);
  getData();
}

function close() {
  modalStatusEdit.value = false;
}

function editStatusReturn(data: any) {
  dialogConfirm($q, () => {
    console.log("saveStatus");
    modalStatusEdit.value = false;
  });
}

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

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

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

function resetFilter() {
  filterKeyword.value = "";
  getData();
}

/** เรียกใช้งาน ฟังชั่น ตอนเริ่มโหลดหน้า */
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">
      <div>
        <q-btn
          id="addComplaints"
          for="addComplaints"
          size="12px"
          flat
          round
          color="primary"
          icon="mdi-plus"
          @click="redirectToPageadd()"
          ><q-tooltip>เพิ่มการอุทธรณ์/ร้องทุกข์</q-tooltip></q-btn
        >
      </div>
    </div>
    <div class="row col-12 q-col-gutter-sm q-mb-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
              lazy-rules
              outlined
              :model-value="
                formData.year === 0 ? null : 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
          option-label="name"
          option-value="id"
          :options="type"
          @update:model-value="dataUpdate"
        />
      </div>
      <div class="col-2">
        <q-select
          v-model="formData.status"
          label="สถานะ"
          dense
          outlined
          emit-value
          map-options
          option-label="name"
          option-value="id"
          :options="dataStore.statusOptions"
          @update:model-value="dataUpdate"
        />
      </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
            v-if="filterKeyword !== ''"
            name="clear"
            class="cursor-pointer"
            @click="resetFilter"
          />
        </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"
        options-cover
        class="col-xs-12 col-sm-3 col-md-2"
      />
    </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"
        v-model:pagination="pagination"
        :rows-per-page-options="[10, 25, 50, 100]"
      >
        <template v-slot:pagination="scope">
          <q-pagination
            v-model="currentPage"
            active-color="primary"
            color="dark"
            :max="Number(maxPage)"
            size="sm"
            boundary-links
            direction-links
          ></q-pagination>
        </template>
        <template v-slot:header="props">
          <q-tr :props="props">
            <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" class="cursor-pointer">
            <q-td
              v-for="col in props.cols"
              :key="col.name"
              :props="props"
              @click="editPage(props.row.id)"
            >
              <div v-if="col.name == 'no'">
                {{
                  (currentPage - 1) * Number(pagination.rowsPerPage) +
                  props.rowIndex +
                  1
                }}
              </div>
              <div
                v-else-if="col.name === 'description'"
                class="table_ellipsis"
              >
                {{ 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"
    @editStatusReturn="editStatusReturn"
  />
</template>

<style scoped></style>
