<!-- step กรอกข้อมูล -->
<template>
  <div>
    <Profile
      :status="status"
      v-model:formInformation="formInformation"
      v-model:formAddress="formAddress"
      v-model:formFamily="formFamily"
      v-model:formOccupation="formOccupation"
    />
    <div class="text-center q-pt-sm">
      <q-checkbox
        v-model="acceptTermOfUse"
        :disable="(status !== 'register' && status !== 'rejectRegister') || statusEdit"
        label="ข้าพเจ้ารับรองว่า ข้าพเจ้ามีคุณสมบัติครบถ้วนตามประกาศรับสมัคร ข้อความข้างต้นตรงตามความจริงทุกประการ"
      />
    </div>

    <div class="row justify-center q-pa-md">
      <q-btn
        color="blue"
        class="q-ml-md"
        label="บันทึกข้อมูล"
        outline
        icon="mdi-content-save"
        @click="saveAuto = false && saveData"
        v-if="status === 'register' || status === 'rejectRegister'"
        :disable="!acceptTermOfUse || statusEdit"
      />
      <q-btn
        color="primary"
        class="q-ml-md"
        icon="mdi-check"
        label="สมัครสอบ"
        @click="okModalConfirm"
        v-if="status === 'register' || status === 'rejectRegister'"
        :disable="!acceptTermOfUse || statusEdit"
      />
    </div>
  </div>
</template>

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

const props = defineProps({
  fetchStep: {
    type: Function,
    default: () => console.log('not function')
  },
  status: {
    type: String,
    required: true
  }
})

const $q = useQuasar()
const mixin = useCounterMixin() //เรียกฟังก์ชันกลาง
const { modalConfirm, modalError, success, dateToISO } = mixin
const loader = ref<boolean>(false)
const statusEdit = ref<boolean>(false)
const acceptTermOfUse = ref<boolean>(false)
const route = useRoute()
const examId = ref<string>(route.params.id.toString())
const positionId = ref<string>(route.params.positionId.toString())
const formInformation = ref<any>({})
const formAddress = ref<any>({})
const formFamily = ref<any>({})
const formOccupation = ref<any>({})
const saveAuto = ref<boolean>(false)

onMounted(async () => {
  //   if (props.status !== 'register') {
  //     acceptTermOfUse.value = true
  //   }
  await fetchStatus()
})

const okModalConfirm = () => {
  if (statusEdit.value == true) {
    modalError($q, 'ไม่สามารถสมัครสอบได้', 'มีข้อมูลที่ยังไม่ถูกบันทึกข้อมูล')
  } else {
    saveAuto.value = true
    modalConfirm(
      $q,
      'ยืนยันการสมัครสอบ?',
      'เมื่อยืนยันการสมัครสอบแล้วจะไม่สามารถแก้ไขข้อมูลได้',
      saveData
    )
  }
}

const fetchStatus = async () => {
  loader.value = true
  await http
    .get(config.API.candidateCard(examId.value, positionId.value))
    .then((res) => {
      acceptTermOfUse.value = true
    })
    .catch(() => {})
    .finally(() => {
      loader.value = false
    })
}

const saveForm = async () => {
  loader.value = true
  await http
    .get(config.API.candidateRegister(examId.value, positionId.value))
    .then(() => {
      //   success($q, 'สมัครสอบสำเร็จสำเร็จ')
    })
    .catch(() => {})
    .finally(async () => {
      await props.fetchStep()
      loader.value = false
    })
}

const saveData = 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
                  loader.value = true
                  await http
                    .post(config.API.candidateId(examId.value, positionId.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(() => {
                      success($q, 'บันทึกข้อมูลส่วนตัวสำเร็จ')
                    })
                    .catch(() => {
                      //   modalError.value = true
                      //   modalErrorTittle.value = 'ไม่สามารถบันทึกข้อมูลร่างได้'
                      //   modalErrorDetail.value = e.response.data.message
                      // statusCode.value = e.response.data.status
                    })
                    .finally(async () => {
                      loader.value = false
                      if (saveAuto.value) await saveForm()
                      await props.fetchStep()
                    })
                }
              })
            }
          })
        }
      })
    }
  })
}
</script>

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