<template>
    <div class="map">
        <div id="container"></div>
        <div class="back" @click="back">
            <van-icon name="arrow-left" size="20" color="#FFFFFF" />
        </div>
        <div id="panel" v-show="showMarker"></div>
        <div class="res">
            <div class="add">
                <div>{{name}}</div>
                <div>{{address}}</div>
            </div>
            <div class="btn">
                <van-button size="normal" class="btn-round" type="info" @click="confirmPlace">确定</van-button>
            </div>
        </div>
    </div>
</template>

<script>
import Bus from '@/bus'

export default {
    data () {
        return {
            map: null,
            address: null,
            /**
             * address: 地址
             * lat: 经度
             * lon: 纬度
             * name: 名称
             * province: 省
             * city: 市
             * distinct: 区
             */
            current: null,
            showMarker: false,
            markerList: null,
            lat: '',
            lng: '',
            geocoder: null,
            marker: null,
            name: null,
            point: null,
        }
    },
    mounted () {
        this.initMap();
    },
    methods: {
        initMap () {
            let that = this;
            //创建地图
            // eslint-disable-next-line no-undef
            const map = new AMap.Map('container', {
                resizeEnable: true,
                zoom: 16
            });
            this.map = map;

            // eslint-disable-next-line no-undef
            this.marker = new AMap.Marker({
                map: this.map,
                icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
            });

            //定位
            if (this.address) {
                // eslint-disable-next-line no-undef
                AMap.plugin('AMap.PlaceSearch', () => {
                // eslint-disable-next-line no-undef
                let placeSearch = new AMap.PlaceSearch({
                    pageSize: 1, // 单页显示结果条数
                    pageIndex: 1, // 页码
                    extensions: 'all',
                })
                placeSearch.search(this.address, (status, result) => {
                    if (status === 'complete' && result.poiList.pois && result.poiList.pois.length > 0) {
                            let l = result.poiList.pois[0].location
                            // eslint-disable-next-line no-undef
                            that.marker.setPosition(new AMap.LngLat(l.lnglat.lng, l.lnglat.lat))
                            // eslint-disable-next-line no-undef
                            that.map.setCenter(new AMap.LngLat(l.lnglat.lng, l.lnglat.lat))
                        }
                    })
                })
            }
            else {
                this.locationPosition();
            }

            map.on('click', (e) => {
                that.getAddress(e.lnglat)
                // eslint-disable-next-line no-undef
                that.marker.setPosition(new AMap.LngLat(e.lnglat.lng, e.lnglat.lat))
                // eslint-disable-next-line no-undef
                that.map.setCenter(new AMap.LngLat(e.lnglat.lng, e.lnglat.lat))
            })

            AMap.plugin('AMap.Geocoder', function () {
                // eslint-disable-next-line no-undef
                that.geocoder = new AMap.Geocoder({
                    // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode
                    city: '全国'
                })
            })

            // 默认的图标样式
            const defaultIconStyle = function (index) {
                return 'red-' + (index + 1)
            }
            //鼠标hover时的样式
            const hoverIconStyle = function (index) {
                return 'blue-' + (index + 1)
            }
            //选中时的图标样式
            const selectedIconStyle = function (index) {
                return 'blue-' + (index + 1)
            }

            const vm = this
            // eslint-disable-next-line no-undef
            AMapUI.loadUI(['misc/PositionPicker', 'control/BasicControl', 'misc/MarkerList', 'overlay/SimpleMarker', 'overlay/SimpleInfoWindow'], function (PositionPicker, BasicControl, MarkerList, SimpleMarker, SimpleInfoWindow) {
                map.addControl(new BasicControl.Zoom({
                    position: 'lt',
                }))

                const markerList = new MarkerList({
                    map: map,
                    listContainer: 'panel',
                    //从数据中读取位置, 返回lngLat
                    getPosition: function (item) {
                        return item.location
                    },
                    //数据ID，如果不提供，默认使用数组索引，即index
                    getDataId: function (item, index) {
                        return item.id
                    },
                    getInfoWindow: function (data, context, recycledInfoWindow) {
                        if (recycledInfoWindow) {
                            recycledInfoWindow.setInfoTitle(data.name)
                            recycledInfoWindow.setInfoBody(data.address)
                            return recycledInfoWindow
                        }

                        return new SimpleInfoWindow({
                            infoTitle: data.name,
                            infoBody: data.address,
                            // eslint-disable-next-line no-undef
                            offset: new AMap.Pixel(0, -32)
                        })
                    },
                    //构造marker用的options对象, content和title支持模板，也可以是函数，返回marker实例，或者返回options对象
                    getMarker: function (data, context, recycledMarker) {
                        if (recycledMarker) {
                            recycledMarker.setIconStyle(defaultIconStyle(context.index))
                            return
                        }
                        return new SimpleMarker({
                            iconTheme: 'numv1',
                            containerClassNames: 'my-marker',
                            iconStyle: defaultIconStyle(context.index),
                        })
                    },
                    //构造列表元素，与getMarker类似，可以是函数，返回一个dom元素，或者模板 html string
                    getListElement: function (data, context, recycledListElement) {
                        const label = '' + (context.index + 1)
                        //使用模板创建
                        const innerHTML = MarkerList.utils.template(
                            '<% if(data.photos && data.photos[0]) { %>' +
                            '<div class="poi-imgbox">' +
                            '    <span class="poi-img" style="background-image:url(<%- data.photos[0].url %>)"></span>' +
                            '</div>' +
                            '<% } %>' +
                            '<div class="poi-info-left">' +
                            '    <h3 class="poi-title">' +
                            '        <%- label %>. <%- data.name %>' +
                            '    </h3>' +
                            '    <div class="poi-info">' +
                            '        <p class="poi-addr">地址：<%- data.address %></p>' +
                            '<% if(data.tel ){ %>' +
                            '        <p class="poi-addr">电话：<%- data.tel %></p>' +
                            '<% } %>' +
                            '    </div>' +
                            '</div>' +
                            '<div class="clear"></div>', {
                            data: data,
                            label: label
                        })

                        if (recycledListElement) {
                            recycledListElement.innerHTML = innerHTML
                            return recycledListElement
                        }

                        return '<li class="poibox">' + innerHTML + '</li>'
                    },
                    //列表节点上监听的事件
                    listElementEvents: ['click'],
                    //marker上监听的事件
                    markerEvents: ['click'],
                    //makeSelectedEvents:false,
                    selectedClassNames: 'selected',
                    autoSetFitView: true
                });
                vm.markerList = markerList;

                markerList.on('selectedChanged', function (event, info) {
                    if (info.selected) {
                        const { data, marker } = info.selected
                        if (marker) {
                            //更新为选中样式
                            info.selected.marker.setIconStyle(selectedIconStyle(info.selected.index))
                        }

                        console.log('data: ', data);
                        if (data && data.location) {
                            map.setZoomAndCenter(18, [data.location.lng, data.location.lat])

                            vm.current = {
                                address: data.address,
                                lat: data.location.lat,
                                lon: data.location.lng,
                                info: data,
                            }
                        }
                    }

                    if (info.unSelected && info.unSelected.marker) {
                        //更新为默认样式
                        info.unSelected.marker.setIconStyle(defaultIconStyle(info.unSelected.index))
                    }
                })
            });
        },
        getAddress (lnglat) {
            const vm = this;
            this.geocoder.getAddress(lnglat, (status, result) => {
                if (status === 'complete' && result.info === 'OK') {
                    vm.point = lnglat;
                    const res = result.regeocode;
                    vm.address = res.formattedAddress;
                    vm.name = res.formattedAddress;
                    vm.current = {
                        address: res.formattedAddress,
                        lat: lnglat.lat,
                        lon: lnglat.lng,
                        info: res.addressComponent,
                    }
                }
            })
        },
        locationPosition() {
            if (window.FireJS) {
                const vm = this;
                window.setLocation = function(res) {
                    if (res) {
                        const json = JSON.parse(res);
                        console.log('json: ', json);
                        vm.address = json.address;
                        vm.current = {
                            address: json.address,
                            lat: json.poi.lat,
                            lon: json.poi.lon,
                            info: json
                        };
                        vm.point = json.poi;
                        const position = new AMap.LngLat(json.poi.lon, json.poi.lat);
                        setTimeout(() => {
                            vm.map.setZoomAndCenter(18, position);
                            vm.marker.setPosition(position);
                        }, 2000);
                    }
                }
                window.FireJS.location();
            }
        },
        currentLocation () {
            const vm = this
            // eslint-disable-next-line no-undef
            AMap.plugin('AMap.Geolocation', function () {
                // eslint-disable-next-line no-undef
                var geolocation = new AMap.Geolocation({
                    // 是否使用高精度定位，默认：true
                    enableHighAccuracy: true,
                    // eslint-disable-next-line no-undef
                    buttonOffset: new AMap.Pixel(10, 20),
                    zoomToAccuracy: true,
                    buttonPosition: 'LB'
                })
                vm.map.addControl(geolocation);
                geolocation.getCurrentPosition();
                // eslint-disable-next-line no-undef
                AMap.event.addListener(geolocation, 'complete', onComplete)

                function onComplete (res) {
                    console.log('currentLocation res: ', res);
                    if (res) {
                        vm.current = {
                            address: res.formattedAddress,
                            lat: res.position.lat,
                            lon: res.position.lng,
                            info: res,
                        }
                    }
                }
            })
        },
        confirmPlace() {
            this.locationPosition();
            if (this.address && this.point) {
                Bus.$emit('changePosition', {
                    address: this.address,
                    point: this.point,
                    addressComponents: this.addressComponents
                })
                this.back()
            }
            else {
                this.$toast.fail('定位失败，请检查是否开启定位功能')
            }
        },
        back() {
            this.$router.back()
        }
    }
}
</script>

<style>
.amap-geolocation-con {
    bottom: 100px !important;
}
.amap-zoomcontrol {
    bottom: 0 !important;
}
</style>

<style lang="scss" scoped>
.map {
    width: 100%;
    height: 100vh;
    position: relative;
    #container {
        width: 100%;
        height: 100%;
    }
    .back {
        position: absolute;
        top: 30px;
        left: 8px;
        width: 40px;
        height: 34px;
        display: flex;
        align-items: center;
        justify-content: center;
        background-color: rgba($color: #000000, $alpha: 0.4);
    }
    .res {
        position: absolute;
        bottom: 0;
        left: 0;
        right: 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        background-color: #FFFFFF;
        padding: 10px;
        z-index: 99999;
        .add {
            flex: 1;
            div:first-child {
                font-size: 16px;
                color: #343434;
            }
            div:last-child {
                font-size: 13px;
                color: #888888;
            }
        }
        .btn {
            display: flex;
            align-items: center;
            justify-content: center;
            .btn-round {
                border-radius: 8px;
            }
        }
    }
}
</style>