<template>
    <div id="fullscreen" class="fullscreen">
        <div :id="name" class="map">
        </div>
        <div :id="name+'_popup'" class="ol-popup" >
            <a href="#" :id="name+'_popup_closer'" class="ol-popup-closer"></a>
            <div :id="name+'_popup_content'"></div>
        </div>
    </div>
</template>
<script>
    import 'ol/ol.css';
    import Map from 'ol/Map';
    import { defaults as defaultControls} from 'ol/control';
    import {defaults as defaultInteractions} from 'ol/interaction';
    import {Fill, Icon, Stroke, Style} from 'ol/style';
    import Overlay from 'ol/Overlay';
    import View from 'ol/View';
    import map from './map';
    import gps from './utils/GPS';
    import router from "../Common/router";
    import Drag from "./interactions/Drag";

    export default {
        mixins: [router,map],//监听外部框架的大小改变事件
        comments:{
            Map:Map
        },data(){
            return {
                // baseURL:"http://service.new0.com.cn/",
                view:null,
                map:null,
                location:[117,25],
                closer:null,
                content:null,
                overlay:null,
                name:"map",
                options:null
            }
        },
        watch:{
        },
        computed: {
        },
        created() {
            this.options = this.getParams();
            if (this.options.name) {
                this.name = this.options.name;
            }
        },
       async mounted() {
            // if(this.baseURL==null)
            //     this.baseURL=this.$store.state.api.axios.baseURL;
           await this.$jsonp(this.$core.replaceQueryString("https://apis.map.qq.com/ws/location/v1/ip"),
                {key:"4LBBZ-R626U-GZ6V5-BB5ZC-7BG6K-VOBTI",output:"jsonp"}).then( //SW2BZ-FIZLW-LFMRT-RWW4K-5YDF7-6AFCZ
                async(res)=>{
                    //{"status":0,"message":"Success","request_id":"bcb39d97-9595-43d7-bc92-5ed4917a9581",
                    // "result":{"ip":"110.82.117.155","location":{"lat":25.09839,"lng":117.03736},
                    // "ad_info":{"nation":"中国","province":"福建省","city":"龙岩市","district":"新罗区","adcode":350802}}}
                    // this.location=gps.gcj_encrypt([res.result.location.lng,res.result.location.lat]);
                    // this.location=[res.result.location.lng,res.result.location.lat];
                    if(res.result) {
                        // this.location = gps.gcj_decrypt([res.result.location.lng, res.result.location.lat]);//腾讯给的是到区政府的地理位置,进行解码即可
                        this.location =gps.gcj_decrypt([res.result.location.lng, res.result.location.lat]);//腾讯给的是到市政府的地理位置,进行解码即可
                        this.$core.debug().log(res.result.location,
                            gps.gcj_decrypt([res.result.location.lng, res.result.location.lat]),
                            gps.gcj_encrypt([res.result.location.lng, res.result.location.lat]))
                    }else{
                        this.$core.debug().warn("坐标获取失败",res)
                    }
                }
            )
            this.view = new View({
                center: this.fromLonLat(this.location),
                zoom: 15,
                minZoom:3,
                maxZoom: 18,
                constrainOnlyCenter: true,
            });
            this.overlay=new Overlay({element: document.getElementById(this.name+'_popup'),
                autoPan: {
                    animation: {
                        duration: 250,
                    },
                },
            })

            this.interactions.push(new Drag());

            this.map = new Map({
                controls: defaultControls().extend(this.controls),
                interactions:defaultInteractions().extend(this.interactions),
                layers: this.getDefaultLayers(),
                target:  this.name,
                view: this.view,
                overlays:[this.overlay]
            });

           this.addVectorLayerByJson({code:"iot",jid:270,distance:10,minDistance:7,zoomToExtent:false});
           //对地址参数进行支持
           if (this.options ) {
               if(this.options.type=="pos"&&this.options.lon&&this.options.lat){
                   this.addVectorLayer({code:"drag_position",encrypt:false,style:new Style({
                           image: new Icon({
                               anchor: [0.5, 200],
                               anchorXUnits: 'fraction',
                               anchorYUnits: 'pixels',
                               opacity: 0.95,
                               src: 'point.png',
                               scale:[0.16,0.16]
                           })}),
                       data:[{id:"drag_object",geom:"POINT("+this.options.lon+" "+this.options.lat+")",draggable:true,dragEnd:(e,control)=>{
                               let coordinate=  this.toLonLat(control.coordinate_);
                               this.options.lon=coordinate[0].toFixed(4);
                               this.options.lat=coordinate[1].toFixed(4);
                               this.$emit('positionChanged', this.options);
                           }}]});
                   let feature= this.getLayer("drag_position").getSource().getFeatureById("drag_object")
                   this.map.getView().fit(feature.getGeometry(),{maxZoom:10});
               }
           }

           this.map.on('singleclick', (e)=> {
               const coordinate = e.coordinate;
               let layers= this.serviceLayerGroup.getLayers();
               layers.forEach((layer, i) => {
                   layer.getFeatures(e.pixel).then((features)=>{
                       this.handlePopup(features,coordinate,"clickable")
                       // if(features.length){
                       //     //增加对剔除模式的支持
                       //     for(let i=0;i<features.length;i++) {
                       //         let feature = features[i];
                       //         if (feature.data == null && feature.values_ && feature.values_.features && feature.values_.features.length) {
                       //             feature = feature.values_.features[0];
                       //         }
                       //         if (feature.data && feature.data.clickable && feature.data.content) {
                       //             if (this.content == null) {
                       //                 this.content = document.getElementById(this.name + '_popup_content');
                       //             }
                       //             this.content.innerHTML = feature.data.content;
                       //             this.overlay.setPosition(coordinate);
                       //             if (this.closer == null) {
                       //                 this.closer = document.getElementById(this.name + '_popup_closer');
                       //                 this.closer.onclick = () => {
                       //                     this.overlay.setPosition(undefined);
                       //                     this.closer.blur();
                       //                     return false;
                       //                 };
                       //             }
                       //         }
                       //     }
                       // }
                   })
               });
           });
           this.map.on('pointermove',  (e)=> {
               let hit = e.map.hasFeatureAtPixel(e.pixel);
               if(hit) {
                   let features= e.map.getFeaturesAtPixel(e.pixel)[0].values_.features;
                   if(features) {
                       this.handlePopup(features, e.coordinate);
                       for (let i in features) {
                           if (features[i].data && features[i].data.clickable) {
                               document.getElementById(e.map.getTarget()).style.cursor = 'pointer';
                               break;
                           }
                           // if (features[i].data && features[i].data.dragable) {
                           //     document.getElementById(e.map.getTarget()).style.cursor = 'grab';
                           //     break;
                           // }
                       }
                   }
               }else{
                   document.getElementById(e.map.getTarget()).style.cursor= '';
               }
           });

            document.getElementsByClassName("position")[0].innerHTML = this.positionFormat(this.location);
            //阻止地图的事件喷涌而产生右键菜单
            document.getElementById(this.name).oncontextmenu=(e)=> {
                if(e.button==2){
                    e.preventDefault();
                }
            }

        },
        methods: {

        }
    }
</script>
<style scoped>
    .fullscreen:-webkit-full-screen {
        height: 100%;
        margin: 0;
    }
    .fullscreen:-ms-fullscreen {
        height: 100%;
    }

    .fullscreen:fullscreen {
        height: 100%;
    }

    .fullscreen {
        width: 100%;
        height: 100%;
    }
    .map {
        width: 100%;
        height:100%;
        position: relative;
    }

</style>
<style lang="scss">
    .map{
        .ol-rotate {
            top: 3em;
        }
        .ol-zoom-extent{
            top:5.5em;
            right:0.5em;
            left: unset;
        }
        .ol-zoom {
            top:8em;
            right:0.5em;
            left: unset;
            .ol-zoom-out{
                margin-top: 200px;
            }
        }
        .ol-zoomslider{
            right:0.5em;
            left: unset;
            top: calc(8em +  1px + 1.14 * 1.375em);
            background-color: transparent;
        }
        .ol-touch{
            .ol-zoom {
                .ol-zoom-out{
                    margin-top: 212px;
                }
            }
            .ol-zoomslider{
                top: 8.25em;
            }
        }
        .ol-zoom-in.ol-has-tooltip:hover [role=tooltip],
        .ol-zoom-in.ol-has-tooltip:focus [role=tooltip] {
            top: 3px;
        }
        .ol-zoom-out.ol-has-tooltip:hover [role=tooltip],
        .ol-zoom-out.ol-has-tooltip:focus [role=tooltip] {
            top: 232px;
        }
        [type="button"]:not(:disabled),[type="reset"]:not(:disabled), [type="submit"]:not(:disabled),button:not(:disabled){
            cursor: pointer;
        }

        .base-map{
            right:0.5em;
            bottom: 6em;
            width: 60px;
            height: auto;
            button{
                width: 54px;
                height: 54px;
                display: block;
                margin-bottom: 3px;
                background-size: 100% 100%;
                &.map1{
                    background-image: url("../../assets/common/map.png");
                    color: #0a9398;
                }
                &.map2{
                    background-image: url("../../assets/common/img.png");
                }
                &.map3{
                    background-image: url("../../assets/common/ter.png");
                    color: #0a9398;
                }
            }
        }
    }
    .position{
        position: absolute;
        bottom: 30px;
        left: calc(50% - 90px);
        width: 180px;
        height: 22px;
        line-height: 22px;
        text-indent: 12px;
        vertical-align: middle;
        background-color:rgba(0,60,136,0.3);
        border-radius: 4px;
        color: #eee;
    }


    .ol-popup {
        position: absolute;
        background-color: white;
        box-shadow: 0 1px 4px rgba(0,0,0,0.2);
        padding: 15px;
        border-radius: 10px;
        border: 1px solid #cccccc;
        bottom: 12px;
        left: -50px;
        min-width: 280px;
    }
    .ol-popup:after, .ol-popup:before {
        top: 100%;
        border: solid transparent;
        content: " ";
        height: 0;
        width: 0;
        position: absolute;
        pointer-events: none;
    }
    .ol-popup:after {
        border-top-color: white;
        border-width: 10px;
        left: 48px;
        margin-left: -10px;
    }
    .ol-popup:before {
        border-top-color: #cccccc;
        border-width: 11px;
        left: 48px;
        margin-left: -11px;
    }
    .ol-popup-closer {
        text-decoration: none;
        position: absolute;
        top: 2px;
        right: 8px;
    }
    .ol-popup-closer:after {
        content: "✖";
    }

</style>