<!-- card ข้อมูลที่อยู่ -->
<template>
  <HeaderTop
    v-model:edit="edit"
    header="ข้อมูลที่อยู่"
    icon="mdi-map-marker"
    :addData="true"
    :editOnly="false"
    :editData="false"
  />
  <q-form ref="myform">
    <div class="row col-12 items-center q-col-gutter-x-sm q-col-gutter-y-xs">
      <div class="col-xs-12">
        <q-input
          :class="getClass(status == 'register' || status == 'rejectRegister')"
          :outlined="status == 'register' || status == 'rejectRegister'"
          dense
          lazy-rules
          type="textarea"
          autogrow
          :readonly="!(status == 'register' || status == 'rejectRegister')"
          :borderless="!(status == 'register' || status == 'rejectRegister')"
          v-model="defaultAddress.address"
          :rules="[(val) => !!val || `${'กรุณากรอก ที่อยู่ตามทะเบียนบ้าน'}`]"
          :label="`${'ที่อยู่ตามทะเบียนบ้าน'}`"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3">
        <q-select
          :class="getClass(status == 'register' || status == 'rejectRegister')"
          :readonly="!(status == 'register' || status == 'rejectRegister')"
          :borderless="!(status == 'register' || status == 'rejectRegister')"
          :rules="[(val) => !!val || `${'กรุณาเลือก จังหวัด'}`]"
          :outlined="status == 'register' || status == 'rejectRegister'"
          dense
          lazy-rules
          v-model="defaultAddress.provinceId"
          emit-value
          map-options
          option-label="name"
          :options="provinceOptions"
          option-value="id"
          :label="`${'จังหวัด'}`"
          @update:model-value="(value) => selectProvince(value, '1')"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3">
        <q-select
          :class="getClass(status == 'register' || status == 'rejectRegister')"
          :readonly="!(status == 'register' || status == 'rejectRegister')"
          :borderless="!(status == 'register' || status == 'rejectRegister')"
          :rules="[(val) => !!val || `${'กรุณาเลือก เขต / อำเภอ'}`]"
          :outlined="status == 'register' || status == 'rejectRegister'"
          dense
          lazy-rules
          v-model="defaultAddress.districtId"
          emit-value
          map-options
          option-label="name"
          :options="districtOptions"
          option-value="id"
          :label="`${'เขต / อำเภอ'}`"
          @update:model-value="(value) => selectDistrict(value, '1')"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3">
        <q-select
          :class="getClass(status == 'register' || status == 'rejectRegister')"
          :readonly="!(status == 'register' || status == 'rejectRegister')"
          :borderless="!(status == 'register' || status == 'rejectRegister')"
          :rules="[(val) => !!val || `${'กรุณาเลือก ตำบล / แขวง'}`]"
          :outlined="status == 'register' || status == 'rejectRegister'"
          dense
          lazy-rules
          v-model="defaultAddress.subdistrictId"
          emit-value
          map-options
          option-label="name"
          :options="subdistrictOptions"
          option-value="id"
          :label="`${'ตำบล / แขวง'}`"
          @update:model-value="(value) => selectSubDistrict(value, '1')"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3">
        <q-input
          :class="getClass(status == 'register' || status == 'rejectRegister')"
          dense
          lazy-rules
          :readonly="!(status == 'rejectRegister')"
          :borderless="!(status == 'register' || status == 'rejectRegister')"
          :outlined="status == 'register' || status == 'rejectRegister'"
          v-model="defaultAddress.code"
          bottom-slots
          :label="`${'รหัสไปรษณีย์'}`"
        />
      </div>
      <div class="col-xs-12 q-gutter-sm items-center flex q-mb-sm row">
        <div class="text-bold" v-if="$q.screen.gt.xs">
          ที่อยู่ปัจจุบันตรงกับที่อยู่ตามทะเบียนบ้าน
        </div>
        <div class="text-bold col-12 q-pt-sm" v-else>
          ที่อยู่ปัจจุบันตรงกับที่อยู่ตามทะเบียนบ้าน
        </div>
        <q-radio
          v-model="defaultAddress.same"
          checked-icon="task_alt"
          unchecked-icon="panorama_fish_eye"
          val="1"
          label="ใช่"
          dense
          :disable="!(status == 'register' || status == 'rejectRegister')"
        />
        <q-radio
          v-model="defaultAddress.same"
          checked-icon="task_alt"
          unchecked-icon="panorama_fish_eye"
          val="0"
          label="ไม่"
          dense
          :disable="!(status == 'register' || status == 'rejectRegister')"
        />
      </div>

      <div class="col-xs-12" v-if="defaultAddress.same == '0'">
        <q-input
          :class="getClass(status == 'register' || status == 'rejectRegister')"
          :outlined="status == 'register' || status == 'rejectRegister'"
          dense
          lazy-rules
          type="textarea"
          autogrow
          :readonly="!(status == 'register' || status == 'rejectRegister')"
          :borderless="!(status == 'register' || status == 'rejectRegister')"
          v-model="defaultAddress.addressC"
          :rules="[(val) => !!val || `${'กรุณากรอก ที่อยู่ปัจจุบัน'}`]"
          :label="`${'ที่อยู่ปัจจุบัน'}`"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3" v-if="defaultAddress.same == '0'">
        <q-select
          :class="getClass(status == 'register' || status == 'rejectRegister')"
          :readonly="!(status == 'register' || status == 'rejectRegister')"
          :borderless="!(status == 'register' || status == 'rejectRegister')"
          :rules="[(val) => !!val || `${'กรุณาเลือก จังหวัด'}`]"
          :outlined="status == 'register' || status == 'rejectRegister'"
          dense
          lazy-rules
          v-model="defaultAddress.provinceIdC"
          emit-value
          map-options
          option-label="name"
          :options="provinceOptions"
          option-value="id"
          :label="`${'จังหวัด'}`"
          @update:model-value="(value) => selectProvince(value, '2')"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3" v-if="defaultAddress.same == '0'">
        <q-select
          :class="getClass(status == 'register' || status == 'rejectRegister')"
          :readonly="!(status == 'register' || status == 'rejectRegister')"
          :borderless="!(status == 'register' || status == 'rejectRegister')"
          :rules="[(val) => !!val || `${'กรุณาเลือก เขต / อำเภอ'}`]"
          :outlined="status == 'register' || status == 'rejectRegister'"
          dense
          lazy-rules
          v-model="defaultAddress.districtIdC"
          emit-value
          map-options
          option-label="name"
          :options="districtCOptions"
          option-value="id"
          :label="`${'เขต / อำเภอ'}`"
          @update:model-value="(value) => selectDistrict(value, '2')"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3" v-if="defaultAddress.same == '0'">
        <q-select
          :class="getClass(status == 'register' || status == 'rejectRegister')"
          :readonly="!(status == 'register' || status == 'rejectRegister')"
          :borderless="!(status == 'register' || status == 'rejectRegister')"
          :rules="[(val) => !!val || `${'กรุณาเลือก ตำบล / แขวง'}`]"
          :outlined="status == 'register' || status == 'rejectRegister'"
          dense
          lazy-rules
          v-model="defaultAddress.subdistrictIdC"
          emit-value
          map-options
          option-label="name"
          :options="subdistrictCOptions"
          option-value="id"
          :label="`${'ตำบล / แขวง'}`"
          @update:model-value="(value) => selectSubDistrict(value, '2')"
        />
      </div>
      <div class="col-xs-12 col-sm-3 col-md-3" v-if="defaultAddress.same == '0'">
        <q-input
          :class="getClass(status == 'register' || status == 'rejectRegister')"
          dense
          lazy-rules
          bottom-slots
          :readonly="!(status == 'rejectRegister')"
          :borderless="!(status == 'register' || status == 'rejectRegister')"
          :outlined="status == 'register' || status == 'rejectRegister'"
          v-model="defaultAddress.codeC"
          :label="`${'รหัสไปรษณีย์'}`"
        />
      </div>
    </div>
  </q-form>
</template>
<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import type { PropType } from 'vue'
import http from '@/plugins/http'
import config from '@/app.config'
import { useCounterMixin } from '@/stores/mixin'
import { useDataStore } from '@/stores/data'
import { useRoute } from 'vue-router'
import { useQuasar } from 'quasar'
import type { Address, DataOption } from '@/modules/01_exam/interface/index/Main'
import { defaultAddress, changeData } from '@/modules/01_exam/interface/index/Main'
import HeaderTop from '@/components/top.vue'

const props = defineProps({
  provinceOptions: {
    type: Array as PropType<DataOption[]>,
    required: true
  },
  status: {
    type: String,
    required: true
  },
  form: {
    type: Object,
    required: true
  }
})
const emit = defineEmits(['update:form'])

const $q = useQuasar()
const dataStore = useDataStore()
const { loaderPage } = dataStore
const mixin = useCounterMixin()
const { messageError } = mixin
const route = useRoute()
const examId = ref<string>(route.params.id.toString())
const positionId = ref<string>(route.params.positionId.toString())
const edit = ref<boolean>(true)
const myform = ref<any>({})
const districtOptions = ref<DataOption[]>([])
const districtCOptions = ref<DataOption[]>([])
const subdistrictOptions = ref<DataOption[]>([])
const subdistrictCOptions = ref<DataOption[]>([])

watch(myform, async (count: any, prevCount: any) => {
  emit('update:form', count)
})

watch(defaultAddress, async (count: Address, prevCount: Address) => {
  await changeData('address', count)
})

onMounted(async () => {
  await fetchData()
  if (defaultAddress.value.provinceId != null)
    await fetchDistrict(defaultAddress.value.provinceId, '1')
  if (defaultAddress.value.provinceIdC != null)
    await fetchDistrict(defaultAddress.value.provinceIdC, '2')
  if (defaultAddress.value.districtId != null)
    await fetchSubDistrict(defaultAddress.value.districtId, '1')
  if (defaultAddress.value.districtIdC != null)
    await fetchSubDistrict(defaultAddress.value.districtIdC, '2')
})

const fetchData = async () => {
  loaderPage(true)
  await http
    .get(config.API.candidateAddress(examId.value, positionId.value))
    .then((res) => {
      const data = res.data.result
      if (data != null) {
        defaultAddress.value.address = data.registAddress
        defaultAddress.value.addressC = data.currentAddress
        defaultAddress.value.provinceId = data.registProvinceId
        defaultAddress.value.provinceIdC = data.currentProvinceId
        defaultAddress.value.districtId = data.registDistrictId
        defaultAddress.value.districtIdC = data.currentDistrictId
        defaultAddress.value.subdistrictId = data.registSubDistrictId
        defaultAddress.value.subdistrictIdC = data.currentSubDistrictId
        defaultAddress.value.code = data.registZipCode
        defaultAddress.value.codeC = data.currentZipCode
        defaultAddress.value.same =
          data.registSame == true ? '1' : data.registSame == false ? '0' : null
      }
    })
    .catch((e) => {
      messageError($q, e)
    })
    .finally(() => {
      loaderPage(false)
    })
}

const selectProvince = async (e: string, name: string) => {
  if (name == '1') {
    defaultAddress.value.districtId = ''
    defaultAddress.value.subdistrictId = ''
    defaultAddress.value.code = null
  } else {
    defaultAddress.value.districtIdC = ''
    defaultAddress.value.subdistrictIdC = ''
    defaultAddress.value.codeC = null
  }
  myform.value.resetValidation()
  await fetchDistrict(e, name)
}

const selectDistrict = async (e: string, name: string) => {
  if (name == '1') {
    defaultAddress.value.subdistrictId = ''
    defaultAddress.value.code = null
  } else {
    defaultAddress.value.subdistrictIdC = ''
    defaultAddress.value.codeC = null
  }
  myform.value.resetValidation()
  await fetchSubDistrict(e, name)
}

const selectSubDistrict = (e: string, name: string) => {
  if (name == '1') {
    const findcode = subdistrictOptions.value.filter((r) => r.id == e)
    const namecode = findcode.length > 0 ? findcode[0].zipCode : null
    defaultAddress.value.code = namecode
  } else {
    const findcode = subdistrictCOptions.value.filter((r) => r.id == e)
    const namecode = findcode.length > 0 ? findcode[0].zipCode : null
    defaultAddress.value.codeC = namecode
  }
}

const fetchDistrict = async (id: string, position: string) => {
  loaderPage(true)
  await http
    .get(config.API.listDistrict(id))
    .then((res) => {
      const data = res.data.result
      let option: DataOption[] = []
      data.map((r: DataOption) => {
        option.push({ id: r.id.toString(), name: r.name.toString() })
      })
      if (position == '1') {
        districtOptions.value = option
      } else {
        districtCOptions.value = option
      }
    })
    .catch((e) => {
      messageError($q, e)
    })
    .finally(() => {
      loaderPage(false)
    })
}

const fetchSubDistrict = async (id: string, position: string) => {
  loaderPage(true)
  await http
    .get(config.API.listSubDistrict(id))
    .then((res) => {
      const data = res.data.result
      let option: DataOption[] = []
      data.map((r: DataOption) => {
        option.push({
          id: r.id.toString(),
          name: r.name.toString(),
          zipCode: r.zipCode != null ? r.zipCode : null
        })
      })
      if (position == '1') {
        subdistrictOptions.value = option
      } else {
        subdistrictCOptions.value = option
      }
    })
    .catch((e) => {
      messageError($q, e)
    })
    .finally(() => {
      loaderPage(false)
    })
}

const getClass = (val: boolean) => {
  return {
    'full-width inputgreen cursor-pointer': val,
    'full-width cursor-pointer': !val
  }
}
</script>
