<template>
    <div class="row">
        <div class="col-md-6">
            <label>Địa chỉ</label>
            <v-select v-model="selectedPlaceId" :reduce="(option) => option.Id" label="Name" :filterable="false"
                :options="places" @search="getPlaces">
                <template #no-options="{ search, searching, loading }">
                    Gõ từ khóa để tìm....
                </template>
            </v-select>
        </div>
        <div class=" col-md-3">
            <label>Quận/huyện</label>
            <v-select v-model="selectedDistrictId" :reduce="(option) => option.Id" label="Name" :options="districts">
                <template #no-options="{ search, searching, loading }">
                    Gõ từ khóa để tìm....
                </template>
            </v-select>
        </div>
        <div class=" col-md-3">
            <label>Phường/xã</label>
            <v-select v-model="selectedWardId" :reduce="(option) => option.Id" label="Name" :options="wards">
                <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, watch } from 'vue';
import _ from 'lodash';
import locationService from "@/services/locationService";
//#endregion


const emit = defineEmits(['update:placeId', 'update:wardId'])


const places = reactive([]);
const selectedPlaceId = ref();

async function getPlaces(keyword, loading) {
    if (keyword.length) {
        loading(true);
        await getPlacesDebounce(loading, keyword);
    }
}

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

    loading(false);
}, 500);

watch(selectedPlaceId, async (newPlaceId) => {
    //Lấy thông tin chi tiết của place
    if (newPlaceId != null && newPlaceId.length > 0) {
        var placeDetailResult = await locationService.placeDetail(newPlaceId);
        console.log(placeDetailResult);
    }

    emit('update:placeId', newPlaceId);
})




</script>