<template>
<div style="width:100%;height:100%">
  <div style="width:100%;height:100%">
    <div id="map" ref="rootmap"><div id="popup"></div></div>
     <div id="textInfo">我是text文本信息</div>
  </div>

  <div class="iconSelect" v-if="iconSelect == 1">
      <el-checkbox-group  v-model="checkList" @change="handleChange" >
          <el-checkbox v-for="item in dict.type.tl_static_type" :label="item.value"  :key="item.value" style="margin-top:1rem">
                 <!-- <img class="tipicon"  src="../../assets/images/icons/video.png" /> -->
                 <img class="tipicon"  :src="imageMap[item.value]" />
                <span style="color:white">{{item.label}}</span>
           </el-checkbox>
      </el-checkbox-group>
  </div>

    <div class="iconSelect" v-if="iconSelect == 2">
      <el-checkbox-group  v-model="checkList" @change="handleChange" >
          <el-checkbox v-for="item in dict.type.tl_dt_type" :label="item.raw.cssClass"  :key="item.value" style="margin-top:1rem">
                 <!-- <img class="tipicon"  src="../../assets/images/icons/video.png" /> -->
                 <img class="tipicon"  :src="imageMap[item.raw.cssClass]" />
                <span style="color:white">{{item.label}}</span>
           </el-checkbox>
      </el-checkbox-group>
   </div>

  <div class="iconSelect" v-if="iconSelect == 3">
      <el-checkbox-group  v-model="checkList" @change="handleChange" >
          <el-checkbox v-for="item in dict.type.tl_area_type" :label="item.raw.cssClass"  :key="item.value" style="margin-top:1rem">
                 <!-- <img class="tipicon"  src="../../assets/images/icons/video.png" /> -->
                 <img class="tipicon"  :src="imageMap[item.raw.cssClass]" />
                <span style="color:white">{{item.label}}</span>
           </el-checkbox>
      </el-checkbox-group>
   </div>


      <el-dialog
          title="视频播放"
          :visible.sync="dialogVisible"
          v-if="dialogVisible"
          width="50%"
          :before-close="handleClose"
          >
            <div style="width:100%;height:60rem;position:relative">
              <videodiv :cameracode="ccode" style="width:100%;height:100%;position:absolute;top:0;left:0"></videodiv>
            </div>

              <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose()">关闭</el-button>
        <!-- <el-button type="primary" @click="dialogVisible = false">确 定</el-button> -->
      </span>
    </el-dialog>
</div>
</template>

<script>
import "ol/ol.css";
import Map from "ol/Map";
// import TileLayer from "ol/layer/Tile";
// import ImageLayer from "ol/layer/Image";
import View from "ol/View";
// import ol from "ol";

// import {getTopLeft, getWidth} from "ol/extent";

// import ImageWMS from "ol/source/ImageWMS";
// import WMTS from "ol/source/WMTS";
// import TileWMS from "ol/source/TileWMS";
// import WMTSTileGrid from "ol/tilegrid/WMTS";
// ol.source.TileImage
// ol.layer.Tile
import {get as getProjection, transform} from "ol/proj";
import {TileGrid} from "ol/tilegrid/TileGrid";
import {TileImage} from "ol/source/TileImage";
import {XYZ, Vector as SourceVec} from "ol/source";
import {Tile,Vector as LayerVec} from "ol/layer";
import { Polygon } from "ol/geom"
import Overlay from 'ol/Overlay';

import {Circle as CircleStyle, Fill, Stroke, Style, Icon, Text } from 'ol/style';
import {Draw, Modify, Snap} from 'ol/interaction';
// import {OSM, Vector as SourceVec} from 'ol/source';
// import {Tile as TileLayer, Vector as LayerVec} from 'ol/layer';
import {get,fromLonLat } from 'ol/proj';
import { Feature } from "ol";



// import {Vector as SourceVec} from "ol/source";
// import {Feature} from "ol";
import videodiv from "@/components/Videoplayer/index.vue"
import {LineString, Point} from "ol/geom";
import { scale } from 'ol/coordinate';
import { getLineData } from "@/api/qdtl/data";
import {toStringHDMS} from 'ol/coordinate';
// import {Icon, Stroke, Style} from "ol/style";
// import {Vector as LayerVec} from "ol/layer";


export default {
  props: {
      pointObj:{type:Object},
      isEdit:false
  },
  dicts: ['tl_static_type','tl_area_type','tl_dt_type'],
  data() {
    return {
      iconSelectArea:true,
      iconSelect:1,
      checkList:[],
      map: null,
      typeSelect:'Point',
      source:null,
      draw:null,
      snap:null,
      locations:[],
      vector:null,
      pointArry:{},
      mapHashMap:{},
      deviceList:[],
      areaList:[],
      dialogVisible:false,
      ccode:'',
      imgSrc:'require(../../assets/images/icons/',
      imgtype:'.png)',
      imageMap:{
            video:require('../../assets/images/icons/video.png'),
            location:require('../../assets/images/icons/location.png'),
            stop:require('../../assets/images/icons/stop.png'),
            work:require('../../assets/images/icons/work.png'),
            area:require('../../assets/images/icons/area.png'),
            bridge:require('../../assets/images/icons/bridge.png'),
            train:require('../../assets/images/icons/train.png'),
            rail:require('../../assets/images/icons/rail.png'),
            yjdw:require('../../assets/images/icons/yjdw.png'),
            device:require('../../assets/images/icons/device.png'),
            police:require('../../assets/images/icons/police.png'),
            wrj:require('../../assets/images/icons/wrj.png'),
            yxjl:require('../../assets/images/icons/yxjl.png'),
      },
      popup:null,
      element:null
    };
  },
   components:{
      videodiv
    },
   watch:{
      iconSelect(val, oldVal){//普通的watch监听
          this.checkList = [];
          for(var key in this.mapHashMap){
                 this.mapHashMap[key].setVisible(false)
            }
            for(var index in this.deviceList){
                 this.deviceList[index].setVisible(false)
            }
            for(var index in this.areaList){
                 this.areaList[index].setVisible(false)
            }
      },
    },
  mounted() {
    this.initdev();
    this.initPoint();
    this.getTrain(),
    this.getLineList();
    window.videosize = "1x1";
    // this.addpoint(point);
    var that = this
    this.map.on("click", function (e) {
          //  that.addMarker(e.coordinate,'专家站点.png',0.2);
            var pixel = that.map.getEventPixel(e.originalEvent);
            var feature = that.map.forEachFeatureAtPixel(e.pixel, function (feature, layer) {
                return feature;
              });
            if (feature) { //这里说明我们点击的是点标记，
                let tadata = feature.get("tadata"); //我们可以通过给点标记传不同的值，来判断点击不同的点标记触发的事件。
                if (tadata) {
                    if (tadata.sectionId == "line") {
                        // alert("我是线：" + tadata.towerNumber)
                    }
                    if (tadata.sectionId == "point") {
                         if(tadata.type == 'video'){
                               that.ccode = tadata.data.cameraIndexCode
                                window.cameraid = that.ccode;
                                that.dialogVisible = true
                                setTimeout(() => {
                                  that.handleOpen()
                                }, 1000);
                         }
                    }
                    //含有lnglat 参数的点标记触发事件
                }
            }
    });


    var view = this.map.getView();

    view.on('change:resolution', function (e) {

    });
    view.on('change:center', function (e) {

    });
    this.map.on('moveend', function (e) {
    });

    this.map.on('pointermove', function (evt) {
          if (evt.dragging) {
            return;
          }
          const pixel = that.map.getEventPixel(evt.originalEvent);
          var feature = that.map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
                return feature;
              });
           if (feature) { //这里说明我们点击的是点标记，
                let tadata = feature.get("tadata"); //我们可以通过给点标记传不同的值，来判断点击不同的点标记触发的事件。
                if (tadata) {
                    if (tadata.sectionId == "line") {
                        // alert("我是线：" + tadata.towerNumber)
                    }
                    if (tadata.sectionId == "point") {
                        //  that.addText(evt.coordinate);
                      console.log(tadata);
                           that.popup.setPosition(evt.coordinate);
                          $(that.element).popover({
                            placement: 'top',
                            html: true,
                            content: tadata.data.name,
                          });
                          $(that.element).popover('show');
                        // } else {
                        //   $(element).popover('dispose');
                        // }
                                          // popup = new OpenLayers.Popup.FramedCloud("Popup",
                    //     new OpenLayers.LonLat(5.6, 50.6),
                    //     null,
                    //     '<div>Hello World! Put your html here</div>',
                    //     null,
                    //     false);
                    // this.map.addPopup(popup);
                    }else{
                       $(that.element).popover('dispose');
                    }
                    //含有lnglat 参数的点标记触发事件
                }
            }
              
    })
  },
  methods: {
       addText(location) {
            var textInfo = new Overlay({
                position: fromLonLat(location),
                offset: [20, -20],
                element: document.getElementById("textInfo")
            });
            this.map.addOverlay(textInfo);
        },
         getTrain(){
           var trainArry = [[121.645366,31.856052],[121.636002,32.02354],[121.530258,32.086391]];
           for(var index in trainArry){
                  this.addMarker(trainArry[index],'train.png',0.6,'marker');
           }
         },
         getLineList(){
           getLineData().then(data =>{
                    for(var index in data.data){
                         var obj = data.data[index]
                         if(obj.configKey.indexOf('lined') > -1){
                                var lineLocations ="["+obj.configValue+"]"                            
                                var json = JSON.parse(lineLocations);
                                this.addline(json,1);
                         }else if(obj.configKey.indexOf('lineun') > -1){
                                var lineLocations ="["+obj.configValue+"]"
                                var json = JSON.parse(lineLocations);
                                this.addline(json,2);
                         }

                    }
              })   
         },
    initdev: function () {
      var projection = getProjection("EPSG:3857");
        const satellite = new Tile({ // 卫星地图
          visible: false, // 显示或隐藏（用于切换地图图层（卫星切换街道））
          source: new XYZ({
            attributions: '',
            url: 'https://webst0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=6&x={x}&y={y}&z={z}&scl=1&ltype=10'
          })
        })
        const street = new Tile({ // 街道地图
          visible: true, // 显示或隐藏（用于切换地图图层（卫星切换街道））
          source: new XYZ({
            attributions: '',
            url: 'https://webst0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}'
          })
        })

      this.source = new SourceVec();
      const vector = new LayerVec({
        source: this.source,
        style: new Style({
          fill: new Fill({
            color: 'rgba(255, 255, 255, 0.2)',
          }),
          stroke: new Stroke({
            color: '#ffcc33',
            width: 2,
          }),
          image: new CircleStyle({
            radius: 7,
            fill: new Fill({
              color: '#ffcc33',
            }),
          }),
        }),
      });
        this.vector = vector;

  // 创建地图
  const map = new Map({
    target: 'map',
    layers: [ // 图层放置（类似有卫星图层，街道图层等）
      satellite,
      street,
      vector
    ],
    view: new View({
      zoom: 11, // 当前缩放
      maxZoom: 16, // 最大缩放
      minZoom: 8, // 最小缩放
      projection: 'EPSG:4326',
      center: [121.65523,31.892831], // 中心坐标
    })
  })

  street.setVisible(false)
  satellite.setVisible(true)

    const modify = new Modify({source: this.source});
      map.addInteraction(modify);
      this.map = map;
      if(this.isEdit){
           this.addInteractions();
      }
      var that = this;
       this.element = document.getElementById('popup');
        this.popup = new Overlay({
          element: this.element,
          positioning: 'bottom-center',
          stopEvent: false,
        });
        this.map.addOverlay(this.popup);
    },
    addInteractions() {
      var that = this
         let draw = new Draw({
          source: this.source,
          type: this.typeSelect,
        });
        draw.on('drawend',that.getLocation,this);
        draw.on('drawstar',that.removeDraw,this);
        //  draw.on('drawstart',that.removeDraw,this);
        this.draw = draw;
        this.map.addInteraction(draw);
        let snap = new Snap({source: this.source});
        this.snap = snap;
        this.map.addInteraction(snap);
      },
      getLocation(evt){
          var feature = evt.feature;
          var geo = feature.getGeometry();
          var cor = geo.getCoordinates();
          this.locations = cor;
      },
      changeAddInteractions(evt) {
         this.map.removeInteraction(this.draw);
         this.map.removeInteraction(this.snap);
         this.addInteractions();
      },
      removeDraw(evt){
          if(this.locations.length > 0){
              this.vector.getSource().clear()
          }
      },
      removeLayer(id){
         var layers = this.pointArry[id];
         this.map.removeLayer(layers);

      },
      addMarker(lnglats,icon,size,id,data,type) {
            let tamarker = new Feature({
                tadata: {
                    sectionId: "point",
                    towerNumber: 22,
                    data: data,
                    type: type
                }, //这里是用来传值用的，在接下来的一章里（事件）中我会讲到。
                geometry: new Point(lnglats) //这里是点坐标的位置，这里要注意fromLonLat
            });
            tamarker.setStyle(
                new Style({
                    image: new Icon({
                        color: "#eee",
                        crossOrigin: "anonymous",
                        src: require("../../assets/images/icons/" + icon), //本地的样式
                        scale:size
                    }),
                },)
            ); //这里是样式
            var markerta = new LayerVec({
                source: new SourceVec({
                    features: [tamarker] //这里放的就是之前的那个点，如果要放置多个点直接push到这里面就行了
                }),
                zIndex:30
            });
            this.pointArry[id]=markerta;
            this.map.addLayer(markerta); //这里是执行，执行之后点就出来了
      },
      addPoints(data,icon,size,type){
        var tamarkerArry =[]
        let tamarker = null
        for(var index in data){
          if(type === 'video'){
                 tamarker = new Feature({
                    tadata: {
                        sectionId: "point",
                        towerNumber: 22,
                        data:data[index],
                        type:type
                    }, //这里是用来传值用的，在接下来的一章里（事件）中我会讲到。
                    geometry: new Point([data[index].longitude, data[index].latitude]) //这里是点坐标的位置，这里要注意fromLonLat
                });
          }else {
                 tamarker = new Feature({
                    tadata: {
                        sectionId: "point",
                        towerNumber: 22,
                        data:data[index],
                        type:type
                    }, //这里是用来传值用的，在接下来的一章里（事件）中我会讲到。
                    geometry: new Point(data[index].fence.split(',')) //这里是点坐标的位置，这里要注意fromLonLat
                });
          }
            tamarker.setStyle(
                new Style({
                    image: new Icon({
                        color: "#eee",
                        crossOrigin: "anonymous",
                        src: require("../../assets/images/icons/" + icon), //本地的样式
                        scale:size,
                        anchor: [0.5, 60],              //锚点
                        anchorOrigin:'top-right',       //锚点源
                        anchorXUnits: 'fraction',       //锚点X值单位
                        anchorYUnits: 'pixels',         //锚点Y值单位
                        offsetOrigin: 'top-right',      //偏移原点
                    }),
                },)
            ); //这里是样式
            tamarkerArry.push(tamarker);
        }

            var markerta = new LayerVec({
                source: new SourceVec({
                    features: tamarkerArry //这里放的就是之前的那个点，如果要放置多个点直接push到这里面就行了
                }),
                zIndex:30
            });
//             markerta.on('mouseover', markerta, function(evt) {
//                     console.log(evt);
//                     popup = new OpenLayers.Popup.FramedCloud("Popup",
//                         new OpenLayers.LonLat(5.6, 50.6),
//                         null,
//                         '<div>Hello World! Put your html here</div>',
//                         null,
//                         false);
//                     this.map.addPopup(popup);
//                 });
// //here add mouseout event
//            markerta.on('mouseout', markerta, function(evt) {popup.hide();});
            // this.pointArry.set(id,markerta);
            this.map.addLayer(markerta); //这里是执行，执行之后点就出来了
            markerta.setVisible(false);
            if(type == 'device'){
                 this.deviceList.push(markerta);
            }else{
                 this.mapHashMap[type]=markerta;
            }
            // markerta.setVisible(true)

      },
        addline: function(lnglats,type) {
            let line = new Feature({
                tadata: {
                    sectionId: "line",
                    towerNumber: 22
                },
                geometry: new LineString(lnglats)
            }); //这里要注意写fromLonLat，很重要
            
            var style =this.getStyle(type);

            line.setStyle(style);

            var linevectorLayer = new LayerVec({
                source: new SourceVec({
                    features: [line] //要绘制多段线，直接push到这里面就行了
                })
            });
              if(type == 'device'){
                 this.deviceList.push(linevectorLayer);
                 linevectorLayer.setVisible(false)
            }
            this.map.addLayer(linevectorLayer); //这里是执行，执行之后点就出来了
        },
         addPolygon(item) {
          var polygon = new Feature({
            geometry: new Polygon(item),
            type: "polygon",
          });
          let style = [
            new Style({
              fill: new Fill({
                color: "rgba(5,96,187,0.2)",
              }),
              // 描边
               stroke: new Stroke({
                  color:"#0560BB",
                  width:3,
                  lineDash:[10,20],
                  lineCap:"butt"
               }),
              zIndex: 10,
            }),
          ];
          polygon.setStyle(style);
           var polygonLayer = new LayerVec({
                source: new SourceVec({
                    features: [polygon]
                })
            });
          this.map.addLayer(polygonLayer);
          this.areaList.push(polygonLayer);
          polygonLayer.setVisible(false)
        },
        initPoint(){
              var pointObj = this.pointObj;
              if(pointObj){
                  if(pointObj.type == 2){
                    this.addMarker(pointObj.locations.split(','),'左侧-车站-高亮.png',0.2,'marker');
                  }
                  if(pointObj.type == 5){
                    this.addMarker(pointObj.locations.split(','),'专家站点.png',0.2,'marker');
                  }


              }
        },
        transpoints: function(points, type) {
            if (false) {
                return points;
            } else {
                if (type == 1) {
                    var pp = [];
                    points.forEach(point => {
                        pp.push(transform(point, "EPSG:3857", "EPSG:4326"));
                    });
                    return pp;
                } else {
                    var pp = [];
                    points.forEach(point => {
                        pp.push(transform(point, "EPSG:4326", "EPSG:3857"));
                    });
                    return pp;
                }
            }
        },
        handleClose(){
            closevideo();
            this.dialogVisible = false
        },
        handleOpen(){
          window.cameraid = this.ccode;
          startPreview(window.cameraid,-1);
        },
        handleChange(value){  
            for(var key in this.mapHashMap){
                 this.mapHashMap[key].setVisible(false)
            }
            for(var index in this.deviceList){
                 this.deviceList[index].setVisible(false)
            }
            for(var index in this.areaList){
                 this.areaList[index].setVisible(false)
            }
            for(var index in value){
              if(value[index] == 'device'){
                    for(var index in this.deviceList){
                         this.deviceList[index].setVisible(true)
                    }
              }else  if(value[index] == 'area'){
                    for(var index in this.areaList){
                         this.areaList[index].setVisible(true)
                    }
              }else{
                var mapkey = value[index]
                if(this.mapHashMap[mapkey]){
                    this.mapHashMap[mapkey].setVisible(true)
                }
              }
            }
        },
        getStyle(type){
          var style =  new Style({
                stroke: new Stroke({
                    width: 3,
                    color: "#008000"
                })
            })
          if(type == 1){
              style =[
                          new Style({
                              stroke: new Stroke({
                                  color:"#000000",
                                  width:6,
                                  lineCap:"butt"
                              }),
                              zIndex:20
                          }),
                          new Style({
                              stroke: new Stroke({
                                  color:"#ffffff",
                                  width:6,
                                  lineDash:[15,15],
                                  lineCap:"butt"
                              }),
                              zIndex:21
                          })
                      ]
          }else if(type == 2){
               style =[
                     new Style({
                          stroke: new Stroke({
                              color:"#000000",
                              width:6,
                              lineDash:[15,45],
                              lineCap:"butt"
                          }),
                          zIndex:20
                      }),
                      new Style({
                          stroke: new Stroke({
                              color:"#ffffff",
                              width:6,
                              lineDash:[15,45],
                              lineDashOffset:30,
                              lineCap:"butt"
                          }),
                          zIndex:21
                      })
                    ]
          }else if(type == 'device'){
               style =new Style({
                          stroke: new Stroke({
                              color:"#07DBFF",
                              width:6,
                              lineDash:[15,45],
                              lineCap:"butt"
                          }),
                          zIndex:20
                      })
          }
             return style;
        }
  }
};
</script>

<style scoped>
#map {
  height: 100%;
}

.iconSelect{
    position: absolute;
    top: 10rem;
    right: 5rem;
    width: 16rem;
    min-height: 30rem;
    background-color: transparent ;
    padding-left:1rem
}

.tipicon{
    width:3rem;
    height:3rem;
    vertical-align: middle;
}
</style>
