<script setup lang="ts">
import { ref, onMounted, reactive } from "vue";
import { useRoute, useRouter } from "vue-router";
import http from "@/plugins/http";
import config from "@/app.config";
import TabMain from "@/modules/08_KPI/components/Tab/TabMain.vue";
import { useQuasar } from "quasar";

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

import DialogHeader from "@/components/DialogHeader.vue";
import type { FormProfile } from "@/modules/08_KPI/interface/request/index";
import type { DataOptions } from "@/modules/08_KPI/interface/index/Main";

const modalEdit = ref<boolean>(false);
const route = useRoute();
const id = ref<string>(route.params.id as string);
const isReadonly = <boolean>(route.name === "KPIEditEvaluator" ? true : false);

const store = useKpiDataStore();
const $q = useQuasar();
const mixin = useCounterMixin();
const { showLoader, hideLoader, messageError, dialogConfirm, success } = mixin;

const evaluatorIdOp = ref<DataOptions[]>([]);
const commanderIdOp = ref<DataOptions[]>([]);
const commanderHighOp = ref<DataOptions[]>([]);

const evaluatorIdMainOp = ref<DataOptions[]>([]);
const commanderIdMainOp = ref<DataOptions[]>([]);
const commanderHighMainOp = ref<DataOptions[]>([]);

const evaluatorId = ref<any>();
const commanderId = ref<any>();
const commanderHighId = ref<any>();

const formProfile = reactive<FormProfile>({
  fullName: "",
  position: "",
  type: "",
  level: "",
  status: "",
  result: "",
  score: "-",
  avartar: "",
});

const router = useRouter();

function fetchEvaluation() {
  showLoader();
  http
    .get(config.API.kpiEvaluation + `/${id.value}`)
    .then((res) => {
      const data = res.data.result;
      store.dataEvaluation = data;
      formProfile.status = store.convertStatus(data.evaluationStatus);
      formProfile.result = store.convertResults(data.evaluationResults);
      fetchProfile(data.profileId);
      console.log(store.dataEvaluation);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

function getProfile() {
  showLoader();
  http
    .get(config.API.profilePosition())
    .then((res) => {
      const data = res.data.result;
      store.dataProfile = data;
      store.checkCompetency();
      store.checkCompetencyDefaultCompetencyLevel();

      formProfile.fullName = `${data.prefix}${data.firstName} ${data.lastName}`;
      formProfile.position = data.position;
      formProfile.type = data.posTypeName;
      formProfile.level = data.posLevelName;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      hideLoader();
    });
}

async function fetchProfile(id: string) {
  showLoader();
  await http
    .get(
      config.API.fileByFile("ทะเบียนประวัติ", "โปรไฟล์", id, `profile-${id}`)
    )
    .then(async (res) => {
      formProfile.avartar = res.data.downloadUrl;
    })
    .catch(() => {
      // profilePicture.value = avatar;
    })
    .finally(() => {
      hideLoader();
    });
}

/** save */
function onSave() {}

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

async function clearDialog() {
  modalEdit.value = false;
  evaluatorId.value = null;
  commanderId.value = null;
  commanderHighId.value = null;
  await fetchEvaluation();
  await getProfile();
  await getOrgOp();
}

function onSubmit() {
  dialogConfirm($q, () => {
    showLoader();
    http
      .put(config.API.kpiEvaluationCheck + `/${id.value}`, {
        evaluatorId: evaluatorId.value.id,
        commanderId: commanderId.value.id,
        commanderHighId: commanderHighId.value.id,
      })
      .then((res) => {
        success($q, "บันทึกสำเร็จ");
        clearDialog();
      })
      .catch((e) => {
        messageError($q, e);
      })
      .finally(() => {
        hideLoader();
      });
  });
}

function getOrgOp() {
  http
    .get(config.API.Kpiorg)
    .then((res) => {
      const data = res.data.result;
      evaluatorIdMainOp.value = data.caregiver.map((i: any) => ({
        id: i.id,
        name: `${i.prefix}${i.firstName} ${i.lastName}`,
      }));
      commanderIdMainOp.value = data.commander.map((i: any) => ({
        id: i.id,
        name: `${i.prefix}${i.firstName} ${i.lastName}`,
      }));
      commanderHighMainOp.value = data.chairman.map((i: any) => ({
        id: i.id,
        name: `${i.prefix}${i.firstName} ${i.lastName}`,
      }));

      evaluatorId.value = data.caregiver
        .map((i: any) => ({
          id: i.id,
          name: `${i.prefix}${i.firstName} ${i.lastName}`,
        }))
        .find((i: any) => i.id == store.dataEvaluation.evaluatorId);
      commanderId.value = data.caregiver
        .map((i: any) => ({
          id: i.id,
          name: `${i.prefix}${i.firstName} ${i.lastName}`,
        }))
        .find((i: any) => i.id == store.dataEvaluation.commanderId);
      commanderHighId.value = data.caregiver
        .map((i: any) => ({
          id: i.id,
          name: `${i.prefix}${i.firstName} ${i.lastName}`,
        }))
        .find((i: any) => i.id == store.dataEvaluation.commanderHighId);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {});
}

function filterOption(val: any, update: Function, refData: string) {
  switch (refData) {
    case "evaluatorIdOp":
      update(() => {
        evaluatorIdOp.value = evaluatorIdMainOp.value.filter(
          (v: any) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "commanderIdOp":
      update(() => {
        commanderIdOp.value = commanderIdMainOp.value.filter(
          (v: any) => v.name.indexOf(val) > -1
        );
      });
      break;
    case "commanderHighOp":
      update(() => {
        commanderHighOp.value = commanderHighMainOp.value.filter(
          (v: any) => v.name.indexOf(val) > -1
        );
      });
      break;
    default:
      break;
  }
}

onMounted(async () => {
  await fetchEvaluation();
  await getProfile();
  await getOrgOp();
});
</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="
            isReadonly ? router.push(`/KPI-evaluator`) : router.push(`/KPI`)
          "
        />
        {{
          isReadonly
            ? "รายละเอียดการประเมินผลการปฏิบัติราชการระดับบุคคล"
            : id
            ? `แก้ไขแบบประเมิน`
            : `เพิ่มแบบประเมิน`
        }}
        <q-space />

        <!-- <q-btn label="บันทึก" color="secondary" unelevated @click="onSave"
          ><q-tooltip>บันทึก</q-tooltip></q-btn
        > -->
      </div>
      <div class="col-12">
        <q-card bordered flat class="relative-position">
          <div
            class="absolute-center-left"
            style="left: 2%; top: 50%; transform: translateY(-50%)"
          >
            <q-avatar size="95px">
              <img :src="formProfile.avartar" />
            </q-avatar>
          </div>
          <div class="row col-12">
            <div class="row items-center col-12 q-pa-sm">
              <div class="col-12" style="padding-left: 12%">
                <div class="row col-12 items-center">
                  <span class="text-h6 text-weight-medium text-primary">{{
                    formProfile.fullName ? formProfile.fullName : "-"
                  }}</span>
                  <q-space />
                  <div class="q-gutter-x-sm">
                    <q-btn
                      v-if="!isReadonly"
                      unelevated
                      round
                      icon="edit"
                      color="grey-2"
                      text-color="edit"
                      size="md"
                      @click="modalEdit = true"
                    >
                      <q-tooltip>แก้ไขผู้ประเมิน</q-tooltip>
                    </q-btn>
                    <q-btn
                      unelevated
                      round
                      icon="mdi-file-eye-outline"
                      color="grey-2"
                      text-color="primary"
                      size="md"
                    >
                      <q-tooltip>ดูข้อมูลการช่วยราชการ</q-tooltip>
                    </q-btn>
                    <q-btn
                      unelevated
                      round
                      color="grey-2"
                      text-color="blue-5"
                      icon="mdi-file-eye-outline"
                      size="md"
                    >
                      <q-tooltip>ดูข้อมูลการทดลองงาน</q-tooltip>
                    </q-btn>
                  </div>
                </div>
              </div>
            </div>

            <div class="row items-center bg-toolbar col-12 q-pa-sm">
              <div class="col-12 q-py-xs" style="padding-left: 12%">
                <div class="row no-wrap">
                  <div class="col-2">
                    <div class="column">
                      <span class="text-grey-6">ตำแหน่งในสายงาน</span>
                      <span class="text-weight-medium text-dark">{{
                        formProfile.position
                      }}</span>
                    </div>
                  </div>
                  <div class="col-2">
                    <div class="column">
                      <span class="text-grey-6">ประเภทตำแหน่ง</span>
                      <span class="text-weight-medium text-dark">{{
                        formProfile.type
                      }}</span>
                    </div>
                  </div>
                  <div class="col-2">
                    <div class="column">
                      <span class="text-grey-6">ระดับตำแหน่ง</span>
                      <span class="text-weight-medium text-dark">{{
                        formProfile.level
                      }}</span>
                    </div>
                  </div>
                  <div class="col-2">
                    <div class="column">
                      <span class="text-grey-6">สถานะการประเมิน</span>
                      <span class="text-weight-medium text-dark">{{
                        formProfile.status
                      }}</span>
                    </div>
                  </div>
                  <div class="col-2">
                    <div class="column">
                      <span class="text-grey-6">ผลการประเมิน</span>
                      <span class="text-weight-medium text-dark">{{
                        formProfile.result
                      }}</span>
                    </div>
                  </div>
                  <div class="col-2">
                    <div class="column">
                      <span class="text-grey-6">คะแนนประเมิน</span>
                      <span class="text-weight-medium text-primary">{{
                        formProfile.score
                      }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </q-card>

        <q-card class="q-mt-md rounded">
          <TabMain />
        </q-card>
      </div>
    </div>
  </div>

  <q-dialog v-model="modalEdit" persistent>
    <q-card bordered style="width: 50vh">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader tittle="แก้ไขผู้ประเมิน" :close="close" />
        <q-separator />
        <q-card-section>
          <div class="column q-gutter-sm">
            <q-select
              v-model="evaluatorId"
              outlined
              label="ผู้ประเมิน"
              dense
              option-label="name"
              option-value="id"
              :options="evaluatorIdOp"
              class="inputgreen"
              map-options
              hide-bottom-space
              lazy-rules
              :rules="[
                  (val:string) =>
                    !!val || `${'กรุณาเลือกผู้ประเมิน'}`,
                ]"
              use-input
              @filter="(inputValue:any,
                    doneFn:Function) => filterOption(inputValue, doneFn,'evaluatorIdOp'
                    ) "
            />
            <q-select
              v-model="commanderId"
              outlined
              label="ผู้บังคับบัญชาเหนือขึ้นไป"
              dense
              option-label="name"
              option-value="id"
              :options="commanderIdOp"
              map-options
              class="inputgreen"
              use-input
              @filter="(inputValue:any,
                    doneFn:Function) => filterOption(inputValue, doneFn,'commanderIdOp'
                    ) "
            >
              <template v-if="commanderId" v-slot:append>
                <q-icon
                  name="cancel"
                  @click.stop.prevent="commanderId = null"
                  class="cursor-pointer"
                />
              </template>
            </q-select>
            <q-select
              v-model="commanderHighId"
              outlined
              label="ผู้บังคับบัญชาเหนือขึ้นไปอีกชั้นหนึ่ง"
              dense
              option-label="name"
              option-value="id"
              :options="commanderHighOp"
              map-options
              use-input
              class="inputgreen"
              @filter="(inputValue:any,
                    doneFn:Function) => filterOption(inputValue, doneFn,'commanderHighOp'
                    ) "
            >
              <template v-if="commanderHighId" v-slot:append>
                <q-icon
                  name="cancel"
                  @click.stop.prevent="commanderHighId = null"
                  class="cursor-pointer"
                />
              </template>
            </q-select>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn label="บันทึก" color="secondary" type="submit"
            ><q-tooltip>บันทึกข้อมูล</q-tooltip></q-btn
          >
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>
<style>
.bg-toolbar {
  background-color: #f2fbfa;
}

.absolute-center-left {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
}
</style>
