<template>
    <div>
        <div id="route-map">

            <span class="icon-base fence-showoff" :class="{buttonActive: showFence}" @click="toggleShowFence">
                <yd-icon name="dianziweilan" size=".4rem"  custom></yd-icon>
            </span>

            <span class="refresh-button" @click="refreshPosAndRoute">
                <yd-icon  name="refresh" size="14px"></yd-icon>
            </span>
            
            <div class="setting-button">
                
                <van-popover v-model="showSettings" trigger="click" placement="left">
                    <div style="padding: 6px;">
                        <van-checkbox v-model="isOnlyFenceDevice" @change="changeSetting('isOnlyFenceDevice',$event)" shape="square" icon-size="14">只显示选中围栏内设备</van-checkbox>
                        <!-- <van-checkbox v-model="isClusterMarker" @change="changeSetting('isClusterMarker',$event)" shape="square" icon-size="14">聚合图标</van-checkbox> -->
                    </div>

                    <template #reference>
                        <van-icon size="18" name="setting" />
                    </template>
                </van-popover>
            </div>
        </div>

        <van-popup v-model="panelShow" round :overlay="false" position="bottom" 
         style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);margin-bottom:1rem;">
         <div class="info-panel">
            <div class="panel-first-row">
                <div style="font-size:14px;font-weight:550;color:gray">{{selectDevice.date_time}}({{selectDevice.awayTime}}前)</div>
                <van-tag plain :type="selectDevice.alarm_state == 0 ? 'primary' : 'danger'">{{selectDevice.alarm_state == 0 ? '安全' : '告警'}}</van-tag>
            </div>

            <div class="panel-second-row">
                <div class="second-row-left">
                    <div class="row-left-layout">
                        <span style="font-size: 10px;font-weight: 600;">{{selectDevice.loc_mode}}</span>
                        <span style="color:darkgray">设备型号</span>
                    </div>
                    <div class="row-left-layout">
                        <span style="font-size:10px;font-weight:600">{{selectDevice.state}}   </span>
                        <span style="color:darkgray">设备状态</span>
                    </div>
                </div>
                <div class="row-right-layout">
                    <!-- <van-image
                    width="1.08rem"
                    height="0.6rem"
                    fit="cover"
                    src="https://rlfd.oss-cn-hangzhou.aliyuncs.com/wxt_school/student_card_product.png"
                    @click.native="showPreview"
                    /> -->
                    <div class="right-number" >
                        <p>名称：{{selectDevice.device_name}}</p>
                        <p>出厂编号：{{selectDevice.factory_number}}</p>
                    </div>
                    
                </div>
            </div>

            <div class="panel-plain-text">
                {{selectDevice.address}}
            </div>
            <div class="route-search-button" style="position:relative">
                <router-link :to="'yys_route_search/'+ selectDevice.factory_number" class="voice-device-item">
                    <van-button type="info" icon="search" size="small" round  style="width:3rem" >历史定位</van-button>
                </router-link>
                <van-button @click.native="refreshSingle"  plain type="info" icon="replay" size="mini" style="font-size:12px;position:absolute;right:0.5rem;top:0.1rem"></van-button>
            </div>

         </div>
        </van-popup>

    </div>
</template>


<script type="text/babel">
import Vue from 'vue'
import { Popup, Image as VanImage,Button,Icon,Tag, ImagePreview, Checkbox, Popover } from 'vant';
Vue.use(VanImage);
Vue.use(Popup);
Vue.use(Button);
Vue.use(Icon);
Vue.use(Tag);
Vue.use(Checkbox);
Vue.use(Popover);


export default {
    filters: {
        upperCase(val) {
            if (val) {
                return val.toUpperCase();
            }
        }
    },
    mounted(){
        let that = this;      
        let map = this.initMap();

        map.then((result) => {
            if(result === false){
                this.$toast('地图初始化失败，请刷新重试');
                return;
            }
            that.getLastPositon();
        }).catch((err) => {
            this.$toast('地图数据初始化出错，请刷新重试');
            console.log(err);
            return;
        });
        // that.getPositioning();
    },
    data(){
        return {
            isClusterMarker: false, // 是否聚合
            isOnlyFenceDevice: false, // 是否仅显示围栏内设备
            showSettings: false, // 显示设置项
            checkedFenceObject: null, // 选中的围栏对象
            cluster: null, // 聚合对象

            userid: '',
            openid: '',
            map: null,
            geocoder: null,
            positionInfo: '',
            parsedAddress: '',
            selectDevice: '',
            selectImei:'',
            markersArr: [],
            fenceOverLays: [],

            panelShow: false, // 显示设备信息栏
            showFence: false, // 显示围栏

            normalColor: 'normalColor',
            alarmColor: 'alarmColor'
        }
    },
    created() {
        this.openid = localStorage.getItem('openid');
        this.userid = localStorage.getItem('yysUserid');

        this.isOnlyFenceDevice = localStorage.getItem('isOnlyFenceDevice');
        // this.isClusterMarker = localStorage.getItem('clusterMarker');
    },
    destroyed() {
        this.infoWindow && this.infoWindow.remove();
        this.infoWindow = null;
        this.markersArr && this.markersArr.forEach(item => {
            item.remove();
        })
        this.markersArr = null;
        this.fenceOverLays && this.fenceOverLays.forEach(item => {
            item.destroy();
        })
        this.fenceOverLays = null;
        this.map && this.map.clearMap() && this.map.destroy();
        this.map = null;
        // console.log(this);
    },
    methods: {
        /**
         * 更改配置
         */
        changeSetting(item, val) {
            if (val) {
                localStorage.setItem(item, val);
            } else {
                localStorage.removeItem(item);
            }

            if (item == 'isOnlyFenceDevice') {
                // 如果没有选中的围栏，不重新请求
                if (!this.checkedFenceObject) {
                    return;
                }
            }
            this.getLastPositon();
        },
        /**
         * 刷新设备信息
         */
        refreshPosAndRoute(){
            this.panelShow = false;
            this.getLastPositon()
        },
        /**
         * 创建信息窗
         */
        createInfowind(str){
            let content = '<div style="background: white;box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);border-radius: 30px;padding:2px 8px">'+
                    // '<div>' +
                    //     '<img style="width:0.4rem;height:0.4rem" src="@/assets/image/walking.png" alt="">' +
                    // '</div>' + 
                    '<div class="info-window-data">' + 
                        '<span> '+ str +'</span>' + 
                        // '<span>'+ data.time +'分钟</span>' + 
                   ' </div>' +
                '</div>';
                return content;
        },
        /**
         * 刷新选中单个设备信息
         */
        refreshSingle(){
            let markerData = this.selectDevice;
            let that =this;
            
            this.$http.get("getLastPositionSingle?id=" + markerData.id +'&openid=' + this.openid).then(res => {
                    if(res.data.code!=10000){
                        that.$dialog.toast({
                            mes: res.data.message,
                            timeout: 3000
                        });
                        return
                    }
                    let devices = res.data.data;
                    devices._index = markerData._index;
                    

                    that.markersArr[markerData._index].setExtData(devices);
                    that.markersArr[markerData._index].setPosition(new AMap.LngLat(devices.lng, devices.lat));
                    that.infoWindow.open(that.map, that.markersArr[markerData._index].getPosition());
                    that.map.panTo(that.markersArr[markerData._index].getPosition());

                    that.selectDevice = devices;
                    // console.log(devices, markerData._index);


                })
                .catch(res => {
                    console.log(res);
                });
            
        },
        /**
         * 预览图片
         */
        showPreview(){
            ImagePreview(['https://rlfd.oss-cn-hangzhou.aliyuncs.com/wxt_school/student_card_product.png']);
        },
        /**
         * 显示/隐藏信息窗
         */
        togglePanel(){
            this.panelShow = !this.panelShow
        },
        /**
         * 显示/隐藏围栏
         */
        toggleShowFence(){
            this.showFence = !this.showFence
            // console.log(this.showFence)
            if(this.showFence && this.fenceOverLays.length === 0){
                this.getAllFences();
                return;
            }

            if(this.showFence){
                this.fenceOverLays.forEach(item => {
                    item.show();
                    item.getExtData().textLabel.show()
                });
                this.map.setFitView(this.fenceOverLays);
                
            }else{
                this.fenceOverLays.forEach(item => {
                    item.hide();
                    item.getExtData().textLabel.hide()
                });
            }
        },
        /**
         * 初始化地图
         */
        initMap(){
            let that = this;

            return new Promise((resolve, reject) => {
                try {
                   
                    var map = new AMap.Map('route-map', {
                        zoom:15,//级别
                        center: [119.5,32.9],//中心点坐标
                        // viewMode:'3D',//使用3D视图
                        // mapStyle: 'amap://styles/light',
                        showBuildingBlock: true
                    });
                    
                    AMap.plugin([
                        'AMap.ToolBar',
                        'AMap.Scale',
                        'AMap.MapType',
                        'AMap.Geocoder',
                        'AMap.Geolocation'
                        // 'AMap.MarkerCluster',
                    ], function () {
                       let geolocation = new AMap.Geolocation({
                            enableHighAccuracy: true,
                            // 设置定位超时时间，默认：无穷大
                            timeout: 10000,
                            // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
                            buttonOffset: new AMap.Pixel(10, 20),
                            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                            zoomToAccuracy: true,
                           panToLocation: true,
                            noIpLocate:0,
                            //  定位按钮的排放位置,  RB表示右下
                            buttonPosition: 'RB'
                       });
                        map.addControl(geolocation);
                        geolocation.getCurrentPosition()
                        console.log(AMap.Event);
                        AMap.Event.addListener(geolocation, 'complete', onComplete);
                        AMap.Event.addListener(geolocation, 'error', onError);
                        function onComplete(data) {
                            // data是具体的定位信息
                            console.log(data)
                            if (data.position) {
                                that.saveLocationInfo(data.position);
                            } else {
                                that.$notify({
                                    type: 'warning',
                                    message: '获取定位失败',
                                });
                            }
                        }
                        function onError(data) {
                            // 定位出错
                            that.$notify({
                                type: 'warning',
                                message: '获取定位失败',
                            });
                        }
                   
                        
                        // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
                        map.addControl(new AMap.ToolBar({position: 'RT', offset: [15, 50]}));
                        // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
                        map.addControl(new AMap.Scale({position: 'LT'}));
                        // // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
                        // map.addControl(new AMap.MapType());
                        that.geocoder = new AMap.Geocoder({})

                    });


                    that.infoWindow = new AMap.InfoWindow({
                        isCustom: true,  //使用自定义窗体
                        content: '',
                        autoMove: false,
                        offset: new AMap.Pixel(0, -40)
                    });

                    that.map = map;
                    that.map.on('click', function(){
                        that.panelShow = false;
                        that.infoWindow.close();
                    });
                    resolve(that.map);
                } catch (error) {
                    console.log(error)
                    reject(false);
                }
            });
        },
        //保存个人定位信息
        saveLocationInfo(data)
        {
            localStorage.setItem('position',data);

        },
        /**
         * 获取围栏数据
         */
        getAllFences(){
            let that= this;
            this.$http.get("/getAllFences&userid=" + this.userid).then(res => {
                    // console.log(res.data, 'fence res')
                    let resp = res.data;
                    if(!resp.success){
                        that.$dialog.toast({
                            mes: resp.message,
                            timeout: 3000
                        });
                        return
                    }
                    let fenceData = resp.data, fenceOverLays = [];

                    fenceData.forEach(item => {
                        let overLay = that.createFenceOverlay(item);
                        if(!overLay){

                        }else{
                            overLay.setMap(that.map)
                            overLay.getExtData().textLabel.setMap(that.map)
                            // that.map.add(overLay)
                            fenceOverLays.push(overLay);
                        }

                    });
                    that.fenceOverLays = fenceOverLays;
                    that.map.setFitView(that.fenceOverLays);
                    
                })
                .catch(res => {
                    console.log(res);
                });

        },
        /**
         * 画围栏
         */
        createFenceOverlay(fenceData){
            let that = this;
            let overLay = '';
            let type = fenceData.type ? '用户围栏' : '系统围栏';

            if(fenceData.shape == 'circle'){
                let center = fenceData.info.center, radius = fenceData.info.radius;

                let textLabel = new AMap.Text({
                    text: fenceData.name + '(' + type + ')',
                    anchor:'center', // 设置文本标记锚点
                    draggable:false,
                    style:{
                        'padding': '.2rem',
                        'background-color': 'white',
                        'min-width': '3rem',
                        'border-width': 0,
                        'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
                        'text-align': 'center',
                        'opacity': '0.8',
                        'font-size': '12px',
                        'color': 'blue'
                    },
                    position: [center.lng, center.lat]
                });
                
                textLabel.on('click', function(e) {
                    that.map.setBounds(e.target.getBounds())
                })

                overLay = new AMap.Circle({
                    center: new AMap.LngLat(center.lng, center.lat), // 圆心位置
                    radius: radius,  //半径
                    strokeColor: "#F33",  //线颜色
                    strokeOpacity: 1,  //线透明度
                    strokeWeight: 3,  //线粗细度
                    fillColor: "#ee2200",  //填充颜色
                    fillOpacity: 0.35, //填充透明度
                    extData: {name: fenceData.name, type: type, textLabel: textLabel}
                });
                
            }

            if(fenceData.shape == 'polygon'){
                let originPt = fenceData.info;
                let path = []

                originPt.forEach(item => {
                    let pt= [item.lng, item.lat]
                    path.push(pt);
                });


                let textLabel = new AMap.Text({
                    text: fenceData.name + '(' + type + ')',
                    anchor:'center', // 设置文本标记锚点
                    draggable:false,
                    style:{
                        'padding': '.2rem 0.5rem',
                        'margin-bottom': '1rem',
                        'border-radius': '.25rem',
                        'background-color': 'white',
                        'width': '4rem',
                        'border-width': 0,
                        'box-shadow': '0 2px 6px 0 rgba(114, 124, 245, .5)',
                        'text-align': 'center',
                        'opacity': '0.8',
                        'font-size': '12px',
                        'color': 'blue'
                    },
                    position: path[0]
                });

                overLay = new AMap.Polygon({
                    path: path,
                    strokeColor: "#FF33FF", 
                    strokeWeight: 6,
                    strokeOpacity: 0.2,
                    fillOpacity: 0.4,
                    fillColor: '#1791fc',
                    zIndex: 50,
                    extData: {name: fenceData.name, type: type, textLabel: textLabel}
                })
            }
            // 添加点击事件
            overLay.on('click', function(e) {
                that.panelShow = false;
                that.checkedFenceObject = e.target;
                that.getLastPositon();
            });

            return overLay;
        },
        /**
         * 获去设备定位数据列表
         */
        getLastPositon(){
            let that = this;
            
            
            this.$http.get("getHydList?userid="+this.userid+'&openid='+this.openid ).then(res => {
                    if(res.data.code!=10000){
                        that.$toast(res.data.message || '获取设备数据失败');
                        return;
                    }
                    let devices = res.data.data;

                    if (!devices.length) {
                        return;
                    }
                    // 移除设备覆盖物
                    // that.map.clearMap()
                    that.markersArr && that.map.remove(that.markersArr);
                    that.infoWindow && that.infoWindow.close();

                    let markerArr = [];
                    devices.forEach( (item,index) => {
                        item._index = index;
                        let markerPos = new AMap.LngLat(item.lng, item.lat)
                        let image ='https://rlfd.oss-cn-hangzhou.aliyuncs.com/smart_tool/beng.png';
                        
                        // 如果选中只显示围栏内设备
                        if (that.isOnlyFenceDevice && that.checkedFenceObject) {
                            if (!that.checkedFenceObject.contains(markerPos)) {
                                return;
                            }
                        }

                        var marker = new AMap.Marker({
                            position: markerPos,
                            icon: new AMap.Icon({
                                size: new AMap.Size(40, 40),
                                image: image,
                                imageSize: new AMap.Size(40, 40),
                            }), // 添加 Icon 图标 URL 
                            offset: new AMap.Pixel(-20,-40),
                            extData: item
                        })

                        marker.on('click', function (e) {
                            
                            let data = e.target.getExtData();
                            data.loc_mode = (data.loc_mode && data.loc_mode.toUpperCase())
                            that.selectDevice = data;

                            let str = (data.device_name  != 'null' &&  data.device_name) ? data.device_name : data.imei;
                            // str = str + '(' + data.imei + ')';

                            let content = that.createInfowind(str);
                            that.infoWindow.setContent(content);
                            that.map.setCenter(e.target.getPosition())
                            that.panelShow = true;
                            that.infoWindow.open(that.map, marker.getPosition());
                        });

                        that.map.add(marker)
                        markerArr.push(marker);
                    });

                    // if(!that.positionInfo.lng && !that.positionInfo.lat){
                    //     that.parsedAddress = '未曾上报位置,无法解析地址';
                    //     return;
                    // }

                    that.markersArr = markerArr;
                    that.map.setFitView(markerArr);

                    //默认选中一个
                    if (that.markersArr.length) {
                        let defaultData  = that.markersArr[0].getExtData();
                        defaultData.loc_mode = (defaultData.loc_mode && defaultData.loc_mode.toUpperCase())
                        that.selectDevice = defaultData;
                        // let defaultStr = defaultData.device_name + '(' + defaultData.imei + ')';
                        let defaultStr = defaultData.device_name || defaultData.imei;
                        let defaultContent = that.createInfowind(defaultStr);
                        that.infoWindow.setContent(defaultContent);
                        that.infoWindow.open(that.map, that.markersArr[0].getPosition());
                        that.panelShow = true;
                    }



                })
                .catch(res => {
                    console.log(res);
                });

        }

    }

}
</script>

<style lang="css" scoped>
#route-map{
    height:calc(100vh - 1rem);
    width: 100%;

   -webkit-transform: translateZ(0);
   -moz-transform: translateZ(0);
   -ms-transform: translateZ(0);
   -o-transform: translateZ(0);
   transform: translateZ(0);
    
}
.map-info-window{
    background: white;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    border-radius: 30px;
    max-width: 4rem;
    display: flex;
    justify-content:  space-around;
    align-items: center;
}
.info-window-data{
    display: flex;
    flex-direction: column;
    align-items: center;
}

.info-panel{
    padding:0.4rem;
}

.panel-first-row{
    display: flex;
    margin-bottom:0.2rem;
    justify-content: space-between;
    align-items: center;
}
.panel-second-row{
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
}
.second-row-left{

    display: flex;
 
}
.right-number{
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    border-radius: 6px;
    padding: 2px 4px 0 4px;
    font-weight: 600;
}
.row-left-layout{
    display: flex;
    flex-direction: column;
    margin-right: 0.5rem ;
}
.row-right-layout{
    display: flex;
    flex-direction: column;
    align-items: center;
}
.route-search-button{
    display: flex;
    justify-content: center;
    margin-top: 0.2rem;
}
.panel-plain-text{
    margin-top: 0.1rem;
    overflow:hidden;
    text-overflow:ellipsis;
    display:-webkit-box;
    -webkit-box-orient:vertical;
    -webkit-line-clamp:2; 
}

.type-bar{
  position: absolute;
    right: 10px;
    z-index: 99;
    top: 2.5rem;
}
.change-button{
  display: flex;
    flex-direction: column;
    justify-content: space-between;
}
.fence-showoff{
  position: absolute;
    bottom: 240px;
    right: 15px;
    z-index: 99;
}

.icon-base{
  width: 0.6rem;
  height: 0.6rem;
  margin-bottom: 0.1rem;
  background: white;
  border-radius: 8px;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
  color: darkgray;
}
.buttonActive{
  color: white;
  background: #2196f3;
}


.close-button-fold{
  /* position: absolute; */
  background: #ffffff;
  width: 40px;
  height: 20px;
  bottom: 4rem;
  left: 0;
  right: 0;
  margin: auto;
  border: 1px darkgray solid;
  border-bottom: none;
  border-radius: 100px 100px 0 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 199;
}
.close-button-unfold{
  /* position: absolute; */
  background: #ffffff;
  width: 40px;
  height: 20px;
  bottom: 0;
  left: 0;
  right: 0;
  margin: auto;
  border: 1px darkgray solid;
  border-bottom: none;
  border-radius: 100px 100px 0 0;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 199;
}


.normalColor{
    color: #2196f3;
}
.alarmColor{
    color: red;
}
.bottom-route-info{
    /* position: absolute; */
    bottom: 0;
    height: 4rem;
    background: #fff;
    width: 100%;
}
.route-button{
    background: #2196f3;
    border-radius: 5px;
    padding: 2px;
    width: 100px;
    text-align: center;
    color: #fff;
}
.address-info{
    display: flex;
    justify-content: space-between;
    margin-top: 10px;
}
.float-first{
    display: flex;
    align-items: center;
    position: relative;
}
.first-locinfo{
    display: flex;
    margin-left: 10px;
}
.first-avatar{
    border-radius: 500px;
    width: 48px;
    height: 48px;
    background: lightgray;
    display: flex;
    justify-content: center;
    align-content: center;
}
.select-butt{
    position: absolute;
    top: 1.2rem;
    z-index: 1;
    right: 0;
    left: 0;
    margin: auto;
}
.bottom-panel{
    position: absolute;
    bottom: 0.3rem;
    z-index: 99;
    width: 100%;
display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    
}
.first-loctime{
    text-align: left;
}
.panel-float{
    padding: 10px;
    background: white;
    border-radius: 10px;
    min-height: 2.4rem;
    width: 90%;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.refresh-button{
    position: absolute;
    bottom: 200px;
    right: 15px;
    z-index: 99;
    height: 30px;
    width: 30px;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 50px;
    padding: 2px;
    background: #fff;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.2);
}

.setting-button {
    position: absolute;
    width: 30px;
    height: 30px;
    z-index: 1000;
    top: 15px;
    right: 15px;
    background-color: #fff;
    padding: 4px;
    border-radius: 6px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);
    text-align: center;
    line-height: 30px;
}
</style>