<!-- card ข้อมูลที่อยู่ -->
<template>
  <q-card flat bordered class="col-12 q-px-lg q-py-md q-mt-md">
    <HeaderTop
      v-model:edit="edit"
      header="ข้อมูลที่อยู่"
      icon="mdi-map-marker"
      :save="saveData"
      :addData="true"
      :editOnly="false"
      :cancel="cancelData"
      :changeBtn="changeBtn"
      :editData="step == 2"
      :disable="statusEdit"
    />
    <q-form ref="myform">
      <div class="row col-12 items-center q-col-gutter-x-xs q-col-gutter-y-xs">
        <div class="col-xs-12">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            type="textarea"
            autogrow
            :readonly="!edit"
            :borderless="!edit"
            v-model="addressData.address"
            :rules="[(val) => !!val || `${'กรุณากรอก ที่อยู่ตามทะเบียนบ้าน'}`]"
            :label="`${'ที่อยู่ตามทะเบียนบ้าน'}`"
          />
          <!-- :filled="edit" -->
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3">
          <q-select
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val) => !!val || `${'กรุณาเลือก จังหวัด'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="addressData.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-6 col-sm-3 col-md-3">
          <q-select
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val) => !!val || `${'กรุณาเลือก เขต / อำเภอ'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="addressData.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-6 col-sm-3 col-md-3">
          <q-select
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val) => !!val || `${'กรุณาเลือก ตำบล / แขวง'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="addressData.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-6 col-sm-3 col-md-3">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            v-model="addressData.code"
            :style="!edit ? '' : 'padding:0 12px;'"
            :label="`${'รหัสไปรษณีย์'}`"
          />
        </div>
        <div class="col-12 q-pt-lg"><q-separator /></div>
        <div class="col-xs-12 q-gutter-sm items-center flex q-my-sm">
          <label class="text-bold">ที่อยู่ปัจจุบันตรงกับที่อยู่ตามทะเบียนบ้าน</label>
          <q-radio
            v-model="addressData.same"
            checked-icon="task_alt"
            unchecked-icon="panorama_fish_eye"
            val="1"
            label="ใช่"
            dense
            :disable="!edit"
          />
          <q-radio
            v-model="addressData.same"
            checked-icon="task_alt"
            unchecked-icon="panorama_fish_eye"
            val="0"
            label="ไม่"
            dense
            :disable="!edit"
          />
        </div>

        <div class="col-xs-12" v-if="addressData.same == '0'">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            :outlined="edit"
            dense
            lazy-rules
            type="textarea"
            autogrow
            :readonly="!edit"
            :borderless="!edit"
            v-model="addressData.addressC"
            :rules="[(val) => !!val || `${'กรุณากรอก ที่อยู่ปัจจุบัน'}`]"
            :label="`${'ที่อยู่ปัจจุบัน'}`"
          />
        </div>
        <div class="col-xs-6 col-sm-3 col-md-3" v-if="addressData.same == '0'">
          <q-select
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val) => !!val || `${'กรุณาเลือก จังหวัด'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="addressData.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-6 col-sm-3 col-md-3" v-if="addressData.same == '0'">
          <q-select
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val) => !!val || `${'กรุณาเลือก เขต / อำเภอ'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="addressData.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-6 col-sm-3 col-md-3" v-if="addressData.same == '0'">
          <q-select
            hide-bottom-space
            :class="getClass(edit)"
            :readonly="!edit"
            :borderless="!edit"
            :rules="[(val) => !!val || `${'กรุณาเลือก ตำบล / แขวง'}`]"
            :outlined="edit"
            dense
            lazy-rules
            v-model="addressData.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-6 col-sm-3 col-md-3" v-if="addressData.same == '0'">
          <q-input
            :class="getClass(edit)"
            hide-bottom-space
            dense
            lazy-rules
            readonly
            borderless
            v-model="addressData.codeC"
            :style="!edit ? '' : 'padding:0 12px;'"
            :label="`${'รหัสไปรษณีย์'}`"
          />
        </div>
      </div>
    </q-form>
  </q-card>
  <q-dialog :model-value="modalConsend" persistent>
    <q-card style="min-width: 800px">
      <Conference :ok="consendOk" :close="consenClose" />
    </q-card>
  </q-dialog>
</template>
<script setup lang="ts">
import { ref, onMounted, watch } from 'vue'
import { useCounterMixin } from '@/stores/mixin'

import http from '@/plugins/http'
import config from '@/app.config'
import type { Address, DataOption, zipCodeOption } from '@/modules/01_exam/interface/index/Main'
import { defaultAddress } from '@/modules/01_exam/interface/index/Main'
import HeaderTop from '@/components/top.vue'
import Conference from '@/modules/01_exam/components/Conference.vue'
import { useExamDataStore } from '@/modules/01_exam/store'

const mixin = useCounterMixin()
const store = useExamDataStore()
const { date2Thai, calAge } = mixin

const edit = ref<boolean>(false)
const addressData = ref<Address>(defaultAddress)
const myform = ref<any>()
const codep = ref<string>('')
const codec = ref<string>('')
const modalConsend = ref<boolean>(false)

const provinceOptions = ref<DataOption[]>([])
const districtOptions = ref<DataOption[]>([])
const districtCOptions = ref<DataOption[]>([])
const subdistrictOptions = ref<zipCodeOption[]>([])
const subdistrictCOptions = ref<zipCodeOption[]>([])

const props = defineProps({
  statusEdit: {
    type: Boolean,
    required: true
  },
  notiNoEdit: {
    type: Function,
    default: () => console.log('not function')
  },
  step: {
    type: Number,
    required: true
  }
})

const emit = defineEmits(['update:statusEdit'])

onMounted(() => {
  //   fetchProvince()
  //   fetchDistrict(addressData.value.provinceId, '1')
  //   fetchDistrict(addressData.value.provinceIdC, '2')
})

const saveData = async () => {
  if (store.consend == true) {
    edit.value = false
    emit('update:statusEdit', false)
    await myform.value.validate().then(async (success: boolean) => {
      if (success) {
      } else {
      }
    })
  } else {
    modalConsend.value = true
  }
}

const changeBtn = async () => {
  if (edit.value == true) {
    if (props.statusEdit === true) {
      edit.value = false
      props.notiNoEdit()
    } else {
      emit('update:statusEdit', true)
    }
  } else {
    emit('update:statusEdit', false)
  }
}

const selectProvince = (e: string, name: string) => {
  if (name == '1') {
    addressData.value.districtId = ''
    addressData.value.subdistrictId = ''
    codep.value = ''
  } else {
    addressData.value.districtIdC = ''
    addressData.value.subdistrictIdC = ''
    codec.value = ''
  }

  myform.value.resetValidation()
  fetchDistrict(e, name)
}

const selectDistrict = (e: string, name: string) => {
  if (name == '1') {
    addressData.value.subdistrictId = ''
    codep.value = ''
  } else {
    addressData.value.subdistrictIdC = ''
    codec.value = ''
  }

  myform.value.resetValidation()
  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 : ''
    codep.value = namecode
  } else {
    const findcode = subdistrictCOptions.value.filter((r) => r.id == e)
    const namecode = findcode.length > 0 ? findcode[0].zipCode : ''
    codec.value = namecode
  }

  //   myform.value.resetValidation();
  //   fetchSubDistrict(e, name);
}

const fetchProvince = async () => {
  //   //   loader.value = true;
  //   await http
  //     .get(config.API.province)
  //     .then((res) => {
  //       const data = res.data.result
  //       let option: DataOption[] = []
  //       //   console.log(data);
  //       data.map((r: any) => {
  //         option.push({ id: r.id.toString(), name: r.name.toString() })
  //       })
  //       provinceOptions.value = option
  //     })
  //     .catch((e: any) => {})
  //     .finally(() => {
  //       //   loader.value = false;
  //     })
}

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

const fetchSubDistrict = async (id: string, position: string) => {
  //   //   loader.value = true;
  //   await http
  //     .get(config.API.listSubDistrict(id))
  //     .then((res) => {
  //       const data = res.data.result
  //       let option: zipCodeOption[] = []
  //       //   console.log(res);
  //       data.map((r: any) => {
  //         option.push({
  //           id: r.id.toString(),
  //           name: r.name.toString(),
  //           zipCode: r.zipCode.toString()
  //         })
  //       })
  //       if (position == '1') {
  //         subdistrictOptions.value = option
  //       } else {
  //         subdistrictCOptions.value = option
  //       }
  //     })
  //     .catch((e: any) => {})
  //     .finally(() => {
  //       //   loader.value = false;
  //     })
}

const consenClose = () => {
  modalConsend.value = false
}

const consendOk = () => {
  modalConsend.value = false
  store.consend = true
  saveData()
}

const cancelData = () => {}

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