<!-- step กรอกข้อมูล -->
<template>
  <div class="toptitle text-dark col-12 row items-center">
    <q-btn
      icon="mdi-arrow-left"
      unelevated
      round
      dense
      flat
      color="primary"
      class="q-mr-sm"
      @click="router.go(-1)"
    />
    ตรวจสอบคุณสมบัติผู้สมัครสอบรอบคัดเลือก
    <q-space />
    <q-btn
      color="blue"
      flat
      round
      icon="mdi-content-save-outline"
      @click="clickSave"
      v-if="status == 'checkRegister' || status == 'payment'"
      class="q-mr-sm bg-blue-1"
      outline
    >
      <q-tooltip>บันทึกข้อมูล</q-tooltip>
    </q-btn>
    <q-btn
      color="primary"
      flat
      round
      icon="check"
      class="bg-teal-1"
      @click="modalCheck"
      v-if="status == 'checkRegister'"
    >
      <q-tooltip>ตรวจสอบข้อมูล</q-tooltip>
    </q-btn>
  </div>
  <q-card class="q-pa-md">
    <div>
      <Profile
        :status="status"
        v-model:formInformation="formInformation"
        v-model:formAddress="formAddress"
        v-model:formFamily="formFamily"
        v-model:formOccupation="formOccupation"
      />
    </div>
  </q-card>
  <q-dialog :model-value="modal" persistent>
    <q-card style="min-width: 700px">
      <q-form ref="myForm">
        <div class="row items-center q-pa-sm">
          <div class="row">
            <div class="text-bold">ตรวจสอบคุณสมบัติ</div>
          </div>
          <q-space />
          <q-btn
            icon="close"
            unelevated
            round
            dense
            style="color: #ff8080; background-color: #ffdede"
            size="12px"
            @click="close"
          />
        </div>
        <q-separator />
        <!-- header บน table มี ค้นหา แสดงคอลัมน์ (status nornmalData true) -->
        <div class="col-12 row q-pa-md">
          <q-radio
            v-model="approve"
            checked-icon="task_alt"
            unchecked-icon="panorama_fish_eye"
            val="1"
            label="ผ่านการตรวจสอบคุณสมบัติ"
            class="col-12"
            @update:modelValue="reason = ''"
          />
          <q-radio
            v-model="approve"
            checked-icon="task_alt"
            unchecked-icon="panorama_fish_eye"
            val="2"
            label="ไม่ผ่านการตรวจสอบคุณสมบัติ(ผู้สมัครแก้ข้อมูลสมัคร)"
            class="col-12"
          />
          <q-radio
            v-model="approve"
            checked-icon="task_alt"
            unchecked-icon="panorama_fish_eye"
            val="3"
            label="ไม่ผ่านการตรวจสอบคุณสมบัติ"
            class="col-12"
          />
          <q-input
            class="col-12 q-px-sm q-pt-sm"
            outlined
            stack-label
            v-model="reason"
            label="หมายเหตุ"
            lazy-rules
            autofocus
            hide-bottom-space
            v-if="approve == '2' || approve == '3'"
            type="textarea"
          ></q-input>
        </div>
        <q-separator />
        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn
            flat
            round
            color="public"
            @click="checkSave"
            icon="mdi-content-save-outline"
          >
            <q-tooltip>บันทึกตรวจสอบ</q-tooltip>
          </q-btn>
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import Profile from "@/modules/03_recruiting/components/Profile.vue";
import {
  defaultInformation,
  defaultOccupation,
  defaultAddress,
  defaultFamily,
} from "@/modules/03_recruiting/interface/index/Main";
import { useCounterMixin } from "@/stores/mixin";
import { useRoute, useRouter } from "vue-router";
import { useQuasar } from "quasar";
import http from "@/plugins/http";
import config from "@/app.config";

const router = useRouter();
const $q = useQuasar();
const mixin = useCounterMixin(); //เรียกฟังก์ชันกลาง
const { success, dateToISO, messageError, showLoader, hideLoader } = mixin;
const route = useRoute();
const examId = ref<string>(route.params.examId.toString());
const candidateId = ref<string>(route.params.candidateId.toString());
const modal = ref<boolean>(false);
const approve = ref<string>("1");
const reason = ref<string>("");
const formInformation = ref<any>({});
const formAddress = ref<any>({});
const formFamily = ref<any>({});
const formOccupation = ref<any>({});
const status = ref<string>("");

onMounted(async () => {
  await fetchStatus();
});

const fetchStatus = async () => {
  showLoader();
  await http
    .get(config.API.candidateId(candidateId.value))
    .then((res) => {
      const data = res.data.result;
      status.value = data.status;
    })
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
    });
};

const confirm = async (status: boolean, reason: string) => {
  showLoader();
  await http
    .put(config.API.candidateCheckRegister(candidateId.value), {
      status: status,
      reason: reason,
    })
    .then((res) => {})
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      success($q, "ตรวจสอบข้อมูลสำเร็จ");
      router.push(`/qualify/manage/${examId.value}`);
    });
};

const reject = async (reason: string) => {
  showLoader();
  await http
    .put(config.API.candidateRejectRegister(candidateId.value), {
      reason: reason,
    })
    .then((res) => {})
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      success($q, "ตรวจสอบข้อมูลสำเร็จ");
      router.push(`/qualify/manage/${examId.value}`);
    });
};

const checkSave = () => {
  if (approve.value == "1") {
    confirm(true, "");
  } else if (approve.value == "2") {
    confirm(false, reason.value);
  } else {
    reject(reason.value);
  }
};

const modalCheck = () => {
  modal.value = true;
};

const close = () => {
  modal.value = false;
};

const clickSave = async () => {
  await formInformation.value.validate().then(async (suc: boolean) => {
    if (suc) {
      await formAddress.value.validate().then(async (suc: boolean) => {
        if (suc) {
          await formFamily.value.validate().then(async (suc: boolean) => {
            if (suc) {
              await formOccupation.value
                .validate()
                .then(async (suc: boolean) => {
                  if (suc) {
                    const type = ref<string | null>("");
                    if (defaultOccupation.value.status == "official")
                      type.value = defaultOccupation.value.official;
                    if (defaultOccupation.value.status == "personnel")
                      type.value = defaultOccupation.value.personnel;
                    if (defaultOccupation.value.status == "officialsOther")
                      type.value = defaultOccupation.value.officialsOther;
                    if (defaultOccupation.value.status == "employee")
                      type.value = defaultOccupation.value.employee;
                    if (defaultOccupation.value.status == "other")
                      type.value = defaultOccupation.value.other;
                    showLoader();
                    await http
                      .post(config.API.candidateId(candidateId.value), {
                        prefixId: defaultInformation.value.prefixId,
                        lastName: defaultInformation.value.lastname,
                        citizenProvinceId: defaultInformation.value.provinceId,
                        citizenDistrictId: defaultInformation.value.districtId,
                        dateOfBirth:
                          defaultInformation.value.birthDate == null
                            ? null
                            : dateToISO(defaultInformation.value.birthDate),
                        citizenDate:
                          defaultInformation.value.cardIdDate == null
                            ? null
                            : dateToISO(defaultInformation.value.cardIdDate),
                        citizenId: defaultInformation.value.cardid,
                        firstName: defaultInformation.value.firstname,
                        relationshipId: defaultInformation.value.relationshipId,
                        nationality: defaultInformation.value.nationality,
                        email: defaultInformation.value.email,
                        mobilePhone: defaultInformation.value.phone,
                        telephone: defaultInformation.value.tel,
                        knowledge: defaultInformation.value.knowledge,
                        occupationType: defaultOccupation.value.status,
                        occupationCompany: defaultOccupation.value.company,
                        occupationDepartment:
                          defaultOccupation.value.department,
                        occupationEmail: defaultOccupation.value.email,
                        occupationTelephone: defaultOccupation.value.tel,
                        occupationPosition: type.value,
                        registAddress: defaultAddress.value.address,
                        currentAddress: defaultAddress.value.addressC,
                        registProvinceId: defaultAddress.value.provinceId,
                        currentProvinceId: defaultAddress.value.provinceIdC,
                        registDistrictId: defaultAddress.value.districtId,
                        currentDistrictId: defaultAddress.value.districtIdC,
                        registSubDistrictId: defaultAddress.value.subdistrictId,
                        currentSubDistrictId:
                          defaultAddress.value.subdistrictIdC,
                        registZipCode: defaultAddress.value.code,
                        currentZipCode: defaultAddress.value.codeC,
                        registSame:
                          defaultAddress.value.same == "1"
                            ? true
                            : defaultAddress.value.same == "0"
                            ? false
                            : null,
                        marryPrefixId: defaultFamily.value.prefixIdC,
                        marryFirstName: defaultFamily.value.firstnameC,
                        marryLastName: defaultFamily.value.lastnameC,
                        marryOccupation: defaultFamily.value.occupationC,
                        marryNationality: defaultFamily.value.nationalityC,
                        fatherPrefixId: defaultFamily.value.prefixIdM,
                        fatherFirstName: defaultFamily.value.firstnameM,
                        fatherLastName: defaultFamily.value.lastnameM,
                        fatherOccupation: defaultFamily.value.occupationM,
                        fatherNationality: defaultFamily.value.nationalityM,
                        motherPrefixId: defaultFamily.value.prefixIdF,
                        motherFirstName: defaultFamily.value.firstnameF,
                        motherLastName: defaultFamily.value.lastnameF,
                        motherOccupation: defaultFamily.value.occupationF,
                        motherNationality: defaultFamily.value.nationalityF,
                        marry:
                          defaultFamily.value.same == "1"
                            ? true
                            : defaultFamily.value.same == "0"
                            ? false
                            : null,
                      })
                      .then(async () => {
                        success($q, "บันทึกข้อมูลส่วนตัวสำเร็จ");
                      })
                      .catch((e) => {
                        messageError($q, e);
                      })
                      .finally(async () => {
                        hideLoader();
                      });
                  }
                });
            }
          });
        }
      });
    }
  });
};
</script>

<style lang="scss" scoped></style>
