<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"
    /> -->
    <HeaderTop
      v-model:edit="edit"
      header="ข้อมูลที่อยู่ปัจจุบัน"
      icon="mdi-map-marker"
      :save="saveData"
      :history="true"
    />
    <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)"
          />
        </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)"
          />
        </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)"
          />
        </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="codep"
            :style="!edit ? '' : 'padding:0 12px;'"
            :label="`${'รหัสไปรษณีย์'}`"
          />
        </div>
      </div>
    </q-form>
  </q-card>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'

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'

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

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

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

onMounted(() => {
  //   fetchProvince()
  //   fetchDistrict(addressData.value.provinceId)
})

const saveData = async () => {
  await myform.value.validate().then(async (success: boolean) => {
    if (success) {
    } else {
    }
  })
}

const selectProvince = (e: string) => {
  addressData.value.districtId = ''
  addressData.value.subdistrictId = ''
  codep.value = ''

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

const selectDistrict = (e: string) => {
  addressData.value.subdistrictId = ''
  codep.value = ''

  myform.value.resetValidation()
  fetchSubDistrict(e)
}

const selectSubDistrict = (e: string) => {
  const findcode = subdistrictOptions.value.filter((r) => r.id == e)
  const namecode = findcode.length > 0 ? findcode[0].zipCode : ''
  codep.value = namecode
}

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) => {
  //   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() })
      })
      districtOptions.value = option
    })
    .catch((e: any) => {})
    .finally(() => {
      //   loader.value = false;
    })
}

const fetchSubDistrict = async (id: 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()
        })
      })
      subdistrictOptions.value = option
    })
    .catch((e: any) => {})
    .finally(() => {
      //   loader.value = false;
    })
}
</script>
