<template>
<div style="width:100%;height:100%;background:rgb(48,65,85)">
  <div id="map">
    <div class="optionsBtn">
      <el-tooltip class="item" effect="dark" content="保存图斑" placement="right">
        <div @click="saveFeatures" v-if="btnType == 'add'" ><img src="~@/assets/icon/save.png" alt=""></div>
        <div @click="updateFeatures" v-if="btnType == 'edit'" ><img src="~@/assets/icon/save.png" alt=""></div>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="重新绘制" placement="right">
        <div @click="resetFeatures"><img src="~@/assets/icon/reset.png" alt=""></div>
      </el-tooltip>
    </div>
    <div class="layerBtn">
      <el-tooltip class="item" effect="dark" content="无人机" placement="right">
        <div @click="toggleDroneMarker">
          <img src="~@/assets/drone_img/drone.png" v-if="!droneButtonActive" alt="">
          <img src="~@/assets/drone_img/drone_active.png" v-if="droneButtonActive" alt="">
        </div>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="历史案件" placement="right">
        <div @click="toggleHistoryLayer"> 
          <img src="~@/assets/drone_img/history.png" v-if="!historyButtonActive" alt="">
          <img src="~@/assets/drone_img/history_active.png" v-if="historyButtonActive" alt="">
        </div>
      </el-tooltip>
      <el-tooltip class="item" effect="dark" content="乡镇边界" placement="right">
        <div @click="togglevillage">
          <img src="~@/assets/drone_img/village.png" v-if="!villageButtonActive" alt="">
          <img src="~@/assets/drone_img/village_active.png" v-if="villageButtonActive" alt="">
        </div>
      </el-tooltip>
    </div>
  </div>
  <el-dialog width="1366px" height="690px" top="60px"
              class="dialog-mini body-small addWindow"
              v-el-drag-dialog
              :title="'案件详情'"
              :close-on-click-modal="false"
              :close-on-press-escape="false"
              :visible.sync="eventDetailVisible"
              >
    <el-container style="width:1350px;height:690px;overflow-y:hidden;">
      <el-container v-if="eventDetailVisible">
        <eventDetailnForm :caseDetailId="caseDetailId"></eventDetailnForm> 
      </el-container>
    </el-container>
  </el-dialog>
</div>
</template>
<script>
//引入
import waves from '@/directive/waves' // 水波纹指令
import elDragDialog from '@/directive/el-dragDialog'
import eventDetailnForm from '../../map/widget/detail.vue'
import MapboxDraw from "@mapbox/mapbox-gl-draw";
import StaticMode from '@mapbox/mapbox-gl-draw-static-mode';
import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css';
import appConfig from '../../../../public/config.json'
import {getMethodCommon} from '@/api/common'
import { postMethodCommon } from '../../../api/common';
import WKT, { parse } from "terraformer-wkt-parser"
  // import {DrawAreaControl} from "gykj-map-core"
const BASE_URL = process.env.VUE_APP_BASE;
  const modes = MapboxDraw.modes;
	modes.static = StaticMode;

export default {
  name:"Map",
  props:["ruleForm"],
  components:{eventDetailnForm},
  data(){
    return {
      droneButtonActive:true,
      historyButtonActive:false,
      villageButtonActive:true,
      btnType:'add',
      globalMap:null,
      summaryArray:[],
      townships:[
            {
                name:"探沂镇",
                coordinate:[118.123866,35.210054],
                color:"rgb(84,112,198,0.8)",
            },{
                name:"胡阳镇",
                coordinate:[118.115661,35.297313],
                color:"rgb(145,204,117,0.8)"
            },{
                name:"上冶镇",
                coordinate:[117.934961,35.372073],
                color:"rgb(250,200,88,0.8)",
            },{
                name:"薛庄镇",
                coordinate:[118.092556,35.364575],
                color:"rgb(238,102,102,0.8)"
            },{
                name:"朱田镇",
                coordinate:[117.841782,35.272331],
                color:"rgb(115,192,222,0.8)"
            },{
                name:"梁邱镇",
                coordinate:[117.737143,35.163698],
                color:"rgb(59,162,114,0.8)"
            },{
                name:"新庄镇",
                coordinate:[117.883076,35.099535],
                color:"rgb(252,132,82,0.8)"
            },{
                name:"马庄镇",
                coordinate:[117.98465,35.144434],
                color:"rgb(154,96,180,0.8)"
            },{
                name:"费城街道",
                coordinate:[117.975684,35.279222],
                color:"rgb(14,59,201,0.8)",
            },{
                name:"石井镇",
                coordinate:[117.754297,35.081906],
                color:"rgb(132,139,161,0.8)"
            },{
                name:"东蒙镇",
                coordinate:[118.013781,35.38787],
                color:"rgb(235,51,163,0.8)"
            },{
                name:"大田庄乡",
                coordinate:[117.969247,35.481575],
                color:"rgb(182,183,233,0.8)",
            }
      ],
      draw: new MapboxDraw({
					displayControlsDefault: false,
					controls: {
						polygon: true,
						trash: true
					},
					modes: modes
				}),
      // geojson: {
      //   features: [],
      //   type: "FeatureCollection"
      // },
      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.globalMap.flyTo({
          center: [e.lng,e.lat], // 中心点
          zoom: 20, // 缩放比例
          pitch: 0 // 倾斜度
        })
        this.loadDroneMarker(e.lng,e.lat);
      }
    },
    '$store.state.app.sidebar.opened':function(e){
      let _this = this;
      setTimeout(function(){
        if(_this.globalMap != null){
          _this.globalMap.resize();
        }
      },300)
    }
  },
  mounted(){
    this.loadMap();
  },
  methods:{
    togglevillage(){
      if(this.globalMap.getLayoutProperty('street-border', "visibility")=='visible'){
        this.globalMap.setLayoutProperty('street-border', "visibility", "none");
      }else{
        this.globalMap.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.globalMap);
        }
      }
      this.droneButtonActive = !this.droneButtonActive;
    },
    toggleHistoryLayer(){
      if(this.globalMap.getLayoutProperty('historyLayerVector', "visibility")=='visible'){
        this.globalMap.setLayoutProperty('historyLayerVector', "visibility", "none");
        this.globalMap.setLayoutProperty('historyLayerVector-line', "visibility", "none");
      }else{
        this.globalMap.setLayoutProperty('historyLayerVector', "visibility", "visible");
        this.globalMap.setLayoutProperty('historyLayerVector-line', "visibility", "visible");
      }
      this.historyButtonActive = !this.historyButtonActive;
    },
    getStreetCaseCount(){
      getMethodCommon("/api/DroneScreenDisplay/GetDroneOrgCount").then(res=>{

      })
    },
    loadMap(){
      this.$mapboxgl.accessToken = "pk.eyJ1Ijoic2hpY2hhbzEyMyIsImEiOiJja3FobnI1aDEwNGF6Mm9vOXVhNnBzZmFhIn0.2fZKiMqCQHxVY74QShMEGQ";
      this.globalMap = new this.$mapboxgl.Map({
        container: 'map',
        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.globalMap.on("load",function(){
        _this.loadLayer();
        _this.loadImageLayer();
        _this.loadStreetBorderLayer();
        // _this.loadHistoryLayer();
        _this.loadHistoryLayerVector();

        _this.globalMap.on("click","historyLayerVector",(e)=>{
                
                console.log(e.features[0].properties.Id);
                if(e.features[0].properties.Id){
                  _this.caseDetailId = e.features[0].properties.Id;
                  _this.eventDetailVisible = true;
                }
              })

        _this.globalMap.addControl(_this.draw, 'top-right');

        // if(_this.geojson.features.length){
        //   _this.geojson.features.forEach((item,index)=>{
        //     _this.draw.add(item);
        //   })
        // }
        
        
        _this.globalMap.on('draw.create', function(e){
          
         
          _this.handleMultiPolygan();
        })

        _this.globalMap.on('draw.update', function(e){
         _this.handleMultiPolygan();
        })
      
				_this.globalMap.on('draw.delete',function(e){
          _this.handleMultiPolygan();
        });

				// _this.globalMap.on('draw.update', _this.updateArea());

        // // let layerid = _this.draw.add(_this.geojson);
        // console.log("mode",_this.draw.getMode());

      })
    },
    updateArea() {
				this.geojson = this.draw.getAll();
        console.log(this.geojson);
		},
    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.globalMap);
          }
        }
      })
        
    },
    loadStreetBorderLayer(){
      this.globalMap.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"
		    },
      });
    },
    loadImageLayer(){
      this.globalMap.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.globalMap.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.globalMap.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.globalMap);
    },
    loadCaseGeoJson(){
      getMethodCommon('/DroneCaseinfo/GetDroneGeoJson',{id:this.ruleForm.id}).then(res =>{
				if(res.code == 200){
         this.geojson = res.result;
              let _this = this;
              _this.draw.deleteAll();
            console.log(res);
              if(_this.geojson.features.length>0){
                _this.formData = _this.geojson.features[0].properties;
                _this.btnType = "edit";
              }else{
                _this.btnType = "add";
              }

            if(_this.geojson.features.length){
                _this.geojson.features[0].geometry.coordinates.forEach((item,index)=>{
                  console.log("item",item);
                  let obj = {
                    geometry:{
                      type:"Polygon",
                      coordinates:item,
                    },
                    properties:{},
                    type:"Feature",
                  };
                  _this.draw.add(obj);
                })
            }
        }
			})
    },
    loadHistoryLayerVector(){
        this.globalMap.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.globalMap.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.globalMap.remove();
    this.globalMap = null;
  }
}
</script>
<style scoped>
#map{
  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;
}
</style>