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

import DialogListCriteria from "@/modules/08_KPI/components/Tab/Dialog/DialogListCriteria.vue";

import config from "@/app.config";
import http from "@/plugins/http";

import Work from "@/modules/08_KPI/components/Tab/Topic/01_Indicator.vue";
import Competency from "@/modules/08_KPI/components/Tab/Topic/02_Competency.vue";

import { useCounterMixin } from "@/stores/mixin";
import { useKpiDataStore } from "@/modules/08_KPI/store";

import type { ListCriteria } from "@/modules/08_KPI/interface/request/index";

const score = defineModel("score", { type: Number, default: 0 });
const dataListCriteria = ref<ListCriteria[]>([]);

const modalCriteria = ref<boolean>(false);
const $q = useQuasar();
const route = useRoute();
const { showLoader, hideLoader, messageError } = useCounterMixin();
const store = useKpiDataStore();

const evaluationId = ref<string>(route.params.id.toString());

const rows_01 = ref<any[]>();
const rows_02 = ref<any[]>();
const rows_03 = ref<any[]>();

const totalResults1 = ref<number>(0);
const totalResults2 = ref<number>(0);
const totalResults3 = ref<number>(0);
// const resultWork = ref<number>(0);

function fetchListPlanned() {
  showLoader();
  http
    .get(config.API.kpiAchievement("planned") + `?id=${evaluationId.value}`)
    .then((res) => {
      const data = res.data.result;
      const newRow = data.map((e: any) => ({
        ...e,
        evaluationResults: (e.point / 5) * e.weight,
      }));
      rows_01.value = newRow;

      if (newRow.length > 0) {
        const result = newRow.reduce(
          (sum: number, e: any) => sum + e.evaluationResults,
          0
        );
        const weight = newRow.reduce(
          (sum: number, e: any) => sum + e.weight,
          0
        );

        totalResults1.value =
          (result * store.dataEvaluation.plannedPoint) / weight;
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function fetchListRole() {
  showLoader();
  http
    .get(config.API.kpiAchievement("role") + `?id=${evaluationId.value}`)
    .then((res) => {
      const data = res.data.result;
      const newRow = data.map((e: any) => ({
        ...e,
        evaluationResults: (e.point / 5) * e.weight,
      }));
      rows_02.value = newRow;

      if (newRow.length > 0) {
        const result = newRow.reduce(
          (sum: number, e: any) => sum + e.evaluationResults,
          0
        );
        const weight = newRow.reduce(
          (sum: number, e: any) => sum + e.weight,
          0
        );

        totalResults2.value =
          (result * store.dataEvaluation.rolePoint) / weight;
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function fetchAssigned() {
  showLoader();
  http
    .get(config.API.kpiAchievement("special") + `?id=${evaluationId.value}`)
    .then((res) => {
      const data = res.data.result;
      const newRow = data.map((e: any) => ({
        ...e,
        evaluationResults: (e.point / 5) * e.weight,
      }));

      rows_03.value = newRow;

      if (newRow.length > 0) {
        const result = newRow.reduce(
          (sum: number, e: any) => sum + e.evaluationResults,
          0
        );
        const weight = newRow.reduce(
          (sum: number, e: any) => sum + e.weight,
          0
        );

        totalResults3.value =
          (result * store.dataEvaluation.specialPoint) / weight;
      }
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      hideLoader();
    });
}

function onInfo() {
  modalCriteria.value = true;
}

const totalCompetency = ref<number>(0);
const resultWork = computed(() => {
  const total = totalResults1.value + totalResults2.value + totalResults3.value;
  score.value = total;
  return total.toFixed(2);
});

function getCriteria() {
  http
    .get(config.API.KpiEvaluationInfo)
    .then((res) => {
      const data = res.data.result.data;
      dataListCriteria.value = data;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

watch(
  () => totalCompetency.value,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      score.value =
        totalResults1.value +
        totalResults2.value +
        totalResults3.value +
        newValue;
    }
  }
);

watch(
  () => store.dataEvaluation.plannedPoint,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      fetchListPlanned();
    }
  }
);

watch(
  () => store.dataEvaluation.rolePoint,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      fetchListRole();
    }
  }
);

watch(
  () => store.dataEvaluation.specialPoint,
  (newValue, oldValue) => {
    if (newValue !== oldValue) {
      fetchAssigned();
    }
  }
);

onMounted(() => {
  getCriteria();
  fetchListPlanned();
  fetchListRole();
  fetchAssigned();
});
</script>

<template>
  <q-scroll-area
    style="height: 100vh"
    class="bg-white row col-12 text-dark q-pa-md"
  >
    <div class="text-weight-bold text-body2">
      <span class="txt-under text-blue-6">องค์ประกอบที่ 1 </span>
      <span class="q-ml-sm"> ผลสัมฤทธิ์ของงาน</span>
    </div>

    <div class="q-gutter-md q-mt-sm">
      <!-- องค์ประกอบที่ 1 -->
      <Work
        v-model:data="rows_01"
        :title="`1. งานตามแผนปฏิบัติราชการประจำปี`"
        :page="1"
        :fetchList="fetchListPlanned"
        :total="totalResults1"
      />
      <Work
        v-model:data="rows_02"
        :title="`2. งานตามหน้าที่ความรับผิดชอบหลัก`"
        :page="2"
        :fetchList="fetchListRole"
        :total="totalResults2"
      />
      <Work
        v-model:data="rows_03"
        :title="`3. งานที่ได้รับมอบหมายพิเศษ`"
        :page="3"
        :fetchList="fetchAssigned"
        :total="totalResults3"
      />
      <div class="row text-body2 text-weight-bold">
        <!-- <div class="col-6 text-center row justify-center">
          <span>รวมผลการประเมิน (ร้อยละ) 100</span>
          <div class="text-primary q-pl-md">{{ total }}</div>
        </div> -->

        <div class="col-12 text-center row justify-center">
          <span
            >สรุปผลการประเมินผลสัมฤทธิ์ของงาน (คะแนนเต็ม
            {{
              store.dataEvaluation.plannedPoint +
              store.dataEvaluation.rolePoint +
              store.dataEvaluation.specialPoint
            }}
            คะแนน)</span
          >
          <div class="text-primary q-pl-md">{{ resultWork }}</div>
        </div>
      </div>

      <q-separator size="3px" class="q-my-lg" />

      <!-- องค์ประกอบที่ 2 -->
      <div class="text-weight-bold text-body2 q-mb-sm">
        <span class="txt-under text-blue-6">องค์ประกอบที่ 2</span>
        <span class="q-ml-sm"> พฤติกรรมการปฎิบัติราชการ (สมรรถนะ)</span>
        <q-btn
          flat
          icon="info"
          color="info"
          round
          class="q-ml-xs"
          @click="onInfo"
        >
          <q-tooltip>เกณฑ์การประเมิน</q-tooltip>
        </q-btn>
      </div>

      <Competency
        v-model:dataListCriteria="dataListCriteria"
        v-model:total-competency="totalCompetency"
      />
    </div>
  </q-scroll-area>

  <DialogListCriteria
    v-model:modal="modalCriteria"
    v-model:dataListCriteria="dataListCriteria"
  />
</template>

<style scoped>
.txt-under {
  text-decoration: underline;
}
</style>
