<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>

        <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;z-index:1">
         <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: 20px;font-weight: 600;">{{selectDevice.loc_mode}}</span>
                        <span style="color:darkgray">定位模式</span>
                    </div>
                    <div class="row-left-layout">
                        <span style="font-size:20px;font-weight:600">{{selectDevice.battery_level}}  <span style="font-size:12px">%</span> </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>IMEI：{{selectDevice.imei}}</p>
                    </div>
                    
                </div>
            </div>

            <div class="panel-plain-text">
                {{selectDevice.address}}
            </div>
            <div class="route-search-button" style="position:relative">
                <router-link :to="'route_search/'+ selectDevice.imei" 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>

        <van-overlay :show="loadingOverlay">
            <div class="wrapper">
                <van-loading type="spinner" color="#dddddd" text-color="#dddddd"  vertical>加载中...</van-loading>
            </div>
        </van-overlay>        

    </div>
</template>


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


export default {
    mounted(){
        let that = this;      
        let map = this.initMap();

        
        map.then((result) => {
            if(result === false){
                this.$dialog.toast({
                    mes: '地图初始化失败，请刷新重试',
                    timeout: 3000
                });
                return
            }

            that.getLastStuPositon();
            
        }).catch((err) => {
            this.$dialog.toast({
                mes: '地图数据初始化出错，请刷新重试或联系管理员',
                timeout: 3000
            });
            this.loadingOverlay = false;
            console.log(err)
            return
        });


    },
    data(){
        return {
            map: null,
            selectStudent: '',
            stuList: [],
            stuPickList: [],
            positionInfo: '',
            geocoder: null,
            parsedAddress: '',
            routeList: [],
            selectDevice: '',
            selectImei:'',
            routePanelShow: false,
            gpsActive: true,
            stationActive: false,
            markersArr: [],
            loadingOverlay: true,
            

            fenceOverLays: [],

            panelShow: false,
            showFence: false,

            normalColor: 'normalColor',
            alarmColor: 'alarmColor'
        }
    },

    methods: {
        refreshPosAndRoute(){
            this.panelShow = false;
            this.getLastStuPositon()
        },
        navi2routeSearch(){
            let that=  this;
        },
        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&imei=" + markerData.imei).then(res => {
                    if(!res.data.success){
                        that.$dialog.toast({
                            mes: res.data.message,
                            timeout: 3000
                        });
                        return
                    }
                    let devices = res.data.data;
                    devices.loc_mode = devices.loc_mode.toUpperCase()
                    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.getSavedFenceAndDraw();
                console.log('-------------1')
                return;
            }

            if(this.showFence){
                this.fenceOverLays.forEach(item => {
                    item.show();
                    item.getExtData().textLabel.show()
                });
                console.log('-------------2')
                this.map.setFitView(this.fenceOverLays);
                
            }else{
                this.fenceOverLays.forEach(item => {
                    item.hide();
                    item.getExtData().textLabel.hide()
                });
                console.log('-------------3')
            }
        },

        navi2routeSearch(){
            let that=  this;
            this.$router.push({name:'routeSearch',params:{student:that.selectStudent}});
        },
        
        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',
                    ], function(){
                        // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
                        map.addControl(new AMap.ToolBar({position: 'RT'}));
                        // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
                        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);
                }
            });
        },

        getSavedFenceAndDraw(){
            let that= this;
            this.$http.get("/getAllFences&userid=" + localStorage.getItem("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.createOverlay(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);
                });

        },
        createOverlay(fenceData){
            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]
                });
                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}
                })
            }

            return overLay;
        },



        getLastStuPositon(){
            let that = this;

            this.$http.get("/getLastPositionMulti&userid=" + localStorage.getItem('userid')).then(res => {
                    if(!res.data.success){
                        that.$dialog.toast({
                            mes: res.data.message,
                            timeout: 3000
                        });
                        this.loadingOverlay = false;
                        return
                    }
                    let devices = res.data.data;
                    that.map.clearMap()

                    let markerArr = [];
                    devices.forEach( (item,index) => {
                        item._index = index;
                        let markerPos = new AMap.LngLat(item.lng, item.lat)
                        let image = item.device_type ? 'https://rlfd.oss-cn-hangzhou.aliyuncs.com/wxt_school/smart_card.png' : 'https://rlfd.oss-cn-hangzhou.aliyuncs.com/wxt_school/smart_card.png';

                        var marker = new AMap.Marker(
                            {
                                position: markerPos,
                                icon: new AMap.Icon({
                                    size: new AMap.Size(128, 128),
                                    imageSize: new AMap.Size(40, 40),
                                    image: image,
                                    
                                }), // 添加 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.toUpperCase()
                            that.selectDevice = data;

                            let str = (data.device_name  != 'null' &&  data.device_name) ? data.device_name : '设备' + data.imei.substr(-4);
                            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);

                    //默认选中一个
                    let defaultData  = that.markersArr[0].getExtData();
                    defaultData.loc_mode = defaultData.loc_mode.toUpperCase()
                    that.selectDevice = defaultData;
                    let defaultStr = (defaultData.device_name  != 'null' &&  defaultData.device_name) ? defaultData.device_name :  '设备' + defaultData.imei.substr(-4);
                    let defaultContent = that.createInfowind(defaultStr);
                    that.infoWindow.setContent(defaultContent);
                    that.infoWindow.open(that.map, that.markersArr[0].getPosition());
                    that.panelShow = true;

                    //loading关闭
                    this.loadingOverlay = false;
                    

                    

                    

                    // that.geocoder.getAddress(markerPos, function(status, result) {
                    //     if (status === 'complete' && result.info === 'OK') {
                    //         // result为对应的地理位置详细信息
                            
                    //         that.parsedAddress =result.regeocode.formattedAddress
                    //     }else{
                    //         that.parsedAddress= '无法解析该坐标';
                    //     }
                    // })

                    
                    // that.map.panTo(markerPos)

                })
                .catch(res => {
                    this.loadingOverlay = false;
                    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);
    
}
.wrapper{
    display: flex;
    justify-content: center;
    align-items: center;
    height: calc(100vh - 1rem);
}
.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;
    left: 10px;
    z-index: 99;
    top: 3rem;
}

.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;
    left: calc(5%);
    top:2rem;
    z-index: 99;
    height: 24px;
    width: 24px;
    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);
}

</style>