<template>
  <div>
    <q-tabs
      v-model="tab"
      dense
      class=""
      active-color="primary"
      indicator-color="primary"
      align="justify"
    >
      <q-tab name="userProfile" label="ข้อมูลส่วนตัว" />
      <q-tab name="citizenId" label="บัตรประชาชน" />
      <q-tab name="address" label="ที่อยู่" />
      <q-tab name="education" label="การศึกษา" />
      <q-tab name="career" label="อาชีพ" />
      <q-tab name="document" label="เอกสาร" />
    </q-tabs>
    <q-tab-panels v-model="tab" animated class="bg-white">
      <!-- ข้อมูลส่วนตัว -->
      <q-tab-panel name="userProfile">
        <div class="row q-px-lg">
          <div class="text-caption text-grey col-2 q-pa-md">
            <label>คำนำหน้า</label>
            <q-select
              outlined
              v-model="namePrefix"
              :options="formOptions.namePrefix"
              :disable="!allowEdit"
            />
          </div>

          <div class="text-caption text-grey col-4 q-pa-md">
            ชื่อ
            <div class="">
              <q-input outlined v-model="firstName" :disable="!allowEdit" />
            </div>
          </div>

          <div class="text-caption text-grey col-4 q-pa-md">
            นามสกุล
            <div class="">
              <q-input outlined v-model="lastName" :disable="!allowEdit" />
            </div>
          </div>

          <div class="text-caption text-grey col-2 q-pa-md">
            วัน เดือน ปีเกิด(พ.ศ.)
            <q-input outlined v-model="dateOfBirthTH" readonly :disable="!allowEdit">
              <template v-slot:append>
                <q-icon name="event" class="cursor-pointer">
                  <q-popup-proxy transition-show="scale" transition-hide="scale">
                    <q-date v-model="dateOfBirth" minimal :locale="localeTH">
                      <div class="row items-center justify-end">
                        <q-btn v-close-popup label="ตกลง" color="primary" flat />
                      </div>
                    </q-date>
                  </q-popup-proxy>
                </q-icon>
              </template>
            </q-input>
          </div>

          <!-- <div class="text-caption text-grey col-2 q-pa-md">
						อายุ
						<div class="">
							<q-input outlined v-model="age" :disable="!allowEdit" />
						</div>
					</div> -->

          <div class="text-caption text-grey col-2 q-pa-md">
            เพศ
            <div class="">
              <q-select outlined v-model="sex" :options="formOptions.sex" :disable="!allowEdit" />
            </div>
          </div>

          <div class="text-caption text-grey col-2 q-pa-md">
            สถานภาพ
            <div class="">
              <q-select
                outlined
                v-model="status"
                :options="formOptions.status"
                :disable="!allowEdit"
              />
            </div>
          </div>

          <div class="text-caption text-grey col-2 q-pa-md">
            หมู่โลหิต
            <div class="">
              <q-select
                outlined
                v-model="bloodGroup"
                :options="formOptions.bloodGroup"
                :disable="!allowEdit"
              />
            </div>
          </div>

          <div class="text-caption text-grey col-2 q-pa-md">
            สัญชาติ
            <div class="">
              <q-input outlined v-model="nationality" :disable="!allowEdit" />
            </div>
          </div>

          <div class="text-caption text-grey col-2 q-pa-md">
            เชื้อชาติ
            <div class="">
              <q-input outlined v-model="ethnicity" :disable="!allowEdit" />
            </div>
          </div>

          <div class="text-caption text-grey col-2 q-pa-md">
            ศาสนา
            <div class="">
              <q-input outlined v-model="religion" :disable="!allowEdit" />
            </div>
          </div>

          <div class="text-caption text-grey col-4 q-pa-md">
            เบอร์โทรศัพท์
            <div class="">
              <q-input outlined v-model="phoneNumber" mask="###-###-####" :disable="!allowEdit" />
            </div>
          </div>

          <div class="text-caption text-grey col-4 q-pa-md">
            อีเมล
            <div class="">
              <q-input outlined v-model="email" :disable="!allowEdit" />
            </div>
          </div>
        </div>
      </q-tab-panel>

      <!-- บัตรประจำตัวประชาชน -->
      <q-tab-panel name="citizenId">
        <div class="row q-px-lg">
          <div class="text-caption text-grey col-4 q-pa-md">
            เลขประจำตัวประชาชน
            <div class="">
              <q-input outlined v-model="citizenId" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-4 q-pa-md">
            ออกให้ ณ จังหวัด
            <q-select
              outlined
              v-model="citizenIdIssuanceAt"
              use-input
              hide-selected
              fill-input
              input-debounce="0"
              :options="formOptions.provinces"
              option-value="name"
              option-label="name"
              emit-value
              hint=""
              :disable="!allowEdit"
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey"> ไม่พบจังหวัดที่คุณค้นหา </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
          <div class="text-caption text-grey col-4 q-pa-md">
            บัตรประจำตัวเจ้าหน้าที่รัฐ (ถ้ามี)
            <div class="">
              <q-input outlined v-model="governmentOfficialId" :disable="!allowEdit" />
            </div>
          </div>

          <div class="text-caption text-grey col-3 q-pa-md">
            วันออกบัตรประชาชน
            <q-input outlined v-model="citizenIdIssuanceOnTH" readonly :disable="!allowEdit">
              <template v-slot:append>
                <q-icon name="event" class="cursor-pointer">
                  <q-popup-proxy transition-show="scale" transition-hide="scale">
                    <q-date v-model="citizenIdIssuanceOn" minimal :locale="localeTH">
                      <div class="row items-center justify-end">
                        <q-btn v-close-popup label="ตกลง" color="primary" flat />
                      </div>
                    </q-date>
                  </q-popup-proxy>
                </q-icon>
              </template>
            </q-input>
          </div>

          <div class="text-caption text-grey col-3 q-pa-md">
            หมดอายุวันที่
            <q-input outlined v-model="citizenIdExpireOnTH" readonly :disable="!allowEdit">
              <template v-slot:append>
                <q-icon name="event" class="cursor-pointer">
                  <q-popup-proxy transition-show="scale" transition-hide="scale">
                    <q-date v-model="citizenIdExpireOn" minimal :locale="localeTH">
                      <div class="row items-center justify-end">
                        <q-btn v-close-popup label="ตกลง" color="primary" flat />
                      </div>
                    </q-date>
                  </q-popup-proxy>
                </q-icon>
              </template>
            </q-input>
          </div>
        </div>
      </q-tab-panel>

      <!-- ที่อยู่ -->
      <q-tab-panel name="address">
        <!-- ที่อยู่ตามทะเบียนบ้านก่อนสมัคร -->
        <div class="row q-px-lg" v-if="!isApply">
          <div class="text-caption text-grey col-12 q-pa-md">
            ที่อยู่ตามทะเบียนบ้าน
            <div class="">
              <q-input outlined v-model="registAddress" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            จังหวัด
            <q-select
              outlined
              v-model="selectRegistProvince"
              use-input
              hide-selected
              fill-input
              input-debounce="0"
              :options="formOptions.registProvinces"
              option-label="name"
              emit-value
              hint=""
              :disable="!allowEdit"
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey"> ไม่พบจังหวัดที่คุณค้นหา </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            เขต/อำเภอ
            <q-select
              outlined
              v-model="selectRegistDistrict"
              use-input
              hide-selected
              fill-input
              input-debounce="0"
              :options="formOptions.registDistrict"
              option-label="name"
              emit-value
              hint=""
              :disable="!allowEdit"
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey"> ไม่พบจังหวัดที่คุณค้นหา </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            แขวง/ตำบล
            <q-select
              outlined
              v-model="selectRegistSubDistrict"
              use-input
              hide-selected
              fill-input
              input-debounce="0"
              :options="formOptions.registSubDistrict"
              option-label="name"
              emit-value
              hint=""
              :disable="!allowEdit"
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey"> ไม่พบจังหวัดที่คุณค้นหา </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            รหัสไปรษณีย์
            <div class="">
              <q-input outlined v-model="registZipCode" :disable="!allowEdit" readonly />
            </div>
          </div>
        </div>

        <!-- ที่อยู่ตามทะเบียนบ้านหลังสมัคร -->
        <div class="row q-px-lg" v-if="isApply">
          <div class="text-caption text-grey col-12 q-pa-md">
            ที่อยู่ตามทะเบียนบ้าน
            <div class="">
              <q-input outlined v-model="registAddress" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            จังหวัด
            <div class="">
              <q-input outlined v-model="registProvince" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            เขต/อำเภอ
            <div class="">
              <q-input outlined v-model="registDistrict" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            แขวง/ตำบล
            <div class="">
              <q-input outlined v-model="registSubDistrict" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            รหัสไปรษณีย์
            <div class="">
              <q-input outlined v-model="registZipCode" :disable="!allowEdit" readonly />
            </div>
          </div>
        </div>

        <q-separator color="secondary" size="3px" spaced="20px" inset />

        <!-- ที่อยู่ปัจจุบันก่อนสมัคร -->
        <div class="row q-px-lg" v-if="!isApply">
          <div class="text-caption text-grey col-12 q-pa-md">
            ที่อยู่ปัจจุบัน
            <div class="">
              <q-input outlined v-model="currentAddress" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            จังหวัด
            <q-select
              outlined
              v-model="selectCurrentProvince"
              use-input
              hide-selected
              fill-input
              input-debounce="0"
              :options="formOptions.currentProvinces"
              option-label="name"
              emit-value
              hint=""
              :disable="!allowEdit"
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey"> ไม่พบจังหวัดที่คุณค้นหา </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            เขต/อำเภอ
            <q-select
              outlined
              v-model="selectCurrentDistrict"
              use-input
              hide-selected
              fill-input
              input-debounce="0"
              :options="formOptions.currentDistrict"
              option-label="name"
              emit-value
              hint=""
              :disable="!allowEdit"
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey"> ไม่พบจังหวัดที่คุณค้นหา </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            แขวง/ตำบล
            <q-select
              outlined
              v-model="selectCurrentSubDistrict"
              use-input
              hide-selected
              fill-input
              input-debounce="0"
              :options="formOptions.currentSubDistrict"
              option-label="name"
              emit-value
              hint=""
              :disable="!allowEdit"
            >
              <template v-slot:no-option>
                <q-item>
                  <q-item-section class="text-grey"> ไม่พบจังหวัดที่คุณค้นหา </q-item-section>
                </q-item>
              </template>
            </q-select>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            รหัสไปรษณีย์
            <div class="">
              <q-input outlined v-model="currentZipCode" :disable="!allowEdit" readonly />
            </div>
          </div>
        </div>

        <!-- ที่อยู่ปัจจุบันหลังสมัคร -->
        <div class="row q-px-lg" v-if="isApply">
          <div class="text-caption text-grey col-12 q-pa-md">
            ที่อยู่ปัจจุบัน
            <div class="">
              <q-input outlined v-model="currentAddress" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            จังหวัด
            <div class="">
              <q-input outlined v-model="currentProvince" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            เขต/อำเภอ
            <div class="">
              <q-input outlined v-model="currentDistrict" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            แขวง/ตำบล
            <div class="">
              <q-input outlined v-model="currentSubDistrict" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            รหัสไปรษณีย์
            <div class="">
              <q-input outlined v-model="currentZipCode" :disable="!allowEdit" readonly />
            </div>
          </div>
        </div>
      </q-tab-panel>

      <!-- การศึกษา -->
      <q-tab-panel name="education">
        <div class="row q-px-lg">
          <div class="text-caption text-grey col-6 q-pa-md">
            วุฒิการศึกษา
            <div class="">
              <q-input outlined v-model="educationalQualification" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-6 q-pa-md">
            สาขา
            <div class="">
              <q-input outlined v-model="educationalField" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-6 q-pa-md">
            มหาวิทยาลัย
            <div class="">
              <q-input outlined v-model="educationalUniversity" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-6 q-pa-md">
            ระดับการศึกษา
            <div class="">
              <q-input outlined v-model="educationalLevel" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            วันที่สำเร็จการศึกษา
            <q-input outlined v-model="educationalGraduationDateTH" readonly :disable="!allowEdit">
              <template v-slot:append>
                <q-icon name="event" class="cursor-pointer">
                  <q-popup-proxy transition-show="scale" transition-hide="scale">
                    <q-date v-model="educationalGraduationDate" minimal :locale="localeTH">
                      <div class="row items-center justify-end">
                        <q-btn v-close-popup label="ตกลง" color="primary" flat />
                      </div>
                    </q-date>
                  </q-popup-proxy>
                </q-icon>
              </template>
            </q-input>
          </div>
          <div class="text-caption text-grey col-3 q-pa-md">
            เกรด
            <div class="">
              <q-input outlined v-model="educationalGPAX" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-6 q-pa-md">
            ความสามารถพิเศษ
            <div class="">
              <q-input outlined v-model="educationalTalent" :disable="!allowEdit" />
            </div>
          </div>
        </div>
      </q-tab-panel>

      <!-- อาชีพ -->
      <q-tab-panel name="career">
        <!-- ใบประกอบวิชาชีพ -->
        <div class="row q-px-lg">
          <div class="text-caption text-grey col-12 q-pa-md">
            ใบประกอบวิชาชีพ
            <div class="">
              <q-input outlined v-model="professionalLicenseName" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-4 q-pa-md">
            เลขที่
            <div class="">
              <q-input outlined v-model="professionalLicenseId" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-4 q-pa-md">
            วันที่ใช้งานได้
            <q-input
              outlined
              v-model="professionalLicenseIssuanceOnTH"
              readonly
              :disable="!allowEdit"
            >
              <template v-slot:append>
                <q-icon name="event" class="cursor-pointer">
                  <q-popup-proxy transition-show="scale" transition-hide="scale">
                    <q-date v-model="professionalLicenseIssuanceOn" minimal :locale="localeTH">
                      <div class="row items-center justify-end">
                        <q-btn v-close-popup label="ตกลง" color="primary" flat />
                      </div>
                    </q-date>
                  </q-popup-proxy>
                </q-icon>
              </template>
            </q-input>
          </div>
          <div class="text-caption text-grey col-4 q-pa-md">
            วันที่หมดอายุ
            <q-input
              outlined
              v-model="professionalLicenseExpireOnTH"
              readonly
              :disable="!allowEdit"
            >
              <template v-slot:append>
                <q-icon name="event" class="cursor-pointer">
                  <q-popup-proxy transition-show="scale" transition-hide="scale">
                    <q-date v-model="professionalLicenseExpireOn" minimal :locale="localeTH">
                      <div class="row items-center justify-end">
                        <q-btn v-close-popup label="ตกลง" color="primary" flat />
                      </div>
                    </q-date>
                  </q-popup-proxy>
                </q-icon>
              </template>
            </q-input>
          </div>
        </div>

        <q-separator color="secondary" size="3px" spaced="20px" inset />

        <!-- อาชีพ -->
        <div class="row q-px-lg">
          <div class="text-caption text-grey col-4 q-pa-md">
            อาชีพ
            <div class="">
              <q-input outlined v-model="currentCareer" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-4 q-pa-md">
            อายุงาน
            <div class="">
              <q-input outlined v-model="currentCareerYearsExperience" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-4 q-pa-md">
            ตำแหน่ง
            <div class="">
              <q-input outlined v-model="currentCareerPosition" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-5 q-pa-md">
            บริษัท
            <div class="">
              <q-input outlined v-model="currentCareerCompany" :disable="!allowEdit" />
            </div>
          </div>
          <div class="text-caption text-grey col-5 q-pa-md">
            เบอร์โทรบริษัท
            <div class="">
              <q-input outlined v-model="currentCareerCompanyPhoneNumber" :disable="!allowEdit" />
            </div>
          </div>
        </div>
      </q-tab-panel>

      <!-- ไฟล์ -->
      <q-tab-panel name="document">
        <div class="row justify-center">
          <div class="q-mt-md" style="width: 100%; min-width: 300px; max-width: 900px">
            <q-select
              :disable="!allowEdit"
              filled
              v-model="filePictureUpload"
              :options="filePictureCurrent"
              option-label="fileName"
              option-value="id"
              emit-value
              map-options
              label="รูปถ่าย (File.png)"
            >
              <template v-slot:append>
                <q-icon
                  v-if="filePictureUpload !== null"
                  name="close"
                  @click.stop.prevent="filePictureUpload = null"
                  class="cursor-pointer"
                />
              </template>
            </q-select>
          </div>
          <div class="q-mt-md" style="width: 100%; min-width: 300px; max-width: 900px">
            <q-select
              :disable="!allowEdit"
              filled
              v-model="fileAddressUpload"
              :options="fileAddressCurrent"
              option-label="fileName"
              option-value="id"
              emit-value
              map-options
              label="สำเนาทะเบียนบ้าน"
            >
              <template v-slot:append>
                <q-icon
                  v-if="fileAddressUpload !== null"
                  name="close"
                  @click.stop.prevent="fileAddressUpload = null"
                  class="cursor-pointer"
                />
              </template>
            </q-select>
          </div>
          <div class="q-mt-md" style="width: 100%; min-width: 300px; max-width: 900px">
            <q-select
              :disable="!allowEdit"
              filled
              v-model="fileCitizenIdUpload"
              :options="fileCitizenIdCurrent"
              option-label="fileName"
              option-value="id"
              emit-value
              map-options
              label="สำเนาบัตรประจำตัวประชาชน"
            >
              <template v-slot:append>
                <q-icon
                  v-if="fileCitizenIdUpload !== null"
                  name="close"
                  @click.stop.prevent="fileCitizenIdUpload = null"
                  class="cursor-pointer"
                />
              </template>
            </q-select>
          </div>
          <div class="q-mt-md" style="width: 100%; min-width: 300px; max-width: 900px">
            <q-select
              :disable="!allowEdit"
              filled
              v-model="fileProfessionalLicenseUpload"
              :options="fileProfessionalLicenseCurrent"
              option-label="fileName"
              option-value="id"
              emit-value
              map-options
              label="ใบอนุญาตประกอบวิชาชีพ"
            >
              <template v-slot:append>
                <q-icon
                  v-if="fileProfessionalLicenseUpload !== null"
                  name="close"
                  @click.stop.prevent="fileProfessionalLicenseUpload = null"
                  class="cursor-pointer"
                />
              </template>
            </q-select>
          </div>
          <div class="q-mt-md" style="width: 100%; min-width: 300px; max-width: 900px">
            <q-select
              :disable="!allowEdit"
              filled
              v-model="fileOtherUpload"
              multiple
              :options="fileOtherCurrent"
              option-label="fileName"
              option-value="id"
              emit-value
              map-options
              label="เอกสารอื่น ๆ"
            >
              <template v-slot:append>
                <q-icon
                  v-if="fileOtherUpload.length !== 0"
                  name="close"
                  @click.stop.prevent="fileOtherUpload = []"
                  class="cursor-pointer"
                />
              </template>
            </q-select>
          </div>
        </div>
      </q-tab-panel>
    </q-tab-panels>

    <div>
      <q-checkbox
        v-if="allowEditProp"
        v-model="acceptTermOfUse"
        :disable="!allowEdit"
        :label="formLabel.acceptTermOfUse"
      />
    </div>

    <div class="row justify-center q-pa-md">
      <q-btn color="warning" label="บันทึก" @click="saveForm" :disable="applyState === 3" />
      <q-btn
        color="primary"
        class="q-ml-md"
        label="สมัครสอบ"
        @click="applyCandidate"
        :disable="!acceptTermOfUse || applyState === 3"
      />
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      loader: false,
      allowEditData: true,
      isApply: false,
      applyState: 0,
      tab: 'userProfile',
      model: null,
      modelArr: [],
      formOptions: {
        namePrefix: ['นาย', 'นาง', 'นางสาว'],
        sex: ['ชาย', 'หญิง', 'ไม่ระบุ'],
        status: ['โสด', 'แต่งงานแล้ว'],
        bloodGroup: ['A+', 'A-', 'B+', 'B-', 'O+', 'O-', 'AB+', 'AB-'],
        registProvinces: [],
        registDistrict: [],
        registSubDistrict: [],
        currentProvinces: [],
        currentDistrict: [],
        currentSubDistrict: []
      },
      selectRegistProvince: null,
      selectRegistDistrict: null,
      selectRegistSubDistrict: null,
      selectCurrentProvince: null,
      selectCurrentDistrict: null,
      selectCurrentSubDistrict: null,
      formLabel: {
        acceptTermOfUse:
          'ข้าพเจ้าขอรับรองว่า ข้าพเจ้ามีคุณสมบัติครบถ้วนตามประกาศรับสมัคร ข้อความข้างต้นตรงตามความจริงทุกประการ หากไม่เป็นความจริง ให้ถือว่าข้าพเข้า'
      },
      namePrefix: null,
      firstName: null,
      lastName: null,
      dateOfBirth: null,
      dateOfBirthTH: null,
      age: null,
      sex: null,
      status: null,
      bloodGroup: null,
      nationality: null,
      ethnicity: null,
      religion: null,
      phoneNumber: null,
      email: null,
      citizenId: null,
      citizenIdIssuanceAt: null,
      citizenIdIssuanceOn: null,
      citizenIdExpireOn: null,
      governmentOfficialId: null,
      registAddress: null,
      registProvince: null,
      registDistrict: null,
      registSubDistrict: null,
      registZipCode: null,
      currentAddress: null,
      currentProvince: null,
      currentDistrict: null,
      currentSubDistrict: null,
      currentZipCode: null,
      educationalQualification: null,
      educationalField: null,
      educationalUniversity: null,
      educationalLevel: null,
      educationalGraduationDate: null,
      educationalGPAX: null,
      educationalTalent: null,
      currentCareer: null,
      currentCareerYearsExperience: null,
      currentCareerPosition: null,
      currentCareerCompany: null,
      currentCareerCompanyPhoneNumber: null,
      professionalLicenseName: null,
      professionalLicenseId: null,
      professionalLicenseIssuanceOn: null,
      professionalLicenseExpireOn: null,
      acceptTermOfUse: false,
      userProfile: {},
      filePictureUpload: null,
      filePictureCurrent: [],
      fileAddressUpload: null,
      fileAddressCurrent: [],
      fileCitizenIdUpload: null,
      fileCitizenIdCurrent: [],
      fileProfessionalLicenseUpload: null,
      fileProfessionalLicenseCurrent: [],
      fileOtherUpload: [],
      fileOtherCurrent: [],
      citizenIdIssuanceOnTH: null,
      citizenIdExpireOnTH: null,
      educationalGraduationDateTH: null,
      professionalLicenseIssuanceOnTH: null,
      professionalLicenseExpireOnTH: null,
      allowEditProp: true,
      localeTH: {
        days: 'อาทิตย์_จันทร์_อังคาร_พุธ_พฤหัสบดี_ศุกร์_เสาร์'.split('_'),
        daysShort: 'อา._จ._อ._พ._พฤ._ศ._ส.'.split('_'),
        months:
          'มกราคม_กุมภาพันธ์_มีนาคม_เมษายน_พฤษภาคม_มิถุนายน_กรกฎาคม_สิงหาคม_กันยายน_ตุลาคม_พฤศจิกายน_ธันวาคม'.split(
            '_'
          ),
        monthsShort: 'ม.ค_.ก.พ._มี.ค._เม.ย._พ.ค._มิ.ย._ก.ค._ส.ค._ก.ย._ต.ค._พ.ย._ธ.ค.'.split('_'),
        firstDayOfWeek: 1
      }
    }
  },
  computed: {
    allowEdit() {
      return this.allowEditProp && this.allowEditData ? true : false
    },
    applyUrl() {
      return `/apply/${localStorage.getItem('examId')}`
    },
    allFilesToSubmit() {
      const allFiles = [
        this.filePictureUpload,
        this.fileAddressUpload,
        this.fileCitizenIdUpload,
        this.fileProfessionalLicenseUpload,
        ...this.fileOtherUpload
      ]
      const result = allFiles.filter((file) => file !== null)
      return result
    }
  },
  watch: {
    selectRegistProvince(newProvince) {
      this.registProvince = newProvince.name
      this.loader = true
      this.$http
        .get(this.$config.API.getDistrictsOptions(newProvince.id))
        .then((res) => {
          this.formOptions.registDistrict = res.data.items
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loader = false
        })
    },
    selectRegistDistrict(newDistrict) {
      this.registDistrict = newDistrict.name
      this.loader = true
      this.$http
        .get(this.$config.API.getSubDistrictsAndZipCodeOptions(newDistrict.id))
        .then((res) => {
          this.formOptions.registSubDistrict = res.data.items
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loader = false
        })
    },
    selectRegistSubDistrict(newSubDistrict) {
      this.registSubDistrict = newSubDistrict.name
      this.registZipCode = newSubDistrict.zipCode
    },
    selectCurrentProvince(newProvince) {
      this.currentProvince = newProvince.name
      this.loader = true
      this.$http
        .get(this.$config.API.getDistrictsOptions(newProvince.id))
        .then((res) => {
          this.formOptions.currentDistrict = res.data.items
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loader = false
        })
    },
    selectCurrentDistrict(newDistrict) {
      this.currentDistrict = newDistrict.name
      this.loader = true
      this.$http
        .get(this.$config.API.getSubDistrictsAndZipCodeOptions(newDistrict.id))
        .then((res) => {
          this.formOptions.currentSubDistrict = res.data.items
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loader = false
        })
    },
    selectCurrentSubDistrict(newSubDistrict) {
      this.currentSubDistrict = newSubDistrict.name
      this.currentZipCode = newSubDistrict.zipCode
    }
  },
  methods: {
    loadUserFiles() {
      this.loader = true
      this.$http
        .get(this.$config.API.getUserFiles())
        .then((res) => {
          this.filePictureCurrent = []
          this.fileAddressCurrent = []
          this.fileCitizenIdCurrent = []
          this.fileProfessionalLicenseCurrent = []
          this.fileOtherCurrent = []
          res.data.items.fileUpload.forEach((file) => {
            if (file.type === 'picture') this.filePictureCurrent.push(file)
            else if (file.type === 'address') this.fileAddressCurrent.push(file)
            else if (file.type === 'citizenId') this.fileCitizenIdCurrent.push(file)
            else if (file.type === 'professionalLicense')
              this.fileProfessionalLicenseCurrent.push(file)
            else if (file.type === 'other') this.fileOtherCurrent.push(file)
          })
        })
        .catch((err) => console.log(err))
        .finally(() => {
          // this.loader = false
          this.loadOptionFromAPI()
        })
    },
    loadOptionFromAPI() {
      // this.loader = true
      this.$http
        .get(this.$config.API.getProvincesOptions())
        .then((res) => {
          this.formOptions.registProvinces = res.data.items
          this.formOptions.currentProvinces = res.data.items
        })
        .catch((err) => console.log(err))
        .finally(() => {
          // this.loader = false
          this.checkCandidateApply()
        })
    },
    checkCandidateApply() {
      // this.loader = true
      this.$http
        .get(
          this.$config.API.checkCandidateApply(
            this.$route.params.examId,
            this.$keycloak.tokenParsed.sub
          )
        )
        .then((res) => {
          if (res.data.items === 1) {
            this.applyState = 1
            this.loadUserProfile()
          } else {
            this.applyState = 2
            this.loadCandidateData()
            if (res.data.items === 3) {
              this.applyState = 3
              this.isApply = true
              this.allowEditProp = false
            }
          }
        })
        .catch((err) => console.log(err))
        .finally(() => {
          this.loader = false
        })
    },
    formatDateToAPI(value) {
      // return value === null ? null : moment(String(value)).format("YYYY-MM-DDTHH:mm:ss")
    },
    formDataPrep() {
      return {
        namePrefix: this.namePrefix,
        firstName: this.firstName,
        lastName: this.lastName,
        dateOfBirth: this.dateOfBirth,
        age: this.age,
        sex: this.sex,
        status: this.status,
        bloodGroup: this.bloodGroup,
        nationality: this.nationality,
        ethnicity: this.ethnicity,
        religion: this.religion,
        phoneNumber: this.phoneNumber,
        email: this.email,
        citizenId: this.citizenId,
        citizenIdIssuanceAt: this.citizenIdIssuanceAt,
        citizenIdIssuanceOn: this.citizenIdIssuanceOn,
        citizenIdExpireOn: this.citizenIdExpireOn,
        governmentOfficialId: this.governmentOfficialId,
        registAddress: this.registAddress,
        registProvince: this.registProvince,
        registDistrict: this.registDistrict,
        registSubDistrict: this.registSubDistrict,
        registZipCode: this.registZipCode,
        currentAddress: this.currentAddress,
        currentProvince: this.currentProvince,
        currentDistrict: this.currentDistrict,
        currentSubDistrict: this.currentSubDistrict,
        currentZipCode: this.currentZipCode,
        educationalQualification: this.educationalQualification,
        educationalField: this.educationalField,
        educationalUniversity: this.educationalUniversity,
        educationalLevel: this.educationalLevel,
        educationalGraduationDate: this.educationalGraduationDate,
        educationalGPAX: this.educationalGPAX,
        educationalTalent: this.educationalTalent,
        currentCareer: this.currentCareer,
        currentCareerYearsExperience: this.currentCareerYearsExperience,
        currentCareerPosition: this.currentCareerPosition,
        currentCareerCompany: this.currentCareerCompany,
        currentCareerCompanyPhoneNumber: this.currentCareerCompanyPhoneNumber,
        professionalLicenseName: this.professionalLicenseName,
        professionalLicenseId: this.professionalLicenseId,
        professionalLicenseIssuanceOn: this.professionalLicenseIssuanceOn,
        professionalLicenseExpireOn: this.professionalLicenseExpireOn,
        acceptTermOfUse: this.acceptTermOfUse,
        dateOfBirth: this.formatDateToAPI(this.dateOfBirth),
        citizenIdIssuanceOn: this.formatDateToAPI(this.citizenIdIssuanceOn),
        citizenIdExpireOn: this.formatDateToAPI(this.citizenIdExpireOn),
        educationalGraduationDate: this.formatDateToAPI(this.educationalGraduationDate),
        professionalLicenseIssuanceOn: this.formatDateToAPI(this.professionalLicenseIssuanceOn),
        professionalLicenseExpireOn: this.formatDateToAPI(this.professionalLicenseExpireOn),
        filesId: this.allFilesToSubmit
      }
    },
    loadUserProfile() {
      if (!this.isApply) {
        this.loader = true
        this.$http
          .get(this.$config.API.getUserProfile())
          .then((res) => {
            let data = res.data.items
            this.namePrefix = data.namePrefix
            this.firstName = data.firstName
            this.lastName = data.lastName
            this.dateOfBirth = this.dateToISO4(new Date(data.dateOfBirth))
            this.age = data.age
            this.sex = data.sex
            this.status = data.status
            this.bloodGroup = data.bloodGroup
            this.nationality = data.nationality
            this.ethnicity = data.ethnicity
            this.religion = data.religion
            this.phoneNumber = data.phoneNumber
            this.email = data.email
            this.citizenId = data.citizenId
            this.citizenIdIssuanceAt = data.citizenIdIssuanceAt
            this.citizenIdIssuanceOn = this.dateToISO4(new Date(data.citizenIdIssuanceOn))
            this.citizenIdExpireOn = this.dateToISO4(new Date(data.citizenIdExpireOn))
            this.governmentOfficialId = data.governmentOfficialId
          })
          .catch((e) => {
            console.log(e.message)
          })
          .finally(() => {
            this.loader = false
          })
      }
    },
    loadCandidateData() {
      this.loader = true
      this.$http
        .get(
          this.$config.API.getCandidateByUserIdAndExamId(
            this.$route.params.examId,
            this.$keycloak.tokenParsed.sub
          )
        )
        .then((res) => {
          let data = res.data.items
          this.namePrefix = data.namePrefix
          this.firstName = data.firstName
          this.lastName = data.lastName
          this.dateOfBirth = data.dateOfBirth
          this.age = data.age
          this.sex = data.sex
          this.status = data.status
          this.bloodGroup = data.bloodGroup
          this.nationality = data.nationality
          this.ethnicity = data.ethnicity
          this.religion = data.religion
          this.phoneNumber = data.phoneNumber
          this.email = data.email
          this.citizenId = data.citizenId
          this.citizenIdIssuanceAt = data.citizenIdIssuanceAt
          this.citizenIdIssuanceOn = data.citizenIdIssuanceOn
          this.citizenIdExpireOn = data.citizenIdExpireOn
          this.governmentOfficialId = data.governmentOfficialId
          this.registAddress = data.registAddress
          this.registProvince = data.registProvince
          this.registDistrict = data.registDistrict
          this.registSubDistrict = data.registSubDistrict
          this.registZipCode = data.registZipCode
          this.currentAddress = data.currentAddress
          this.currentProvince = data.currentProvince
          this.currentDistrict = data.currentDistrict
          this.currentSubDistrict = data.currentSubDistrict
          this.currentZipCode = data.currentZipCode
          this.educationalQualification = data.educationalQualification
          this.educationalField = data.educationalField
          this.educationalUniversity = data.educationalUniversity
          this.educationalLevel = data.educationalLevel
          this.educationalGraduationDate = data.educationalGraduationDate
          this.educationalGPAX = data.educationalGPAX
          this.educationalTalent = data.educationalTalent
          this.currentCareer = data.currentCareer
          this.currentCareerYearsExperience = data.currentCareerYearsExperience
          this.currentCareerPosition = data.currentCareerPosition
          this.currentCareerCompany = data.currentCareerCompany
          this.currentCareerCompanyPhoneNumber = data.currentCareerCompanyPhoneNumber
          this.professionalLicenseName = data.professionalLicenseName
          this.professionalLicenseId = data.professionalLicenseId
          this.professionalLicenseIssuanceOn = data.professionalLicenseIssuanceOn
          this.professionalLicenseExpireOn = data.professionalLicenseExpireOn
          this.acceptTermOfUse = data.acceptTermOfUse

          this.fileOtherUpload = []
          data.fileUpload.forEach((file) => {
            if (file.type === 'picture') this.filePictureUpload = file.id
            else if (file.type === 'address') this.fileAddressUpload = file.id
            else if (file.type === 'citizenId') this.fileCitizenIdUpload = file.id
            else if (file.type === 'professionalLicense')
              this.fileProfessionalLicenseUpload = file.id
            else if (file.type === 'other') this.fileOtherUpload.push(file.id)
          })
        })
        .catch((err) => {
          console.log(err)
        })
        .finally(() => {
          this.loader = false
        })
    },
    saveForm() {
      if (this.isApply) return
      this.loader = true
      this.$http
        .put(this.$config.API.candidateSaveForm(this.$route.params.examId), this.formDataPrep())
        .then((res) => {
          this.notify('บันทึกข้อมูลสำเร็จ')
        })
        .catch((err) => console.log(err))
        .finally(() => {
          this.loader = false
          this.loadUserFiles()
        })
    },
    applyCandidate() {
      if (!this.acceptTermOfUse) return
      if (this.isApply) return
      if (this.allFilesToSubmit.length < 1) {
        this.notifyError('กรุณาเลือกเอกสารอย่างน้อย 1 รายการ')
        return
      }
      this.loader = true
      this.$http
        .put(this.$config.API.candidateSaveForm(this.$route.params.examId), this.formDataPrep())
        .then((res) => {
          this.$http
            .post(
              this.$config.API.newCandidateApply(this.$route.params.examId),
              this.formDataPrep()
            )
            .then((res) => {
              if (res.data.status === 200) {
                this.notify('สมัครสอบสำเร็จกรุณารอการยืนยัน')
                window.location.reload()
              }
            })
            .catch((err) => {
              console.log(err.message)
            })
            .finally(() => {
              this.loader = false
              this.loadUserFiles()
            })
        })
        .catch((err) => console.log(err))
        .finally(() => {
          this.loader = false
        })
    }
  },
  created() {
    this.loadUserFiles()
    // this.loadUserProfile();
  },
  watch: {
    dateOfBirth(val) {
      if (val !== null) {
        this.dateOfBirthTH = this.date2Thai(new Date(val))
      } else {
        this.dateOfBirthTH = null
      }
    },
    citizenIdIssuanceOn(val) {
      if (val !== null) {
        this.citizenIdIssuanceOnTH = this.date2Thai(new Date(val))
      } else {
        this.citizenIdIssuanceOnTH = null
      }
    },
    citizenIdExpireOn(val) {
      if (val !== null) {
        this.citizenIdExpireOnTH = this.date2Thai(new Date(val))
      } else {
        this.citizenIdExpireOnTH = null
      }
    },
    educationalGraduationDate(val) {
      if (val !== null) {
        this.educationalGraduationDateTH = this.date2Thai(new Date(val))
      } else {
        this.educationalGraduationDateTH = null
      }
    },
    professionalLicenseIssuanceOn(val) {
      if (val !== null) {
        this.professionalLicenseIssuanceOnTH = this.date2Thai(new Date(val))
      } else {
        this.professionalLicenseIssuanceOnTH = null
      }
    },
    professionalLicenseExpireOn(val) {
      if (val !== null) {
        this.professionalLicenseExpireOnTH = this.date2Thai(new Date(val))
      } else {
        this.professionalLicenseExpireOnTH = null
      }
    }
  }
}
</script>

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