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

import http from "@/plugins/http";
import config from "@/app.config";
import { useCounterMixin } from "@/stores/mixin";
import { useEvaluateDetailStore } from "@/modules/06_evaluate/stores/evaluteDetail";

/** importType*/
import type {
  EducationForm,
  CertificatesForm,
} from "@/modules/06_evaluate/interface/evalute";

/** importComponents*/
import TableData from "@/modules/06_evaluate/components/viewstep/tableStep1.vue";

/** use*/
const mixin = useCounterMixin();
const store = useEvaluateDetailStore();
const $q = useQuasar();
const route = useRoute();
const { showLoader, hideLoader, messageError, date2Thai } = mixin;
const {
  columnsCertificates,
  columnSalaries,
  columnTraining,
  columnProjectsProposed,
  columnAssessments,
} = store;

const props = defineProps({
  data: {
    type: Object,
  },
});

const emit = defineEmits(["update:formDeital"]);

const formDetail = reactive<any>({
  userId: "",
  citizenId: "",
  prefix: "",
  fullName: "",
  position: "",
  oc: "",
  org: "",
  salary: "",
  positionLevel: "",
  posNo: "",
  birthDate: "",
  govAge: "",
  govAgeMap: {
    year: 0,
    month: 0,
    day: 0,
  },
  educations: [] as EducationForm[],
  certificates: [],
  salaries: [],
  trainings: [],
  assessments: [],
  honor: [],
});

/** function เรียกข้อมูลตรวจสอบคุณสมบัติ*/
async function fetchDetail() {
  showLoader();
  await http
    .get(config.API.positionBykeycloak())
    .then((res) => {
      const data = res.data.result;
      formDetail.userId = data.id;
      formDetail.citizenId = data.citizenId;
      formDetail.prefix = data.prefix;
      formDetail.fullName = `${data.firstName}  ${data.lastName}`;
      formDetail.firstName = data.firstName;
      formDetail.lastName = data.lastName;
      formDetail.position = data.position;
      formDetail.oc = data.rootShortName;
      formDetail.positionLevel = data.posLevelName;
      formDetail.posNo = data.posNo ?? '';
      formDetail.birthDate = data.birthDate;
      formDetail.govAge = data.govAge; // ยังไม่มี
      formDetail.salary = data.salary;

      http.get(config.API.dataUserEducations).then((res) => {
        formDetail.educations = res.data.result;
      });

      http.get(config.API.dataUserCertificate("certificate")).then((res) => {
        formDetail.certificates = res.data.result.map(
          (e: CertificatesForm) => ({
            certificateNo: e.certificateNo,
            certificateType: e.certificateType,
            expireDate: e.expireDate,
            issueDate: e.issueDate,
            issuer: e.issuer,
          })
        );
      });

      http.get(config.API.dataUserSalary).then((res) => {
        formDetail.salaries = res.data.result;
        // formDetail.salary = formDetail.salaries
        //   ? formattedNumber(
        //       formDetail.salaries[formDetail.salaries.length - 1].amount
        //     )
        //   : "";
      });

      http.get(config.API.dataUserCertificate("training")).then((res) => {
        formDetail.trainings = res.data.result.map((e: any) => ({
          dateOrder: e.dateOrder,
          department: e.department,
          duration: e.duration,
          endDate: e.endDate,
          name: e.name,
          numberOrder: e.numberOrder,
          place: e.place,
          startDate: e.startDate,
          topic: e.topic,
          yearly: e.yearly,
        }));
      });

      http.get(config.API.dataUserAssessments).then((res) => {
        // formDetail.honor =  res.data.result
        //  res.data.result.map((e: any) => ({
        //   receivedDate: e.createdAt,
        //   authority: e.issuer,
        //   detail: e.detail,
        //   orderNumber: e.refCommandNo,
        //   doce: e.refCommandDate,
        formDetail.assessments = res.data.result;
      });
      // }));
      emit("update:formDeital", formDetail);
    })
    .catch((err) => {
      messageError($q, err);
    })
    .finally(() => {
      setTimeout(() => {
        hideLoader();
      }, 2500);
    });
}

/**
 *  function fetchData ตรวจสอบคุณสมบัติ
 * @param id ประเมิน
 */
async function fetchCheckSpec(data: any) {
  formDetail.userId = data.id;
  formDetail.citizenId = data.citizenId;
  formDetail.prefix = data.prefix;
  formDetail.fullName = data.fullName;
  formDetail.position = data.position;
  formDetail.oc = data.oc;
  formDetail.salary = data.salary ? formattedNumber(data.salary) : "";
  formDetail.positionLevel = data.positionLevel;
  formDetail.posNo = data.posNo;
  formDetail.birthDate = data.birthDate;
  formDetail.educations = data.educations;

  formDetail.certificates = data.certificates.map((e: CertificatesForm) => ({
    certificateNo: e.certificateNo,
    certificateType: e.certificateType,
    expireDate: date2Thai(e.expireDate),
    issueDate: date2Thai(e.issueDate),
    issuer: e.issuer,
  }));
  formDetail.salaries = data.salaries.map((e: any) => ({
    amount: e.amount,
    date: e.date,
    mouthSalaryAmount: e.mouthSalaryAmount ? e.mouthSalaryAmount : 0,
    posNo: e.posNo,
    position: e.position,
    positionSalaryAmount: e.positionSalaryAmount ? e.positionSalaryAmount : 0,
    refCommandDate: e.refCommandDate ? e.refCommandDate : "",

    refCommandNo: e.refCommandNo ? e.refCommandNo : "",
    salaryClass: e.salaryClass ? e.salaryClass : "",
    salaryRef: e.salaryRef ? e.salaryRef : "",
    salaryStatus: e.salaryStatus ? e.salariesStatus : "",
    //
    oc: "-",
    lineWork: "-",
    side: "-",
    positionType: "-",
    level: "-",
    positionsAdministrative: "-",
    aspectAdministrative: "-",
  }));
  formDetail.trainings = data.trainings.map((e: any) => ({
    dateOrder: date2Thai(e.dateOrder),
    department: e.department,
    duration: e.duration,
    endDate: date2Thai(e.endDate),
    name: e.name,
    numberOrder: e.numberOrder,
    place: e.place,
    startDate: date2Thai(e.startDate),
    topic: e.topic,
    yearly: e.yearly,
  }));
  formDetail.assessments = data.assessments;
}

/**
 * function convertตัวเลข
 * @param x
 */
function formattedNumber(x: number) {
  if (x) {
    return x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  } else {
    return "";
  }
}

/** get data */
function getData() {
  showLoader();
  http
    .get(config.API.dataUserGovernment)
    .then((res) => {
      const data = res.data.result;
      formDetail.org = data.org;
      formDetail.govAge = data.govAge
        ? `${data.govAge.year} วัน ${data.govAge.month} เดือน ${data.govAge.year} ปี`
        : "";
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(() => {
      setTimeout(() => {
        hideLoader();
      }, 2500);
    });
}

onMounted(async () => {
  const promises = [];

  if (route.name === "evaluate-add") {
    promises.push(fetchDetail());
  }

  if (props.data) {
    promises.push(fetchCheckSpec(props.data));
  }

  promises.push(getData());

  await Promise.all(promises);
});
</script>

<template>
  <q-card
    bordered
    class="col-12 row shadow-0 q-pa-sm"
    :style="$q.screen.lt.sm ? '' : 'height: 60vh; overflow: scroll;'"
  >
    <div class="row col-12">
      <q-card class="col-12 cardSp1" bordered>
        <div class="text-weight-bold row items-center bg-grey-2 col-12">
          <span class="q-ml-lg q-my-sm">ข้อมูลส่วนตัว</span>
        </div>
        <div class="col-12"><q-separator /></div>

        <div class="row col-12 q-pa-sm">
          <div class="row q-col-gutter-sm">
            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                readonly
                :model-value="formDetail.prefix"
                label="คำนำหน้าชื่อ"
              ></q-input>
            </div>
            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                readonly
                :model-value="formDetail.fullName"
                label="ชื่อ - นามสกุล"
              />
            </div>
            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                :model-value="
                  formDetail.birthDate ? date2Thai(formDetail.birthDate) : '-'
                "
                readonly
                label="วันเดือนปีเกิด"
              >
              </q-input>
            </div>
            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                readonly
                :model-value="formDetail.position"
                label="ตำแหน่ง"
              />
            </div>
            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                readonly
                :model-value="`${formDetail.posNo ? formDetail.posNo :'-'}`"
                label="ตำแหน่งเลขที่"
              />
            </div>
            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                readonly
                :model-value="formDetail.salary"
                label="เงินเดือน"
              />
            </div>

            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                readonly
                :model-value="formDetail.positionLevel"
                label="ระดับปัจจุบัน"
              />
            </div>

            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                readonly
                :model-value="formDetail.positionLevel"
                label="ระดับที่ประเมิน"
              />
            </div>

            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                readonly
                :model-value="formDetail.govAge ? formDetail.govAge : '-'"
                label="อายุราชการ"
              />
            </div>
            <div class="col-xs-12 col-sm-9">
              <q-input
                borderless
                readonly
                :model-value="formDetail.org"
                label="สังกัด"
                autogrow
              />
            </div>
          </div>
        </div>
      </q-card>

      <q-card class="col-12 cardSp1" bordered>
        <div class="text-weight-bold row items-center bg-grey-2 col-12">
          <span class="q-ml-lg q-my-sm">ประวัติการศึกษา </span>
        </div>
        <div class="col-12"><q-separator /></div>
        <div
          class="row col-12 q-pa-sm"
          v-if="formDetail.educations && formDetail.educations.length > 0"
        >
          <div
            class="row q-col-gutter-sm"
            v-for="(education, index) in formDetail.educations"
            :key="index"
          >
            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                readonly
                :model-value="
                  education.educationLevel ? education.educationLevel : '-'
                "
                label="ระดับศึกษา"
              />
            </div>

            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                readonly
                :model-value="education.institute ? education.institute : '-'"
                label="สถานศึกษา"
              />
            </div>

            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                :model-value="
                  education.startDate ? date2Thai(education.startDate) : '-'
                "
                readonly
                label="ตั้งแต่"
              >
              </q-input>
            </div>

            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                :model-value="
                  education.endDate ? date2Thai(education.endDate) : '-'
                "
                readonly
                label="ถึง"
              >
              </q-input>
            </div>
            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                :model-value="
                  education.finishDate ? date2Thai(education.finishDate) : '-'
                "
                readonly
                label="วันที่สำเร็จการศึกษา"
              >
              </q-input>
            </div>

            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                readonly
                :model-value="education.isEducation ? 'ใช่' : 'ไม่ใช่'"
                label="วุฒิการศึกษาในตําแหน่ง"
              />
            </div>

            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                readonly
                :model-value="education.degree ? education.degree : '-'"
                label="วุฒิการศึกษา"
              />
            </div>

            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                readonly
                :model-value="education.field ? education.field : '-'"
                label="สาขาวิชา/ทาง"
              />
            </div>
            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                readonly
                :model-value="education.fundName ? education.fundName : '-'"
                label="ทุน"
              />
            </div>

            <div class="col-xs-6 col-sm-4 col-md-3">
              <q-input
                borderless
                readonly
                :model-value="education.gpa ? education.gpa : '-'"
                label="เกรดเฉลี่ย"
              />
            </div>

            <div class="col-xs-6 col-sm-4 col-md-6">
              <q-input
                borderless
                readonly
                :model-value="education.country ? education.country : '-'"
                label="ประเทศ"
              />
            </div>
            <div
              v-if="index + 1 !== formDetail.educations.length"
              class="col-12"
            >
              <q-separator size="2px" />
            </div>
          </div>
        </div>
        <div v-else class="row col-12 q-pa-md">ไม่มีประวัติการศึกษา</div>
      </q-card>

      <q-card class="col-12 cardSp1" bordered>
        <div class="text-weight-bold row items-center bg-grey-2 col-12">
          <span class="q-ml-lg q-my-sm">ใบอนุญาตประกอบวิชาชีพ</span>
        </div>
        <div class="col-12"><q-separator /></div>
        <TableData
          class="col-12"
          :columns="columnsCertificates"
          :row="formDetail.certificates"
        />
      </q-card>

      <q-card class="col-12 cardSp1" bordered>
        <div class="text-weight-bold row items-center bg-grey-2 col-12">
          <span class="q-ml-lg q-my-sm">ประวัติการรับราชการ</span>
        </div>
        <div class="col-12"><q-separator /></div>
        <div class="col-10">
          <d-table
            ref="table"
            row-key="id"
            flat
            bordered
            dense
            :columns="columnSalaries"
            :rows="formDetail.salaries"
            :paging="true"
            :rows-per-page-options="[20, 50, 100]"
          >
            <template v-slot:header="props">
              <q-tr :props="props">
                <q-th v-for="col in props.cols" :key="col.name" :props="props">
                  <span class="text-weight-medium">{{ col.label }}</span>
                </q-th>
              </q-tr>
            </template>
            <template v-slot:body="props">
              <q-tr :props="props" class="cursor-pointer">
                <q-td
                  v-for="col in props.cols"
                  :key="col.id"
                  class="vertical-top"
                >
                  <div class="table_ellipsis">
                    {{ col.value ? col.value : "-" }}
                  </div>
                </q-td>
              </q-tr>
            </template>
          </d-table>
          <!-- <TableData :columns="columnSalaries" :row="formDetail.salaries" /> -->
        </div>
      </q-card>

      <q-card class="col-12 cardSp1" bordered>
        <div class="text-weight-bold row items-center bg-grey-2 col-12">
          <span class="q-ml-lg q-my-sm">ประวัติการฝึกอบรมดูงาน</span>
        </div>
        <div class="col-12"><q-separator /></div>
        <TableData
          class="col-12"
          :columns="columnTraining"
          :row="formDetail.trainings"
        />
      </q-card>

      <q-card class="col-12 cardSp1" bordered>
        <div class="text-weight-bold row items-center bg-grey-2 col-12">
          <span class="q-ml-lg q-my-sm">ประสบการณ์ในการปฏิบัติงาน </span>
        </div>
        <div class="col-12"><q-separator /></div>
        <div class="col-12 q-pa-sm">-</div>
      </q-card>

      <q-card class="col-12 cardSp1" bordered>
        <div class="text-weight-bold row items-center bg-grey-2 col-12">
          <span class="q-ml-lg q-my-sm">ผลงานที่เคยเสนอขอประเมิน (ถ้ามี)</span>
        </div>
        <div class="col-12"><q-separator /></div>
        <div class="col-10">
          <TableData
            :columns="columnAssessments"
            :row="formDetail.assessments"
          />
        </div>
      </q-card>
    </div>
  </q-card>
</template>

<style>
.cardSp1 {
  border: 1px solid #d6dee1;
  margin-bottom: 10px;
  box-shadow: none !important;
}
</style>
