<template>
    <div id="container">
        <lj-win-common ref="baseWin" title="定位服务">
            <div slot="header_right" style="position: relative;top: 8px;left: -20px;">
                <van-button type="info" size="small" @click="confirmLocation">确认</van-button>
            </div>
            <template slot="body">
                <div id="aMap" class="aMap">
                    <div class="aMapList">
                        <van-list
                            v-model="loading"
                            :error.sync="error"
                            error-text="请求失败，点击重新加载"
                            :finished="finished"
                            finished-text="没有更多了"
                            offset="0"
                            :immediate-check="false"
                            @load="searchNearbyLocations"
                        >
                            <van-cell v-for="(item,index) in nearbyLocations" :key="index" :title="item.name" center @click="selectLocation(item)">
                                <template #label>
                                    <span v-if="item.distance > 100">{{ item.distance }}米</span>
                                    <span v-else>100米内</span>
                                    <span>|</span>
                                    <span>{{ item.address }}</span>
                                </template>
                                <template #right-icon>
                                    <i class="iconfont icon-check" style="color: #07c160;" v-if="item.checked"></i>
                                </template>
                            </van-cell>
                        </van-list>
                    </div>
                </div>
            </template>
        </lj-win-common>
    </div>
</template>

<script>
    import ljWinCommon from 'components/lj-win-common'
    export default {
        components: {
            ljWinCommon,
        },
        data() {
            return {
                appBarHeight: 0,
                loading: false, // list加载状态
                finished: false, // list全部加载完状态
                error: false, // list错误状态
                pageSize: 10,
                pageIndex: 1,
                map: api.require('aMap'),
                currentLocation: null,
                nearbyLocations: []
            }
        },
        created() {
            let headerSubHeight = 0;
            let appBarHeight = 0;
            if (document.getElementById("headerSub")) {
                headerSubHeight = document.getElementById("headerSub").offsetHeight;
            }
            appBarHeight = $lj.getAppBarHeight();
            this.appBarHeight = appBarHeight + headerSubHeight;
        },
        beforeDestroy() {
            this.destroyMap();
        },
        mounted() {
            // 调用权限请求函数
            this.requestLocationPermission();
        },
        methods: {
            requestLocationPermission() {
                var aMap = api.require('aMap');
                aMap.updateMapViewPrivacy({
                    privacyAgree:'didAgree',
                    privacyShow:'didShow',
                    containStatus:'didContain'
                });
        
                aMap.updateSearchPrivacy({
                    privacyAgree:'didAgree',
                    privacyShow:'didShow',
                    containStatus:'didContain'
                });

                this.initMap();
            },
            initMap() {
                // 初始化地图
                let self = this;

                this.map.open({
                    rect: {
                        x: 0,
                        y: self.appBarHeight,
                        w: api.winWidth,
                        h: api.winHeight - self.appBarHeight - 400
                    },
                    zoomLevel: 18,
                    fixedOn: api.frameName,
                    fixed: true
                }, function(ret, err) {
                    if (ret.status) {
                        console.log('地图初始化成功');
                        self.initValue();
                        // 获取当前位置
                        self.getCurrentLocation();
                    } else {
                        console.error('地图初始化失败：', JSON.stringify(err),JSON.stringify(ret));
                    }
                });
            },
            initValue() {
                let self = this;
                // 是否显示用户
                this.map.showUserLocation({
                    isShow: true,
                    showsAccuracyRing: false,
                    showsHeadingIndicator: false
                });
            },
            handleChangeView(location) {
                this.nearbyLocations = [];
                this.getNameFromCoords(location);
                // 添加当前位置到附近位置列表
                this.nearbyLocations.push(location);
                // 添加标记到地图
                this.addAnnotation(location);
                // 获取附近兴趣点
                this.searchNearbyLocations(location);
            },
            getCurrentLocation() {
                let self = this;

                this.map.getLocation(function(ret, err) {
                    if (ret.status) {
                        console.log('定位成功', JSON.stringify(ret));
                        self.map.setCenter({
                            coords: {
                                lon: ret.lon,
                                lat: ret.lat,
                            },
                            animation: true
                        });

                        // 添加监听器(视角改变事件) 
                        self.map.addEventListener({
                            name: 'viewChange'
                        }, (ret) => {
                            if (ret.status) {
                                self.currentLocation = {
                                    name: '当前位置',
                                    lon: ret.lon,
                                    lat: ret.lat,
                                    distance: 0,
                                    checked: true
                                };

                                self.handleChangeView(self.currentLocation);
                            }
                        });
                    } else {
                        console.error('定位失败', err);
                    }
                });
            },
            searchNearbyLocations(location) {
                let self = this;
                this.map.searchNearby({
                    keyword: "",
                    lon: location.lon,
                    lat: location.lat,
                    offset: this.pageSize,
                    page: this.pageIndex,
                    radius: 3000
                }, function(ret, err) {
                    if (ret.status) {
                        console.log('附近兴趣点搜索成功', JSON.stringify(ret));

                        if (self.pageIndex == 1 && !ret.pois.length) {
                            self.loading = false;
                            self.error = false;
                            return false;
                        } else if (ret.pois.length < self.pageSize) {
                            self.loading = false;
                            self.error = false;
                            /**全部内容加载完成 */
                            self.finished = true;
                        } else {
                            self.pageIndex++;
                            self.loading = false;
                            self.error = false;
                        }

                        // 处理搜索结果
                        self.nearbyLocations = self.nearbyLocations.concat(ret.pois.map(function(poi) {
                            return {
                                name: poi.name,
                                lon: poi.lon,
                                lat: poi.lat,
                                distance: poi.distance,
                                address: poi.address
                            };
                        }));
                    } else {
                        self.finished = false;
                        self.loading = false;
                        self.error = true;
                        console.error('附近兴趣点搜索失败', err);
                    }
                });
            },
            addAnnotation(location) {
                this.map.addAnnotations({
                    annotations: [{
                        id: 'currentLocation',
                        lon: location.lon,
                        lat: location.lat,
                        w: 40,
                        h: 40,
                        icons: ['widget://assets/image/location.png'],
                        locked: true,
                        title: '当前位置',
                        subTitle: '当前位置'
                    }]
                }, function(ret, err) {
                    if (ret.status) {
                        console.log('标注添加成功');
                    } else {
                        console.error('标注添加失败：', err);
                    }
                });
            },
            selectLocation(location) {
                this.$set(this.currentLocation,"checked",false);
                this.currentLocation = location;
                this.$set(this.currentLocation,"checked",true);
                // this.map.setCenter({
                //     coords: {
                //         lon: location.lon,
                //         lat: location.lat,
                //     },
                //     animation: true
                // });
                // 可以选择性添加或更新选中标记的逻辑
                this.addAnnotation(location);
            },
            confirmLocation() {
                if (this.currentLocation) {
                    console.log('确认选择的位置信息：', this.currentLocation);
                    // 在这里可以处理确认选中位置的逻辑，比如提交数据或者关闭地图界面等
                    $lj.sendEvent("aMap_select",{location: this.currentLocation});
                    $lj.closeWin();
                } else {
                    console.warn('请先选择一个位置');
                    // 可以添加用户提示或者交互逻辑
                    $lj.toast("请先选择一个位置");
                }
            },
            destroyMap() {
                // 销毁地图对象
                if (this.map) {
                    this.map.close();
                    console.log('地图关闭成功');
                }
            },
            /**
             * 根据经纬度查找地址信息
             * @param {*} lon 
             * @param {*} lat 
             */
            getNameFromCoords(location) {
                let self = this;
                this.map.getNameFromCoords({
                    lon: location.lon,
                    lat: location.lat
                }, function(ret, err) {
                    if (ret.status) {
                        console.log("getNameFromCoords ret:>>>",JSON.stringify(ret))
                        self.$set(location,"address",ret.address);
                    } else {
                        console.log("getNameFromCoords err:>>>",JSON.stringify(err))
                    }
                })
            }
        },
        computed: {
            
        },
    }
</script>

<style scoped lang="less">
    .aMap {
        width: 100%;
        height: 400px;
        display: block;

        border-top-left-radius: 16px;
        border-top-right-radius: 16px;
        background-color: #fff;

        position: fixed;
        bottom: 0;

        z-index: 999;

        overflow: hidden;
        
        .aMapList {
            height: 100%;
            width: 100%;
            overflow-y: auto;
        }
    }
</style>