<template>
<div style="width:100%;height:100%;background:rgb(48,65,85)">
  <div id="map-detail" style="width:100%;height:100%;">

  </div>
</div>
</template>
<script>
//引入
import waves from '@/directive/waves' // 水波纹指令
import elDragDialog from '@/directive/el-dragDialog'
import appConfig from '../../../../public/config.json'
import {getMethodCommon} from '@/api/common'
import { postMethodCommon } from '../../../api/common';
const BASE_URL = process.env.VUE_APP_BASE;

export default {
  name:"Map",
  props:["ruleForm"],
  components:{},
  data(){
    return {
      droneButtonActive:true,
      historyButtonActive:false,
      villageButtonActive:true,
      btnType:'add',
      globalMapDetail:null,
      summaryArray:[],
      geojson:{ },
      formData:{},
      droneMarker:null,   
      eventDetailVisible:false,
      caseDetailId:null,
    }
  },
  directives: {
    waves,
    elDragDialog
  },
  watch:{

    'ruleForm':function(e){
      // this.loadCaseGeoJson();
      // console.log("ruleForm",e);
      // 如果对象不为空
      if(JSON.stringify(e) != "{}"){
        this.globalMapDetail.flyTo({
          center: [e.lng,e.lat], // 中心点
          zoom: 18, // 缩放比例
          pitch: 0 // 倾斜度
        })
        this.loadDroneMarker(e.lng,e.lat);
      }
    },
    '$store.state.app.sidebar.opened':function(e){
      let _this = this;
      setTimeout(function(){
        if(_this.globalMapDetail != null){
          _this.globalMapDetail.resize();
        }
      },300)
    }
  },
  mounted(){
    this.loadMap();
  },
  methods:{
    togglevillage(){
      if(this.globalMapDetail.getLayoutProperty('street-border', "visibility")=='visible'){
        this.globalMapDetail.setLayoutProperty('street-border', "visibility", "none");
      }else{
        this.globalMapDetail.setLayoutProperty('street-border', "visibility", "visible");
      }
      this.villageButtonActive = !this.villageButtonActive;
    },
    toggleDroneMarker(){
      if(this.droneButtonActive == true){
        if(this.droneMarker!=null){
          this.droneMarker.remove();
        }
      }else{
        if(this.droneMarker!=null){
          this.droneMarker.addTo(this.globalMapDetail);
        }
      }
      this.droneButtonActive = !this.droneButtonActive;
    },
    toggleHistoryLayer(){
      if(this.globalMapDetail.getLayoutProperty('historyLayerVector', "visibility")=='visible'){
        this.globalMapDetail.setLayoutProperty('historyLayerVector', "visibility", "none");
        this.globalMapDetail.setLayoutProperty('historyLayerVector-line', "visibility", "none");
      }else{
        this.globalMapDetail.setLayoutProperty('historyLayerVector', "visibility", "visible");
        this.globalMapDetail.setLayoutProperty('historyLayerVector-line', "visibility", "visible");
      }
      this.historyButtonActive = !this.historyButtonActive;
    },
    getStreetCaseCount(){
      getMethodCommon("/api/DroneScreenDisplay/GetDroneOrgCount").then(res=>{

      })
    },
    loadMap(){
      
      // let worldMapContainer1 = document.getElementById('map');
      // worldMapContainer1.style.height="560px";
      // worldMapContainer1.style.width="1200px";

      this.$mapboxgl.accessToken = "pk.eyJ1Ijoic2hpY2hhbzEyMyIsImEiOiJja3FobnI1aDEwNGF6Mm9vOXVhNnBzZmFhIn0.2fZKiMqCQHxVY74QShMEGQ";
      this.globalMapDetail = new this.$mapboxgl.Map({
        container: 'map-detail',
        zoom: 10.5,
        style: {
          glyphs: "mapbox://fonts/mapbox/{fontstack}/{range}.pbf",
          "version": 8,
          "sources": {
            "raster-tiles": {
              "type": "raster",
              "tiles": ['http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk='+appConfig.appInfo.tiandituKey],
              "tileSize": 256,
            },
             "raster-tiles-l": {
              "type": "raster",
              "tiles": ['http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk='+appConfig.appInfo.tiandituKey],
              "tileSize": 256,
            }
          },
          "layers": [
            {
            "id": "tdt-img-tiles",
            "type": "raster",
            "source": "raster-tiles",
            "minzoom": 0,
            "maxzoom": 22
          },
          // {
          //   "id": "tdt-img-tiles-l",
          //   "type": "raster",
          //   "source": "raster-tiles-l",
          //   "minzoom": 0,
          //   "maxzoom": 22
          // }
          ]
        },
        maxZoom: 22,
        minZoom: 5,
        center: [117.84714891969796,35.22152309532066],
        pitch: 35,
      })
      let _this = this;
      this.globalMapDetail.on("load",function(){
        // _this.loadLayer();
        // _this.loadDroneMarker(e.lng,e.lat);
         
        _this.loadCaseGeoJson();
        _this.loadImageLayer();
        _this.loadStreetBorderLayer();
        _this.globalMapDetail.resize();
      })
    },
    updateArea() {
				this.geojson = this.draw.getAll();
		},
    loadLayer(){
      let townsCount = [];
      getMethodCommon("/DroneScreenDisplay/GetDroneOrgCount").then(res=>{
        if(res.code == 200){
          console.log("rrrrr",res.result);
          townsCount = res.result;
          for(let t =0;t<this.townships.length;t++){
           
              let arr = townsCount.filter((item,index)=>{
                return item.name == this.townships[t].name
              })
              console.log("arrrr",arr)
              let townshipContainer = document.createElement('div');
              townshipContainer.className = 'townshipParent';

              var townshipChildren = document.createElement("div");
              townshipChildren.className = 'townshipChildren';

              let mytext = document.createTextNode(this.townships[t].name+" ："+arr[0].reportCount+"条");
              // let mytext = document.createTextNode(this.townships[t].name);
              townshipChildren.appendChild(mytext);

              townshipContainer.appendChild(townshipChildren);
              townshipContainer.style.width="70px";
              townshipContainer.style.height="70px";
              townshipContainer.style.backgroundColor=this.townships[t].color;
              
              townshipContainer.style.borderRadius="50%";
              townshipContainer.style.color="#fff";
              townshipContainer.style.paddingTop="16px"
              townshipContainer.style.fontSize="12px";
              townshipContainer.style.lineHeight="24px"
              townshipContainer.style.textAlign="center"

              let township =  new this.$mapboxgl.Marker(townshipContainer).setLngLat(this.townships[t].coordinate);
              township.addTo(this.globalMapDetail);
          }
        }
      })
        
    },
    loadStreetBorderLayer(){
      this.globalMapDetail.addLayer({
        'id': 'street-border',
        'type': 'raster',
        'source': {
          'type': 'raster',
          'tiles': ['http://175.27.168.120:8080/geoserver/feixian/wms?service=WMS&version=1.1.0&request=GetMap&layers=feixian:zhenjie&styles=&bbox={bbox-epsg-3857}&width=256&height=256&srs=EPSG:3857&format=image/png&TRANSPARENT=TRUE'],
          'tileSize': 256
        },
        'paint': {},
        'layout': {
		        "visibility":"visible"
		    },
      });
      this.globalMapDetail.resize();
    },
    loadImageLayer(){
      this.globalMapDetail.addLayer({
        'id': 'wms-test-layer',
        'type': 'raster',
        'source': {
          'type': 'raster',
          'tiles': ['http://175.27.168.120:8080/geoserver/feixian/wms?service=WMS&version=1.1.0&request=GetMap&layers=feixian:yingxiang&styles=&bbox={bbox-epsg-3857}&width=256&height=256&srs=EPSG:3857&format=image/png&TRANSPARENT=TRUE'],
          'tileSize': 256
        },
        'paint': {}
        });
    },
    loadHistoryLayer(){
      getMethodCommon("/DroneCaseinfo/LoadAllDroneGeoJson").then(res =>{
        if(res.code == 200){
          let historyGeoJson = res.result;
          console.log("historyGeoJson",historyGeoJson)
              
              this.globalMapDetail.addLayer({
              	"id": "historyLayer-fill",
              	"type": "fill",
              	"source": {
                  "type": "geojson",
                  "data":historyGeoJson
              	},
              	'layout': {
                    "visibility":"none",
                },
                'paint': {
                    "fill-color": "#FE9003",
                    "fill-opacity": 0.2,
                    "fill-outline-color": "#FE9003"
                }
              });


          		this.globalMapDetail.addLayer({
              	"id": "historyLayer",
              	"type": "line",
              	"source": {
                  "type": "geojson",
                  "data":historyGeoJson
              	},
              	'layout': {
                    "visibility":"none",
                    'line-join': 'round',
                    'line-cap': 'round'
                },
                'paint': {
                    'line-color':'#FE9003',
                    'line-width': 3
                }
              });

             
        }
      })
    },
    loadDroneMarker(lng,lat){
      if(this.droneMarker != null){
        this.droneMarker.remove();
      }
      let el = document.createElement('div');
      el.className='droneContainer';
      el.style.width='30px';
      el.style.height='30px';
      // el.style.backgroundColor="#ff0000";
      el.style.backgroundImage="url(/image/icon_fly2.png)";
      el.style.backgroundSize="30px 30px";
      this.droneMarker = new this.$mapboxgl.Marker(el).setLngLat([lng,lat]).addTo(this.globalMapDetail);
    },
    loadCaseGeoJson(){
      getMethodCommon('/DroneCaseinfo/GetDroneGeoJson',{id:this.ruleForm.id}).then(res =>{
				if(res.code == 200){
         this.geojson = res.result;
         if(this.geojson.features.length==0){
           this.globalMapDetail.addLayer({
              "id": "points",
              "type": "symbol",
              "source": {
                "type": "geojson",
                "data": {
                  "type": "FeatureCollection",
                  "features": [{
                      "type": "Feature",
                      "geometry": {
                      "type": "Point",
                      "coordinates": [this.ruleForm.lng,this.ruleForm.lng]
                      },
                      "properties": {
                        "title": "Mapbox DC",
                        "icon": "monument"
                      }
                    }]
                }
              },
              "layout": {
              
              }
            });
         }
           this.globalMapDetail.addLayer({
            'id': 'geojsonfill',
            'type': 'fill',
            'source': {
                type: 'geojson',
                data:this.geojson
              },
              // 'filter': ['==', 'isState', true],
              'layout':{
                // 'visibility':"none"
              },
              'paint': {
                  "fill-color": "#FE9003",
                  "fill-opacity": 0.2,
                  "fill-outline-color": "#FE9003"
              }
          })
           this.globalMapDetail.addLayer({
            'id': 'geojsonline',
            'type': 'line',
            'source': {
                type: 'geojson',
                data:this.geojson
              },
              // 'filter': ['==', 'isState', true],
              'layout':{
                // 'visibility':"none"
                "line-join": "round",
                "line-cap": "round"
              },
              'paint': {
                "line-color": "#FE9003",
                "line-width": 4
                  // "fill-color": "#FE9003",
                  // "fill-opacity": 0.2,
                  // "fill-outline-color": "#FE9003"
              }
          })
        }
			})
    },
    loadHistoryLayerVector(){
        this.globalMapDetail.addLayer({
          'id': 'historyLayerVector',
          'type': 'fill',
          'source': {
              type: 'vector',
              tiles: [BASE_URL+'/api/DroneCaseinfo/QueryVectorTileByTable?z={z}&x={x}&y={y}&table=view_drone_shp_data&field=\"Id\",&X-Token='+localStorage.getItem("X-Token")],
              minzoom: 1,
              maxzoom: 20
                    },
            "source-layer": "view_drone_shp_data",
            // 'filter': ['==', 'isState', true],
            'layout':{
              'visibility':"none"
            },
            'paint': {
                "fill-color": "#FE9003",
                "fill-opacity": 0.2,
                "fill-outline-color": "#FE9003"
            }
        })

        this.globalMapDetail.addLayer({
          'id': 'historyLayerVector-line',
          'type': 'line',
          'source': {
              type: 'vector',
              tiles: [BASE_URL+'/api/DroneCaseinfo/QueryVectorTileByTable?z={z}&x={x}&y={y}&table=view_drone_shp_data&X-Token='+localStorage.getItem("X-Token")],
              minzoom: 1,
              maxzoom: 20
                    },
            "source-layer": "view_drone_shp_data",
            'layout': {
                  'line-join': 'round',
                  'line-cap': 'round',
                  'visibility':"none"
              },
              'paint': {
                  'line-color':'#FE9003',
                  'line-width': 3
              }
        })
    },
    handleMultiPolygan(){
      let _this  = this;
      let allGeoJson = _this.draw.getAll().features;

      let area = 0;
      if(allGeoJson.length>0){
        allGeoJson.forEach((item,index)=>{
          let polygons = _this.$turf.polygon(item.geometry.coordinates);
          console.log("area",_this.$turf.area(polygons));
          area+=this.$turf.area(polygons);
        })
        
      }else{
         let area = 0
      }
      _this.$emit("setArea",area.toFixed(2));
         
      if(allGeoJson.length>0){
        let multiPolygon = "MULTIPOLYGON (";
        allGeoJson.forEach((item,index)=>{
          let polygon = WKT.convert(item.geometry)
          console.log(polygon);
          if(polygon.indexOf("(((") > 0){
            polygon = polygon.substring(polygon.indexOf("((")+1,polygon.length-1);
          }else{
            polygon = polygon.substring(polygon.indexOf("(("));
          }
          
          if(index != allGeoJson.length-1){
            multiPolygon = multiPolygon+polygon+",";
          }else{
            multiPolygon = multiPolygon+polygon;
          }
        })
        
        multiPolygon= multiPolygon+")";
        console.log(multiPolygon);
        return multiPolygon;
      }else{
        let multiPolygon = "";
        return multiPolygon;
      }
      
    },
    saveFeatures(){
      if(JSON.stringify(this.ruleForm)=="{}" || this.ruleForm == null){
        return;
      }
      let data = {
        relid:this.ruleForm.id,
        geom:this.handleMultiPolygan()
      }
      console.log(data);
      if(data.geom){
        postMethodCommon("/DroneCaseinfo/AddIllegalBuildeLayer",data).then(res=>{
          if(res.code == 200){
            this.$message({
              type:"success",
              message:"保存成功",
            })
          }
        })
      }else{
        this.$message({
          type:"error",
          message:"图斑不能为空",
        })
      }
      
    },
    updateFeatures(){
      if(JSON.stringify(this.ruleForm)=="{}" || this.ruleForm == null){
        return;
      }
      let data = {
        relid:this.ruleForm.id,
        gid:this.formData.gid,
        geom:this.handleMultiPolygan()
      }
     
      console.log(data);
      if(data.geom){
        postMethodCommon("/DroneCaseinfo/UpdateIllegalBuildeLayer",data).then(res=>{
          if(res.code == 200){
            this.$message({
              type:"success",
              message:"保存成功",
            })
          }
        })
      }else{
        this.$message({
          type:"error",
          message:"图斑不能为空",
        })
      }
      
    },
    resetFeatures(){
      if(JSON.stringify(this.ruleForm)=="{}" || this.ruleForm == null){
        return;
      }
      this.loadCaseGeoJson();
    }

  },
  destroyed(){
    // this.globalMapDetail.remove();
    // this.globalMapDetail = null;
  }
}
</script>
<style scoped>
#map-detail{
 width:100%;
 height:100%;
}
.townshipParent{
  width:80px;
  height:80px;
  color:#fff;
}
.townshipChildren{
   width:80px;
  height:80px;
  color:#fff;
}
.optionsBtn{
  width:30px;
  height:60px;
  position:absolute;
  right:10px;
  background:#fff;
  box-shadow: 0 0 0 2px rgb(0 0 0 / 10%);
  top:100px;
  border-radius:3px;
  z-index:999999999;
}
.optionsBtn div{
  width:29px;
  height:29px;
  line-height:29px;
  text-align: center;
}
.optionsBtn div:last-child{
  border-top:1px solid #ccc;
}
.optionsBtn div:hover{
  background:rgba(0,0,0,0.2);
}
.optionsBtn div img{
  width:16px;
}
.layerBtn{
  width:38px;
  height:150px;
  position:absolute;
  top:200px;
  right:4px;
  z-index:9999;
}
.layerBtn div{
  width:30px;
  height:38px;
  text-align: center;
  line-height:50px;
}

.layerBtn div img{
  width:30px;
  height:30px;
}
.droneContainer{
  width:100px;
  height:100px;
  background:'#ff0000';
  background-image: url('../../../assets/drone_img/icon_fly2.png');
}
.townshipChildren{
  font-size:12px;
  color:#ff0000;
}

::v-deep .mapbox-ctrl{display: none !important}

::v-deep .mapboxgl-ctrl-logo{
  display: none !important;
}
</style>