<template>
    <div class="qqmap-box" :style="{ height }">
        <h-search  
            type="map" 
            v-model="value"
            placeholderAlign="center" 
            placeholder="搜索地点"
            @click="handleSearch"
        />
        <div id="map-content" class="hanzo-map-content"></div>
        <ul class="searchRes">
            <li class="searchRes-item" v-for="( item, index ) in searchList" :key="item.id" @click="handleClick(item, index)">
                <p class="name">{{ item.name }}</p>
                <p class="address">{{ item.address }}</p>
                <span class="item-active" v-if="active === index">
                    <h-icon type="success" size="14" color="#07c160"/>
                </span>
            </li>
        </ul>
    </div>
</template>
<script>
import { loadJs } from '../../common/utils/index';
import hSearch from '../search/index.vue';
import hIcon from '../icon/index.vue';
const MAPKEY = 'B3EBZ-QYULJ-N5EFH-FVOSK-CVXET-3VBQF'; // key
let count = 0; // 加载地图重试次数
const DEFAULTGPS = { // moren jingweidu 
    latitude:28.208,
    longitude:112.885
};
export default {
    name: 'h-qq-map',
    components: {
        hSearch,
        hIcon
    },
    mounted() {
        this.createMap();
        this.geolocationInit();
    },
    props: {
        // 必填key
        mapKey: {
            type: String,
            default: ""
        },
        //纬度 parseFloat 28.223806
        latitude: {
            type: Number|String,
            default: 0,
        },
        //经度 parseFloat 112.9207
        longitude: {
            type: Number|String,
            default: 0,
        },
        //缩放18
        zoom: {
            type: Number,
            default: 14
        },
        height: [String, Number]
    },
    data() {
        return {
            qqMap: null,
            MAPS: null,
            value: '',
            markersArray:[],
            searchList: [],
            active: -1
        }
    },
    methods: {
        /**
         * 创建地图
         */
        createMap(latitude,longitude) {
            if ( count > 3 ) {
                console.log( '创建地图失败，尝试次数：', count );
                return;
            }
            if ( this.qqMap ) {
                const lat = latitude || DEFAULTGPS.latitude;
                const long = longitude || DEFAULTGPS.longitude;
                let timer = setInterval( () => {
                    if ( this.qqMap.LatLng ) {
                        clearInterval( timer );
                        let center = new this.qqMap.LatLng(parseFloat(lat), parseFloat(long));
                        //地图初始化
                        this.MAPS = new this.qqMap.Map("map-content", {
                            center: center,
                            zoom: this.zoom,
                            zoomControl: false, // 放大缩小控件
                            mapTypeControl: false, // 地图类型控件
                        });
                        this.createMarker(center);
                    }
                }, 200 );

            } else {
                let that = this;
                this.loadMap()
                    .then( () => {
                        count++;
                        that.qqMap = qq.maps;
                        that.createMap();
                    } )
                    .catch( (err) => {
                        console.log('err', err);
                    } )
            }
        },
        createMarker(position){
            //创建一个Marker
            const marker = new this.qqMap.Marker({
                //设置Marker的位置坐标
                position: position,
                //设置显示Marker的地图
                map: this.MAPS
            });
            marker.setAnimation(this.qqMap.MarkerAnimation.DOWN);
            let size = new this.qqMap.Size(28, 28);
            marker.setIcon( new this.qqMap.MarkerImage("https://front-xps-cdn.xsyx.xyz/2019/08/20/744202685.png", null,null,null, size) );
            this.markersArray.push(marker);

            this.handleSearch();
        }, 
        /**
         * 加载地图
         */
        async loadMap() {
            const url = '//map.qq.com/api/js?v=2.exp&libraries=convertor&callback=initTheMap&key='+MAPKEY;
            window.initTheMap = function() {
                console.log('QQmap加载完成!');
            }
            return new Promise( ( resolve, reject ) => {
                window.initTheMap = function() {
                    resolve(qq.maps);
                }
                loadJs( url )
                .then( () => {
                    resolve();
                } )
                .catch( ( err ) => { 
                    reject();
                 } )
            } )
        },
        /**
         * 腾讯h5定位库
         */
        async geolocationInit() {
            loadJs('https://3gimg.qq.com/lightmap/components/geolocation/geolocation.min.js').then(() => {
                console.log('地图基础库加载完成');
            }).catch(e => {
                console.log('地图基础库加载失败', e)
            })
        },
        // 地图搜索
        handleSearch() {
            let that = this;
            let searchService = new this.qqMap.SearchService({
                complete : function(results){
                    if ( results.type === 'POI_LIST' ) {
                        that.searchList = results.detail.pois
                    } else {
                        that.searchList = [];
                    }
                }
            });
            searchService.search( this.value ||"麓谷" );
            this.active = -1;
        },
        handleClick(item, index) {
            let latLng = item.latLng;
            this.MAPS.panTo(new this.qqMap.LatLng(latLng.lat, latLng.lng));
            let center = new this.qqMap.LatLng(latLng.lat, latLng.lng);
            for (let i in this.markersArray) {
                this.markersArray[i].setMap(null);
            }
            this.markersArray = [];
            this.createMarker(center);
            this.active = index;
            this.$emit( 'click', item );
        }
    }
}
</script>
<style lang="less" scoped>
@import './index.less';
</style>