<template>
    <el-select filterable remote v-model="keywords" reserve-keyword :placeholder="placeholder" :remote-method="remoteMethod" @change="searchKeywords" :loading="loading" clearable style="width: 440px">
        <el-option v-for="item in options" :key="item.id" :label="item.district + item.address.toString()" :value="item.id" />
    </el-select>
</template>
<script setup lang="ts">
import { debounce } from 'lodash';
import AMapLoader from '@amap/amap-jsapi-loader';
const props = defineProps<{
    modelValue: any;
    placeholder?: string;
}>();
const emit = defineEmits<{
    (e: 'update:modelValue', value: string): void;
}>();
import { httpRequests } from '@/utils/httpRequests';
const keywords = ref<string>('');
const options = ref<any[]>([]);
const loading = ref<boolean>(false);
const remoteMethod = debounce((keywords: string) => {
    if (!keywords) {
        return;
    }
    loading.value = true;
    let autoComplete = new mapData.AMap.Autocomplete();
    autoComplete.search(keywords, function (status: string, result: any) {
        console.log(result.tips);
        if (!result.tips?.length) {
            options.value = [];
            loading.value = false;
            return;
        }
        const tips = result.tips?.filter((item: any) => item.id);
        options.value = [...tips];
        loading.value = false;
    });
}, 1000);
const mapData: any = {
    AMap: null,
    map: null,
    marker: null,
    circle: null
};
const initMap = (positions: any[] = []) => {
    window._AMapSecurityConfig = {
        securityJsCode: '059c519d3546bc48566ecca0b38f22ae',
    };
    AMapLoader.load({
        key: '26b919a68880ad60637f5cabd6c94a76', // 申请好的Web端开发者Key，首次调用 load 时必填
        version: '2.0', // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: [
            'AMap.PlaceSearch',
            'AMap.AutoComplete'
        ] // 需要使用的的插件列表，如比例尺'AMap.Scale'等
    })
        .then((AMap) => {
            mapData.AMap = AMap;
        })
        .catch((e) => {
            console.log(e);
        });
};
const searchKeywords = (val: string) => {
    console.log(val);
    const item = options.value.find(i => i.id === val);
    if (item) {
        emit('update:modelValue', item);
    } else {
        emit('update:modelValue', '');
    }
};
watch(() => props.modelValue, (val) => {
    if (val && val.name) {
        keywords.value = (val?.name || '') + (val?.district || '');
    } else {
        keywords.value = '';
    }
}, { immediate: true });
onMounted(() => {
    initMap();
});
</script>
