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

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

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

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

const totalList = ref<number>(0);

/**
 * ดึงข้อมูลรายการขอรับประเมินผลการปฏิบัติราชการระดับบุคคล
 * @param type
 */
const isLoadOp = ref<boolean>(false);
async function fetchRoundOption() {
  isLoadOp.value = true;
  await http
    .get(
      config.API.kpiPeriod +
        `?page=${1}&pageSize=${10}&keyword=${""}&year=${store.yearRound}`
    )
    .then(async (res) => {
      const data = 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 (data.length === 0) {
        store.formQuery.round = "";
        dataListMain.value = [];
      } else {
        store.formQuery.round = roundOp.value[0].id;
        await fetchList();
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      isLoadOp.value = false;
    });
}

/** ดึงข้อมูล list */
const isLoad = ref<boolean>(false);
async function fetchList() {
  isLoad.value = true;
  const body = {
    page: store.formQuery.page,
    pageSize: store.formQuery.pageSize,
    kpiPeriodId: store.formQuery.round ?? "",
    keyword: store.formQuery.keyword,
    year: store.yearRound,
    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,
    ...(store.formQuery.sortBy && {
      sortBy: store.formQuery.sortBy,
      descending: store.formQuery.descending,
    }),
  };

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

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

/** เปลี่ยน tab */
async function onChangTab() {
  store.formQuery.page = 1;
  dataListMain.value = [];
  store.selected = [];
  await 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-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()
              "
            >
              <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
              v-if="!isLoadOp"
              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-skeleton
              v-else
              class="col-md-2 col-xs-12"
              type="QInput"
              height="40px"
            />
            <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"
                    :fetchList="fetchList"
                    :is-load="isLoad"
                  />
                </q-tab-panel>

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

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

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

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

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