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

import DialogHeader from "@/components/DialogHeader.vue";
import Assessment from "@/modules/14_KPI/components/Tab/01_Assessment.vue";
import File from "@/modules/14_KPI/components/Tab/05_File.vue";

import type {
  DataOption,
  ItemsTab,
} from "@/modules/14_KPI/interface/index/Main";
import type { ResUserEvaluation } from "@/modules/14_KPI/interface/response/KPI";

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

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

const kpiId = ref<string>(route.params.id as string);

/** Header*/
const dataEvaluation = ref<ResUserEvaluation>();
const avartarProfile = ref<string>("");

function fetchEvaluation() {
  http
    .get(config.API.kpiUserEvaluation + `/${kpiId.value}`)
    .then((res) => {
      const data = res.data.result;
      store.dataEvaluation = data;
      dataEvaluation.value = data;
      fetchProfile(data.profileId);
      fetchProfilePosition(data.profileId);
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      if (store.dataEvaluation) {
        Promise.all([
          store.checkStep(),
          store.checkCompetency(),
          store.checkCompetencyDefaultCompetencyLevel(),
        ]);
      }
    });
}
function fetchProfilePosition(id: string) {
  http
    .get(config.API.profilePosition() + `/${id}`)
    .then((res) => {
      const data = res.data.result;
      store.dataProfile = data;
    })
    .catch((e) => {
      messageError($q, e);
    });
}
function sendToEvaluatore(status: string) {
  dialogConfirm(
    $q,
    () => {
      if (kpiId.value) {
        showLoader();
        http
          .put(config.API.kpiSendToStatus(kpiId.value), {
            status: status,
          })
          .then(() => {
            success($q, "ส่งข้อตกลงให้ผู้ประเมินอนุมัติสำเร็จ");
            close();
          })
          .catch((e) => {
            messageError($q, e);
          })
          .finally(() => {
            hideLoader();
          });
      }
    },
    "ยืนยันการส่งข้อตกลงให้ผู้ประเมินอนุมัติ",
    "ต้องการยืนยันส่งข้อตกลงนี้ให้ผู้ประเมินอนุมัติใช่หรือไม่?"
  );
}
function requireEdit() {
  dialogConfirm(
    $q,
    () => {
      if (kpiId.value) {
        showLoader();
        http
          .put(config.API.kpiReqEdit(kpiId.value), {
            status: "EVALUATOR",
          })
          .then((res) => {
            success($q, "ขอแก้ไขสำเร็จ");
            close();
          })
          .catch((e) => {
            messageError($q, e);
          })
          .finally(() => {
            hideLoader();
          });
      }
    },
    "ยืนยันการขอแก้ไขข้อตกลง",
    "ต้องการยืนยันการขอแก้ไขข้อตกลงนี้ใช่หรือไม่?"
  );
}
function fetchProfile(id: string) {
  http
    .get(
      config.API.fileByFile("ทะเบียนประวัติ", "โปรไฟล์", id, `profile-${id}`)
    )
    .then((res) => {
      avartarProfile.value = res.data.downloadUrl;
    })
    .catch(() => {
      avartarProfile.value = Avatar;
    });
}

/** Dialog  ข้อมูลผู้ประเมิน*/
const modal = ref<boolean>(false);
const evaluatorIdOp = ref<DataOption[]>([]);
const commanderIdOp = ref<DataOption[]>([]);
const commanderHighOp = ref<DataOption[]>([]);
const evaluatorIdMainOp = ref<DataOption[]>([]);
const commanderIdMainOp = ref<DataOption[]>([]);
const commanderHighMainOp = ref<DataOption[]>([]);
const evaluatorId = ref<any>(null);
const commanderId = ref<any>(null);
const commanderHighId = ref<any>(null);

function openDialogAssessor() {
  modal.value = true;
  fetchListAssessor();
}
function closeDialogAssessor() {
  modal.value = false;
  evaluatorId.value = null;
  commanderId.value = null;
  commanderHighId.value = null;
}
function onSubmit() {
  dialogConfirm($q, () => {
    if (kpiId.value) {
      showLoader();
      http
        .put(config.API.kpiEvaluationCheck + `/${kpiId.value}`, {
          evaluatorId: evaluatorId.value ? evaluatorId.value.id : null,
          commanderId: commanderId.value ? commanderId.value.id : null,
          commanderHighId: commanderHighId.value
            ? commanderHighId.value.id
            : null,
        })
        .then(() => {
          close();
          fetchEvaluation();
          success($q, "บันทึกสำเร็จ");
        })
        .catch((e) => {
          messageError($q, e);
        })
        .finally(() => {
          hideLoader();
        });
    }
  });
}
function fetchListAssessor() {
  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;
  }
}

/** ์ Body*/
const splitterModel = ref<number>(15);
const itemsTab = ref<ItemsTab[]>([
  {
    name: "1",
    label: "จัดทำแบบฟอร์มการประเมิน",
  },
  {
    name: "2",
    label: "รายงานความก้าวหน้า",
  },
  {
    name: "3",
    label: "รายงานผลสำเร็จของงาน",
  },
  {
    name: "5",
    label: "ไฟล์เอกสาร",
  },
]);

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

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

  <!-- Profile -->
  <q-card>
    <q-card-section style="padding: 0px">
      <div
        class="absolute-center-left"
        style="left: 2%; top: 50%; transform: translateY(-50%)"
      >
        <q-avatar size="90px">
          <q-img :src="avartarProfile" />
        </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">
                {{
                  `${dataEvaluation?.prefix ?? ""}${
                    dataEvaluation?.firstName
                  } ${dataEvaluation?.lastName}`
                }}
              </span>
              <q-space />
              <div class="q-gutter-x-sm">
                <span
                  class="text-red"
                  v-if="
                    (store.dataEvaluation.posExecutiveName == null &&
                      store.indicatorWeightTotal != 100) ||
                    (store.dataEvaluation.posExecutiveName != null &&
                      (store.indicatorWeight1Total != 100 ||
                        store.indicatorWeight2Total != 20))
                  "
                  >*น้ำหนัก(ร้อยละ) ผลสัมฤทธิ์ของงานไม่ถูกต้อง</span
                >
                <q-btn
                  v-if="
                    store.rolePerson == 'USER' &&
                    store.dataEvaluation.evaluationStatus == 'NEW'
                  "
                  :disabled="
                    (store.dataEvaluation.posExecutiveName == null &&
                      store.indicatorWeightTotal != 100) ||
                    (store.dataEvaluation.posExecutiveName != null &&
                      (store.indicatorWeight1Total != 100 ||
                        store.indicatorWeight2Total != 20))
                  "
                  unelevated
                  round
                  icon="mdi-send"
                  color="grey-2"
                  text-color="blue-6"
                  size="md"
                >
                  <q-tooltip>ส่งให้ผู้ประเมินอนุมัติ</q-tooltip>
                </q-btn>

                <q-btn
                  v-if="
                    store.rolePerson == 'USER' &&
                    store.dataEvaluation.evaluationStatus == 'EVALUATING'
                  "
                  unelevated
                  round
                  icon="mdi-send"
                  color="grey-2"
                  text-color="blue-6"
                  size="md"
                  @click="sendToEvaluatore('EVALUATING_EVALUATOR')"
                >
                  <q-tooltip>ส่งให้ผู้ประเมินอนุมัติผลการประเมิน</q-tooltip>
                </q-btn>

                <q-btn
                  v-if="
                    store.rolePerson == 'USER' &&
                    store.tabOpen < 3 &&
                    store.dataEvaluation.evaluationStatus != 'NEW' &&
                    (store.dataEvaluation.evaluationReqEdit == null ||
                      store.dataEvaluation.evaluationReqEdit == 'DONE')
                  "
                  :disabled="store.dataEvaluation.evaluatorId == null"
                  unelevated
                  round
                  icon="mdi-file-edit"
                  color="grey-2"
                  text-color="red-6"
                  size="md"
                  @click="requireEdit()"
                >
                  <q-tooltip>ขอแก้ไขข้อตกลง</q-tooltip>
                </q-btn>

                <q-btn
                  unelevated
                  round
                  icon="mdi-account"
                  color="grey-2"
                  text-color="edit"
                  size="md"
                  @click="openDialogAssessor"
                >
                  <q-tooltip>{{
                    dataEvaluation?.evaluationStatus === "NEW" &&
                    store.rolePerson === "USER"
                      ? "แก้ไขผู้ประเมิน"
                      : "ข้อมูลผู้ประเมิน"
                  }}</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">
                    {{ dataEvaluation?.position }}
                  </span>
                </div>
              </div>
              <div class="col-2">
                <div class="column">
                  <span class="text-grey-6">ประเภทตำแหน่ง</span>
                  <span class="text-weight-medium text-dark">
                    {{ dataEvaluation?.posTypeName }}
                  </span>
                </div>
              </div>
              <div class="col-2">
                <div class="column">
                  <span class="text-grey-6">ระดับตำแหน่ง</span>
                  <span class="text-weight-medium text-dark">
                    {{ dataEvaluation?.posLevelName }}
                  </span>
                </div>
              </div>
              <div class="col-2">
                <div class="column">
                  <span class="text-grey-6">สถานะการประเมิน</span>
                  <span class="text-weight-medium text-dark">
                    {{
                      dataEvaluation?.evaluationStatus
                        ? store.convertStatus(dataEvaluation?.evaluationStatus)
                        : "-"
                    }}
                  </span>
                </div>
              </div>
              <div class="col-2">
                <div class="column">
                  <span class="text-grey-6">ผลการประเมิน</span>
                  <span class="text-weight-medium text-dark">
                    {{
                      dataEvaluation?.evaluationResults
                        ? store.convertResults(dataEvaluation.evaluationResults)
                        : "-"
                    }}
                    ผลการประเมิน
                  </span>
                </div>
              </div>
              <div class="col-2">
                <div class="column">
                  <span class="text-grey-6">คะแนนประเมิน</span>
                  <span class="text-weight-medium text-primary">
                    คะแนนประเมิน
                    {{
                      dataEvaluation?.posExecutiveName === null
                        ? (
                            store.indicatorScoreVal +
                            store.competencyScoreVal +
                            store.devScoreVal
                          ).toFixed(2)
                        : (
                            store.excusiveIndicator1ScoreVal +
                            store.excusiveIndicator2ScoreVal +
                            store.competencyScoreVal
                          ).toFixed(2)
                    }}
                  </span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </q-card-section>
  </q-card>

  <q-card class="q-mt-md">
    <q-card-section style="padding: 0px">
      <q-splitter v-model="splitterModel" disable>
        <template v-slot:before>
          <q-tabs
            v-model="store.tabMain"
            vertical
            class="text-grey-7 text-weight-light"
            active-class="bg-blue-1 text-blue-8 text-weight-bold"
          >
            <q-tab name="1" label="จัดทำข้อตกลง" />
            <q-tab
              name="2"
              label="รายงานความก้าวหน้า"
              :disable="store.tabOpen < 2"
            />
            <q-tab
              name="3"
              label="รายงานผลสำเร็จของงาน"
              :disable="store.tabOpen < 3"
            />

            <q-tab name="5" label="ไฟล์เอกสาร" />
          </q-tabs>
        </template>

        <template v-slot:after>
          <q-tab-panels
            v-model="store.tabMain"
            animated
            swipeable
            vertical
            transition-prev="jump-up"
            transition-next="jump-up"
          >
            <q-tab-panel
              v-for="(tab, index) in itemsTab"
              :key="index"
              :name="tab.name"
              class="q-pa-none"
            >
              <Assessment v-if="store.tabMain === '1'" />
              <Assessment v-if="store.tabMain === '2'" />
              <Assessment v-if="store.tabMain === '3'" />
              <File v-if="store.tabMain === '5'" />
            </q-tab-panel>
          </q-tab-panels>
        </template> </q-splitter
    ></q-card-section>
  </q-card>

  <q-dialog v-model="modal" persistent>
    <q-card bordered style="width: 50vh">
      <q-form greedy @submit.prevent @validation-success="onSubmit">
        <DialogHeader
          :tittle="
            store.dataEvaluation.evaluationStatus === 'NEW' &&
            store.rolePerson === 'USER'
              ? 'แก้ไขผู้ประเมิน'
              : 'ข้อมูลผู้ประเมิน'
          "
          :close="closeDialogAssessor"
        />
        <q-separator />
        <q-card-section>
          <div class="column q-gutter-sm">
            <q-select
              :readonly="
                !(
                  store.dataEvaluation.evaluationStatus === 'NEW' &&
                  store.rolePerson === 'USER'
                )
              "
              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
              :readonly="
                !(
                  store.dataEvaluation.evaluationStatus === 'NEW' &&
                  store.rolePerson === 'USER'
                )
              "
              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="
                  store.dataEvaluation.evaluationStatus === 'NEW' &&
                  store.rolePerson === 'USER' &&
                  commanderId
                "
                v-slot:append
              >
                <q-icon
                  name="cancel"
                  @click.stop.prevent="commanderId = null"
                  class="cursor-pointer"
                />
              </template>
            </q-select>
            <q-select
              :readonly="
                !(
                  store.dataEvaluation.evaluationStatus === 'NEW' &&
                  store.rolePerson === 'USER'
                )
              "
              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="
                  store.dataEvaluation.evaluationStatus === 'NEW' &&
                  store.rolePerson === 'USER' &&
                  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
          v-if="
            store.dataEvaluation.evaluationStatus === 'NEW' &&
            store.rolePerson === 'USER'
          "
          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 scoped>
.bg-toolbar {
  background-color: #f2fbfa;
}

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