<script setup lang="ts">
import { ref, onMounted, reactive, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useQuasar, type QTableProps } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

/** importType*/
import type {
  DataOption,
  NewPagination,
  DataAssignment,
} from "@/modules/01_masterdata/interface/index/Main";
import type { FormFilterAssignment } from "@/modules/01_masterdata/interface/request/Main";
import type { ResAssignment } from "@/modules/01_masterdata/interface/response/Main";

/** importStore*/
import { useCounterMixin } from "@/stores/mixin";
import { checkPermission } from "@/utils/permissions";

const $q = useQuasar();
const router = useRouter();
const route = useRoute();
const { showLoader, hideLoader, dialogRemove, success, messageError } =
  useCounterMixin();

/** table*/
const columns = ref<QTableProps["columns"]>([
  {
    name: "including",
    align: "left",
    label: "รหัสตัวชี้วัด",
    sortable: true,
    field: "including",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
  {
    name: "includingName",
    align: "left",
    label: "ชื่อตัวชี้วัด",
    sortable: true,
    field: "includingName",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
  },
]);
const visibleColumns = ref<string[]>(["including", "includingName"]);

/** Option  รอบการประเมิน*/
const roundOp = ref<DataOption[]>([
  { id: "APR", name: "รอบเมษายน" },
  { id: "OCT", name: "รอบตุลาคม" },
]);
const rows = ref<DataAssignment[]>([]);

const formFilter = reactive<FormFilterAssignment>({
  keyword: "",
  period: "",
  year: new Date().getFullYear(),
  pageSize: 10,
  page: 1,
});
const totalList = ref<number>(0); //จำนวนข้อมูลรายการ
const maxPage = ref<number>(1);

function fetchList() {
  showLoader();
  formFilter.year = formFilter.year ? formFilter.year.toString() : null;
  http
    .post(config.API.kpiSpecial + `/search`, formFilter)
    .then((res: ResAssignment) => {
      maxPage.value = Math.ceil(res.data.result.total / formFilter.pageSize);
      totalList.value = res.data.result.total;
      rows.value = res.data.result.data;
    })
    .catch((err) => {
      messageError($q, err);
      rows.value = [];
    })
    .finally(() => {
      hideLoader();
    });
}

function onClickView(id: string = "") {
  router.push(`/masterdata/indicator-assignment/${id}`);
}

function onClickDelete(id: string) {
  dialogRemove($q, () => {
    showLoader();
    http
      .delete(config.API.kpiSpecial + `/${id}`)
      .then(() => {
        fetchList();
        success($q, "ลบข้อมูลสำเร็จ");
      })
      .catch((err) => {
        messageError($q, err);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function fetchNewList() {
  formFilter.page = 1;
  fetchList();
}

function updatePageSize(newPagination: NewPagination) {
  formFilter.page = 1;
  formFilter.pageSize = newPagination.rowsPerPage;
}

watch(
  () => formFilter.pageSize,
  () => {
    fetchList();
  }
);

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

<template>
  <div class="toptitle text-dark col-12 row items-center">
    รายการงานที่ได้รับมอบหมาย
  </div>
  <q-card flat bordered class="q-pa-md">
    <div class="row q-col-gutter-sm q-pl-sm">
      <q-toolbar style="padding: 0">
        <div class="row q-gutter-sm">
          <datepicker
            style="width: 150px"
            menu-class-name="modalfix"
            v-model="formFilter.year"
            :locale="'th'"
            autoApply
            year-picker
            :enableTimePicker="false"
            @update:model-value="(formFilter.period = ''), fetchNewList()"
          >
            <template #year="{ year }">{{ year + 543 }}</template>
            <template #year-overlay-value="{ value }">{{
              parseInt(value + 543)
            }}</template>
            <template #trigger>
              <q-input
                dense
                outlined
                :model-value="
                  formFilter.year === null
                    ? 'ทั้งหมด'
                    : Number(formFilter.year) + 543
                "
                :label="`${'ปีงบประมาณ'}`"
              >
                <template v-slot:prepend>
                  <q-icon
                    name="event"
                    class="cursor-pointer"
                    style="color: var(--q-primary)"
                  >
                  </q-icon>
                </template>
                <template v-if="formFilter.year" v-slot:append>
                  <q-icon
                    name="cancel"
                    @click.stop.prevent="
                      (formFilter.year = null), fetchNewList()
                    "
                    class="cursor-pointer"
                  />
                </template>
              </q-input>
            </template>
          </datepicker>
          <q-select
            dense
            outlined
            v-model="formFilter.period"
            :model-value="
              formFilter.period === '' ? 'ทั้งหมด' : formFilter.period
            "
            :options="roundOp"
            label="รอบการประเมิน"
            option-label="name"
            option-value="id"
            emit-value
            map-options
            @update:model-value="fetchNewList"
            style="width: 160px"
          >
            <template v-if="formFilter.period" v-slot:append>
              <q-icon
                name="cancel"
                @click.stop.prevent="(formFilter.period = ''), fetchNewList()"
                class="cursor-pointer"
              />
            </template>
          </q-select>
        </div>
        <q-space />
        <div class="row q-gutter-sm">
          <q-input
            dense
            outlined
            v-model="formFilter.keyword"
            label="ค้นหา"
            @keydown.enter="fetchNewList"
          >
            <template v-slot:append>
              <q-icon
                v-if="formFilter.keyword !== ''"
                name="clear"
                class="cursor-pointer"
                @click="(formFilter.keyword = ''), fetchNewList()"
              />
              <q-icon v-else name="search" color="grey-5" />
            </template>
          </q-input>
          <q-select
            v-model="visibleColumns"
            multiple
            outlined
            dense
            options-dense
            :display-value="$q.lang.table.columns"
            emit-value
            map-options
            :options="columns"
            option-value="name"
            options-cover
            style="min-width: 150px"
          />
        </div>
      </q-toolbar>
    </div>
    <div class="col-12">
      <d-table
        for="table"
        ref="table"
        :columns="columns"
        :rows="rows"
        row-key="id"
        flat
        bordered
        dense
        class="custom-header-table"
        :rows-per-page-options="[10, 25, 50, 100]"
        :visible-columns="visibleColumns"
        @update:pagination="updatePageSize"
      >
        <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"
                flat
                round
                dense
                color="info"
                icon="mdi-eye"
                @click.pervent="onClickView(props.row.id)"
              >
                <q-tooltip>รายละเอียด</q-tooltip>
              </q-btn>
              <q-btn
                v-if="checkPermission($route)?.attrIsDelete"
                flat
                dense
                round
                color="red"
                icon="mdi-delete "
                @click.pervent="onClickDelete(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 class="table_ellipsis">
                {{ col.value ? col.value : "-" }}
              </div>
            </q-td>
          </q-tr>
        </template>
        <template v-slot:pagination="scope">
          ทั้งหมด {{ totalList }} รายการ
          <q-pagination
            v-model="formFilter.page"
            active-color="primary"
            color="dark"
            :max="maxPage"
            :max-pages="5"
            size="sm"
            boundary-links
            direction-links
            @update:model-value="fetchList"
          ></q-pagination>
        </template>
      </d-table>
    </div>
  </q-card>
</template>

<style scoped></style>
