<!-- 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)"
    />
    ตรวจสอบคุณสมบัติผู้สมัครสอบรอบคัดเลือก
    {{
      rejectDetail == null || rejectDetail == ""
        ? ""
        : "(เหตุผล: " + rejectDetail + ")"
    }}
    <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>
    <q-btn
      color="red"
      flat
      round
      icon="refresh"
      class="bg-red-1"
      @click="modalReverse"
      v-if="status == 'payment' || status == 'checkSeat'"
    >
      <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:formOccupation="formOccupation"
        v-model:formContact="formContact"
        v-model:formEducation="formEducation"
      />
    </div>
    <!-- v-model:formFamily="formFamily" -->
  </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>

  <q-dialog :model-value="modalReverseOfficer" 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="closeReverse"
          />
        </div>
        <q-separator />
        <!-- header บน table มี ค้นหา แสดงคอลัมน์ (status nornmalData true) -->
        <div class="col-12 row q-pa-md">
          <q-input
            class="col-12 q-px-sm q-pt-sm"
            outlined
            stack-label
            v-model="reason"
            label="หมายเหตุ"
            lazy-rules
            autofocus
            hide-bottom-space
            type="textarea"
          ></q-input>
        </div>
        <q-separator />
        <q-card-actions align="right" class="bg-white text-teal">
          <q-btn
            flat
            round
            color="public"
            @click="checkSaveReverse"
            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,
  defaultContact,
  defaultAddress,
  defaultEducation,
} 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,
  notifyError,
} = 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 modalReverseOfficer = ref<boolean>(false);
const approve = ref<string>("1");
const reason = ref<string>("");
const formInformation = ref<any>({});
const formAddress = ref<any>({});
const formEducation = ref<any>({});
const formOccupation = ref<any>({});
const formContact = ref<any>({});
const status = ref<string>("");
const rejectDetail = 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;
      rejectDetail.value = data.rejectDetail;
      console.log(rejectDetail.value);
    })
    .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 checkSaveReverse = () => {
  rejectReverse(reason.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 rejectReverse = async (reason: string) => {
  showLoader();
  await http
    .put(config.API.candidateCheckRegisterReject(candidateId.value), {
      reason: reason,
    })
    .then((res) => {})
    .catch((e) => {
      messageError($q, e);
    })
    .finally(async () => {
      hideLoader();
      success($q, "สำเร็จ");
      router.push(`/qualify/manage/${examId.value}`);
    });
};

const modalReverse = () => {
  modalReverseOfficer.value = true;
};

const closeReverse = () => {
  modalReverseOfficer.value = false;
};
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 formEducation.value.validate().then(async (suc: boolean) => {
            if (suc) {
              await formOccupation.value
                .validate()
                .then(async (suc: boolean) => {
                  if (suc) {
                    await formContact.value
                      .validate()
                      .then(async (suc: boolean) => {
                        if (suc) {
                          showLoader();
                          await http
                            .post(config.API.candidateId(candidateId.value), {
                              prefixId: defaultInformation.value.prefixId,
                              lastName: defaultInformation.value.lastname,
                              dateOfBirth:
                                defaultInformation.value.birthDate == null
                                  ? null
                                  : dateToISO(
                                      defaultInformation.value.birthDate
                                    ),
                              citizenId: defaultInformation.value.cardid,
                              firstName: defaultInformation.value.firstname,
                              religionId: defaultInformation.value.religionId,
                              nationality: defaultInformation.value.nationality,
                              email: defaultInformation.value.email,
                              mobilePhone: defaultInformation.value.phone,
                              telephone: defaultInformation.value.tel,
                              knowledge: defaultInformation.value.knowledge,
                              occupationOrg: defaultOccupation.value.org,
                              occupationPile: defaultOccupation.value.pile,
                              occupationGroup: defaultOccupation.value.group,
                              occupationSalary: defaultOccupation.value.salary,
                              occupationPosition:
                                defaultOccupation.value.position,
                              occupationPositionType:
                                defaultOccupation.value.positionType,
                              occupationTelephone: defaultOccupation.value.tel,
                              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,
                              educationLevelExamId:
                                defaultEducation.value.educationLevelExamId,
                              educationName:
                                defaultEducation.value.educationName,
                              educationMajor:
                                defaultEducation.value.educationMajor,
                              educationLocation:
                                defaultEducation.value.educationLocation,
                              educationType:
                                defaultEducation.value.educationType,
                              educationEndDate:
                                defaultEducation.value.educationEndDate == null
                                  ? null
                                  : dateToISO(
                                      defaultEducation.value.educationEndDate
                                    ),
                              educationScores:
                                defaultEducation.value.educationScores,
                              educationLevelHighId:
                                defaultEducation.value.educationLevelHighId,
                              contactPrefixId:
                                defaultContact.value.contactPrefixId,
                              contactFirstname:
                                defaultContact.value.contactFirstname,
                              contactLastname:
                                defaultContact.value.contactLastname,
                              contactRelations:
                                defaultContact.value.contactRelations,
                              contactTel: defaultContact.value.contactTel,
                            })
                            .then(async () => {
                              success($q, "บันทึกข้อมูลส่วนตัวสำเร็จ");
                            })
                            .catch((e) => {
                              messageError($q, e);
                            })
                            .finally(async () => {
                              hideLoader();
                            });
                        } else {
                          notifyError($q, "กรุณากรอกข้อมูลให้ครบถ้วน");
                        }
                      });
                  } else {
                    notifyError($q, "กรุณากรอกข้อมูลให้ครบถ้วน");
                  }
                });
            } else {
              notifyError($q, "กรุณากรอกข้อมูลให้ครบถ้วน");
            }
          });
        } else {
          notifyError($q, "กรุณากรอกข้อมูลให้ครบถ้วน");
        }
      });
    } else {
      notifyError($q, "กรุณากรอกข้อมูลให้ครบถ้วน");
    }
  });
};
</script>

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