<template>
    <div class="row">

        <div class=" col-md-3">
            <label>Quận/huyện</label>
            <v-select v-model="selectedDistrictId" :reduce="(option) => option.Id" label="CombinedName" :filterable="false"
                :options="districts" @search="getDistricts">
                <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:wardId'])


const districts = reactive([]);
const wards = reactive([]);

const selectedDistrictId = ref();
const selectedWardId = ref();

async function getDistricts(keyword, loading) {
    if (keyword.length) {
        loading(true);
        await getDistrictsDebounce(loading, keyword);
    }
}

let getDistrictsDebounce = _.debounce(async (loading, keyword) => {
    districts.splice(0, districts.length);
    var districtResult = await locationService.loSug(keyword, 1, 0);
    if (districtResult != null && districtResult.length > 0) {
        districtResult.forEach(district => {
            districts.push(district);
        });
    }
    loading(false);

    loading(false);
}, 500);


watch(selectedDistrictId, async (newDistrictId) => {

    wards.splice(0, wards.length);
    selectedWardId.value = null;
    if (newDistrictId != null && newDistrictId > 0) {
        wards.splice(0, wards.length);
        var wardResult = await locationService.loSug("", 2, newDistrictId);
        if (wardResult != null && wardResult.length > 0) {
            wardResult.forEach(ward => {
                wards.push(ward);
            });
        }
    }

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


</script>