<template>
    <div class="row">
        <div class="col-md-12">
            <label>Phường/xã - Quận/huyện - Tỉnh/Thành phố</label>
            <v-select v-model="selectedWardId" :reduce="(option) => option.Id" label="Name" :filterable="false"
                :options="wards" @search="getWards">
                <template #no-options="{ search, searching, loading }">
                    Gõ từ khóa để tìm....
                </template>
            </v-select>
        </div>

    </div>
</template>
<script setup>
//#region Imports
import { ref, reactive, onMounted, watch } from 'vue';
import _ from 'lodash';
import locationService from "@/services/locationService";
//#endregion



const props = defineProps({
    wardId: String

})
const emit = defineEmits(['update:cityId', 'update:districtId', 'update:wardId'])


const wards = reactive([]);
const selectedWardId = ref();

async function getWards(keyword, loading) {
    if (keyword.length) {
        loading(true);
        await loSugWards(loading, keyword);
    }
}

let loSugWards = _.debounce(async (loading, keyword) => {
    wards.splice(0, wards.length);
    var wardResult = await locationService.addressAutocomplete(keyword);
    console.log(wardResult);
    if (wardResult.Result === 1) {
        var items = wardResult.Items;
        if (items != null && items.length > 0) {
            items.forEach(ward => {
                wards.push(ward);
            });
        }
    }

    loading(false);
}, 500);

watch(selectedWardId, async (newWardId) => {
    if (newWardId != props.wardId) {
        emit('update:wardId', newWardId);
    }

})




</script>