<script setup lang="ts">
import { ref, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { useQuasar } from "quasar";
import type { QTableProps } from "quasar";

import config from "@/app.config";
import http from "@/plugins/http";
import { useCounterMixin } from "@/stores/mixin";
import { useKpiDataStore } from "@/modules/08_KPI/store";

import type {
  DataOptions,
  Pagination,
} from "@/modules/08_KPI/interface/index/Main";
import type {
  ResRound,
  ResEvaluatorAssessor,
} from "@/modules/08_KPI/interface/response/index";

import TabAll from "@/modules/08_KPI/components/Evaluator/01_TabAll.vue";
import TabOther from "@/modules/08_KPI/components/Evaluator/02_TabOther.vue";

const $q = useQuasar();
const router = useRouter();
const store = useKpiDataStore();
const { showLoader, hideLoader, messageError, date2Thai } = useCounterMixin();

const dataListMain = ref<ResEvaluatorAssessor[]>([]);

const roundOp = ref<DataOptions[]>([]);

const visibleColumns = ref<string[]>([
  "name",
  "createdAt",
  "evaluationStatus",
  "evaluationResults",
]);
const columns = ref<QTableProps["columns"]>([
  {
    name: "name",
    align: "left",
    label: "ผู้ขอรับการประเมิน",
    sortable: true,
    field: "name",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "createdAt",
    align: "left",
    label: "วันที่สร้างแบบประเมิน",
    sortable: true,
    field: "createdAt",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => date2Thai(v),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "evaluationStatus",
    align: "left",
    label: "สถานะการประเมิน",
    sortable: true,
    field: "evaluationStatus",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => store.convertStatus(v),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
  {
    name: "evaluationResults",
    align: "left",
    label: "ผลการประเมิน",
    sortable: true,
    field: "evaluationResults",
    headerStyle: "font-size: 14px",
    style: "font-size: 14px",
    format: (v) => store.convertResults(v),
    sort: (a: string, b: string) =>
      a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }),
  },
]);

const totalList = ref<number>(0);
const maxPage = ref<number>(1);

/**
 * ดึงข้อมูลรายการขอรับประเมินผลการปฏิบัติราชการระดับบุคคล
 * @param type
 */
async function fetchRoundOption(type: boolean = false) {
  showLoader();
  await http
    .get(
      config.API.kpiPeriod +
        `?page=${1}&pageSize=${10}&keyword=${""}&year=${store.yearRound}`
    )
    .then(async (res) => {
      const data = await res.data.result.data;
      const list = data.map((e: ResRound) => ({
        id: e.id,
        name:
          e.durationKPI === "OCT"
            ? "รอบที่ 2 ตุลาคม"
            : e.durationKPI === "APR"
            ? "รอบที่ 1 เมษายน"
            : "",
      }));
      roundOp.value = list;
      if (type) {
        store.formQuery.round = "";
      }
      await fetchList();
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** ดึงข้อมูล list */
async function fetchList() {
  showLoader();
  const body = {
    page: store.formQuery.page,
    pageSize: store.formQuery.pageSize,
    kpiPeriodId: store.formQuery.round,
    keyword: store.formQuery.keyword,
    status:
      store.tabMainevaluator === "2"
        ? "NEW"
        : store.tabMainevaluator === "4"
        ? "APPROVE"
        : store.tabMainevaluator === "5"
        ? "EVALUATING_EVALUATOR"
        : store.tabMainevaluator === "6"
        ? "SUMMARY"
        : undefined,
    reqedit: store.tabMainevaluator === "3" ? "NEW" : undefined,
  };

  await http
    .post(config.API.kpiEvaluation + `/admin`, body)
    .then(async (res) => {
      const data = await res.data.result;
      maxPage.value = Math.ceil(data.total / store.formQuery.pageSize);
      totalList.value = data.total;
      dataListMain.value = data.data;
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

/** เลือกรอบการประเมิน */
function changRound() {
  store.formQuery.page = 1;
  fetchList();
}

/**
 * function updatePagination
 * @param newPagination ข้อมูล Pagination ใหม่
 */
function updatePagination(newPagination: Pagination) {
  store.formQuery.page = 1;
  store.formQuery.pageSize = newPagination.rowsPerPage;
}

/** เปลี่ยน tab */
async function onChangTab() {
  store.formQuery.page = 1;
  dataListMain.value = [];
  store.selected = [];
  await fetchList();
}

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

onMounted(async () => {
  await fetchRoundOption();
});
</script>

<template>
  <div class="col-12 row justify-center">
    <div class="col-xs-12 col-sm-12 col-md-11">
      <div class="toptitle text-white col-12 row items-center">
        <q-btn
          icon="mdi-arrow-left"
          unelevated
          round
          dense
          flat
          color="primary"
          class="q-mr-sm"
          @click="router.push(`/`)"
        />
        รายการการประเมินผลการปฏิบัติราชการระดับบุคคล
      </div>

      <div class="col-12">
        <q-card bordered class="q-pa-md">
          <div class="items-center col-12 row q-col-gutter-sm q-mb-sm">
            <datepicker
              class="col-md-1 col-xs-12"
              v-model="store.yearRound"
              :locale="'th'"
              autoApply
              year-picker
              :enableTimePicker="false"
              @update:model-value="
                (store.formQuery.page = 1), fetchRoundOption(true)
              "
            >
              <template #year="{ year }">{{ year + 543 }}</template>
              <template #year-overlay-value="{ value }">{{
                parseInt(value + 543)
              }}</template>
              <template #trigger>
                <q-input
                  dense
                  lazy-rules
                  outlined
                  hide-bottom-space
                  :model-value="
                    !!store.yearRound ? store.yearRound + 543 : null
                  "
                  :label="`${'ปีงบประมาณ'}`"
                >
                  <template v-slot:prepend>
                    <q-icon
                      name="event"
                      class="cursor-pointer"
                      style="color: var(--q-primary)"
                    >
                    </q-icon>
                  </template>
                </q-input>
              </template>
            </datepicker>
            <q-select
              class="col-md-2 col-xs-12"
              v-model="store.formQuery.round"
              outlined
              label="รอบการประเมิน"
              dense
              option-label="name"
              option-value="id"
              :options="roundOp"
              emit-value
              map-options
              @update:model-value="changRound"
            />

            <q-space />

            <q-input
              class="col-md-2 col-xs-12"
              outlined
              dense
              v-model="store.formQuery.keyword"
              label="ค้นหาผู้ขอรับการประเมิน"
              @keydown.enter.prevent="changRound"
            >
              <template v-slot:append>
                <q-icon
                  v-if="store.formQuery.keyword !== ''"
                  name="clear"
                  class="cursor-pointer"
                  @click="(store.formQuery.keyword = ''), changRound()"
                />
                <q-icon v-else name="search" color="grey-5" />
              </template>
            </q-input>
            <q-select
              class="col-md-1 col-xs-12"
              v-model="visibleColumns"
              multiple
              outlined
              dense
              options-dense
              :display-value="$q.lang.table.columns"
              emit-value
              map-options
              :options="columns"
              option-value="name"
              style="min-width: 140px"
            />
          </div>

          <div class="col-12">
            <q-card bordered class="q-mt-sm">
              <q-tabs
                v-model="store.tabMainevaluator"
                inline-label
                align="left"
                class="text-grey"
                active-color="primary"
                indicator-color="primary"
              >
                <q-tab name="1" label="รายการทั้งหมด" @click="onChangTab" />
                <q-tab name="2" label="รออนุมัติข้อตกลง" @click="onChangTab" />
                <q-tab
                  name="3"
                  label="รออนุมัติแก้ไขข้อตกลง"
                  @click="onChangTab"
                />
                <q-tab name="5" label="รายงานผลสำเร็จ" @click="onChangTab" />
                <q-tab name="6" label="สรุปผลการประเมิน" @click="onChangTab" />
              </q-tabs>
              <q-separator />

              <q-tab-panels v-model="store.tabMainevaluator" animated>
                <q-tab-panel name="1">
                  <TabAll
                    :columns="columns"
                    :visibleColumns="visibleColumns"
                    :rows="dataListMain"
                    :formQuery="store.formQuery"
                    :total="totalList"
                    :maxPage="maxPage"
                    :updatePagination="updatePagination"
                    :fetchList="fetchList"
                  />
                </q-tab-panel>

                <q-tab-panel name="2">
                  <TabOther
                    :columns="columns"
                    :visibleColumns="visibleColumns"
                    :rows="dataListMain"
                    :formQuery="store.formQuery"
                    :total="totalList"
                    :maxPage="maxPage"
                    :updatePagination="updatePagination"
                    :fetchList="fetchList"
                  />
                </q-tab-panel>

                <q-tab-panel name="3">
                  <TabOther
                    :columns="columns"
                    :visibleColumns="visibleColumns"
                    :rows="dataListMain"
                    :formQuery="store.formQuery"
                    :total="totalList"
                    :maxPage="maxPage"
                    :updatePagination="updatePagination"
                    :fetchList="fetchList"
                  />
                </q-tab-panel>

                <q-tab-panel name="5">
                  <TabOther
                    :columns="columns"
                    :visibleColumns="visibleColumns"
                    :rows="dataListMain"
                    :formQuery="store.formQuery"
                    :total="totalList"
                    :maxPage="maxPage"
                    :updatePagination="updatePagination"
                    :fetchList="fetchList"
                  />
                </q-tab-panel>

                <q-tab-panel name="6">
                  <TabOther
                    :columns="columns"
                    :visibleColumns="visibleColumns"
                    :rows="dataListMain"
                    :formQuery="store.formQuery"
                    :total="totalList"
                    :maxPage="maxPage"
                    :updatePagination="updatePagination"
                    :fetchList="fetchList"
                  />
                </q-tab-panel>
              </q-tab-panels>
            </q-card>
          </div>
        </q-card>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.icon-color {
  color: #4154b3;
}
</style>
