<template>
  <div ref="cparent">
    <div id="map" ></div>
    <div class="drawbutton">
      <!-- <el-button type="success" size="mini" @click="saveEdit" v-if="saveEditBtn">保存编辑</el-button>
      <el-button type="primary" size="mini" @click="cancelEdit" v-if="saveEditBtn">取消编辑</el-button> -->

      <el-button type="info" size="mini" @click="removeLayer">删除当前图斑</el-button>
    </div>
    <div class="diacontain">
      <div class="diacontainer" v-if="formsVisible"></div>
      <div class="diabox" v-if="formsVisible">
          <div class="diatitle">
            <div class="flex">
              <span>案件详情</span>
              <i class="el-icon-close" @click="formsVisible = false"></i>
            </div>
          </div>
          <div class="diacontent">
              <formDetail :ruleFormId="ruleFormId" :ruleForm="handleForm" @close="formsVisible = false"></formDetail> 
          </div>
      </div>
    </div>
  </div>

</template>

<script>
import {cun} from './geojson.js';
import waves from '@/directive/waves'
import {loadBaseLayers} from "./layerManage";
import {layerStyle} from "./layerStyle";
import elDragDialog from '@/directive/el-dragDialog'
import WKT, { parse } from "terraformer-wkt-parser"
import {getMethodCommon} from "@/api/common";
import {addIllegalBuildeLayer,updateIllegalBuildeLayer,getDroneGeoJson,loadIllegalBuildeLayerData,loadAllDroneGeoJson,DeleteDroneLayers} from './../../../api/map'
import formDetail from "./formdetail"
import layersInfo from '/public/config.json'
export default {
  name: "index",
  props:["areaData","layersData","toggleLayer","togglevillage","togglehistory"],
  components: {
    formDetail
  },
  directives: {
    waves,
    elDragDialog
  },
  data(){
    return{
      formsVisible: false,
      ruleFormId: '',
      handleForm: [],
      caseData:null,
      saveEditBtn:false,
      reildId:null,
      editData:null,
      editId:null,
      villageLayerGroup:[],
      villageGeoJson:null,
      UAVMarker:null,  //无人机图标
      satelliteLayer:null,  //存放影像图层
      villageLayer:null,//存放村庄图层
      townshipLayer:null,
      villageNames:[],
      map: '',
      updateData:{
        id:'',
        relid:''
      },//加载数据详情
      // tableLayerGroup:{},//图层数据
      drawLayerData:{},//绘制得到的图层
      // drawLayerList:[],//所有图层
      layerId:100,
      openLayersGid: '',
      openLayersDatas: '',
      tclayerDataBeforeEdit:[],
      tclayerData:[],
      listQuery: {
        is_intact:null,
        is_reporter:null,
        is_dealer:null,
        handle_status_id:null,
        report_start_time:'',
        report_end_time:'',
        report_name:'',
        deal_username:'',
        page: 1,
        limit: 20,
        key:''
      },
      total:0,
      polygonArea: ''
    }
  },
  watch: {
    areaData: function (e) {
      if (e) {
        // this.map.removeLayer(this.tclayerData)
        this.currentChange(e)
        this.reildId = e.id;
        this.caseData = e;
        // this.getLayerGeoJson(e)
      } 
    },
    layersData: function(e){
      // this.map.removeLayer(this.tclayerData)
      
      if(this.areaData){
        this.currentChange(this.areaData)
        // this.getLayerGeoJson(this.areaData)
      }
    },
    toggleLayer:function(e){
      if(this.UAVMarker != null){
        if(e == false){
          this.map.addLayer(this.UAVMarker);
        }else if(e == true){
          this.map.removeLayer(this.UAVMarker);
        }
      }
    },
    togglevillage:function(e){
      if(this.townshipLayer != null){
        if(e == true){
          this.map.addLayer(this.townshipLayer);
        }else if(e == false){
          this.map.removeLayer(this.townshipLayer);
        }
      }
    },
    togglehistory: function(e){
      if(this.tclayerData != null){
        if(e == false){
          this.map.addLayer(this.tclayerData);
        }else if(e == true){
          this.map.removeLayer(this.tclayerData);
        }
      }
    }
  },
  
  created(){
    
  },
  mounted(){
    this.mapInit();
    this.showLayers();
    this.$nextTick(() => {
      this.getLayerGeoJson()
    })
  },
  methods:{

    //地图配置
    mapInit() {
      let baseLayers = loadBaseLayers()
      var overlayLayers = {}
      this.map = L.map("map", {
        center: [35.281969,117.8827], // 地图中心
        zoom: 10, //缩放比列
        maxZoom:24,
        zoomControl: false, //禁用 + - 按钮
        doubleClickZoom: false, // 禁用双击放大
        attributionControl: false, // 移除右下角leaflet标识
        crs: L.CRS.EPSG4326, //设置坐标系4326
        layers: [baseLayers["卫星"]],
      });
      this.map.pm.addControls({
        position: "topleft",
        drawCircleMarker:false,//圆
        drawPolygon: true, // 添加绘制多边形
        drawMarker: false, //点
        drawCircleMarker: false, //添加按钮以绘制圆形标记
        drawPolyline: false, //添加按钮绘制线条
        drawRectangle:	false,	//添加按钮绘制矩形
        drawCircle: false, //  添加按钮绘制圆圈
        editMode: false, //  添加按钮编辑多边形
        dragMode: false, //   添加按钮拖动多边形
        cutPolygon: false, // 添加一个按钮以删除图层里面的部分内容
        removalMode: false,  // 清除图层
        splitMode:false,
     
      });
      // L.control.layers(baseLayers, overlayLayers).addTo(this.map);//可以引用多个图层
      this.map.pm.setLang("zh"); //设置语言  en, de, it, ru, ro, es, fr, pt_br, zh , nl
      this.drawCoordinates();//绘制坐标
    },

    currentChange(currentRow,oldCurrentRow){
      if(this.UAVMarker != null){
        this.map.removeLayer(this.UAVMarker);
      }
      this.map.fitBounds([[currentRow.lat,currentRow.lng]],{maxZoom: 18,animate: true});

      // L.marker([currentRow.lat,currentRow.lng]).addTo(this.map)
      let myimage = L.icon({
          iconUrl: require('@/assets/drone_img/icon_fly2.png'), //图片url
          iconSize:[20,20]
      })
      this.UAVMarker = L.marker([currentRow.lat,currentRow.lng],{
          icon: myimage,
          draggable:false
        }).addTo(this.map);
      
    },
    showLayers(data){
      this.map.on("click",function(e){
        
      })
      this.satelliteLayer =  L.tileLayer.wms(layersInfo.layers.imageLayer.url,{
        layers:layersInfo.layers.imageLayer.name,
        format: 'image/png',
        maxZoom:24,
        transparent: true
      }).addTo(this.map);


    //clos
      this.townshipLayer = L.tileLayer.wms(layersInfo.layers.townshipLayer.url, {
                layers: layersInfo.layers.townshipLayer.name,
                style:{
                  color: "blue",
                  fillColor: "blue",
                  fillOpacity: 0,
                  lineWidth:1,
                },
                format: "image/png", //返回的数据格式
                transparent: true,
            }
        );
      // this.townshipLayer = L.tileLayer.wms("http://192.168.10.111:6080/geoserver/test/wms", {
      //         layers: "test:zhenjie",
      //         style:{
      //           color: "blue",
      //           fillColor: "blue",
      //           fillOpacity: 0,
                
      //         },
      //         format: "image/png", //返回的数据格式
      //         transparent: true,
      //     }
      // );
      this.townshipLayer.addTo(this.map);


      this.getVillageGeoJson();


      // this.loadCunName();  

      // 设置村庄名称的显示级别
      // let _this = this;
      // _this.map.on('zoom',function(e){
      //   if(_this.map.getZoom() < 11){
      //     _this.map.removeLayer(_this.villageLayerGroup);
      //   }else{
      //     _this.map.addLayer(_this.villageLayerGroup);
      //   }
      // })
      
    },
    // hideLayers(){
    //   // if(this.satelliteLayer != null){
    //     this.map.removeLayer(this.satelliteLayer);
    //     this.satelliteLayer = null;
    //   // }
    // },
    getVillageGeoJson(){
      this.$axios({
        method:"get",
        url:layersInfo.layers.administrationLayer.url,
      }).then(res=>{
        if(res.status == 200){
          this.villageGeoJson = res.data;
          this.villageLayer = L.geoJSON(this.villageGeoJson, {
              style:{
                color: "blue",
                fillColor: "blue",
                fillOpacity: 0,
              }
            }).bindTooltip(function(e){
              return e.feature.properties.XZQMC;
            });
          }
          this.loadCunName();
      }).catch(error=>{
        // console.log("axioserror",error);
      });
    },
    loadCunName(){
      for(let i = 0;i<this.villageGeoJson.features.length;i++){
        let str = "<div style='font-size:12px;color:#fff;text-shadow:#000 3px 0 0;'>"+this.villageGeoJson.features[i].properties.XZQMC+"</div>"
        let divicon = L.divIcon({
          html:str,
          className:"myDivIcon",
          iconSize:[80],
        });
        let newcor = this.getPolygon(this.villageGeoJson.features[i].geometry.coordinates[0][0]);
        let myMarker = L.marker([newcor[1],newcor[0]],{icon:divicon,maxZoom:20,minZoom:12});
        this.villageNames.push(myMarker);
      }
      // this.villageLayerGroup = L.layerGroup(this.villageNames).addTo(this.map);

    },
    getPolygon(pList) {  //获取多边形中心点
      var area = 0;
      var x = 0;
      var y = 0;
      for (var i = 1; i <= pList.length; i++) {
        var lat = pList[i % pList.length][0];
        var lng = pList[i % pList.length][1];
        var nextLat = pList[i - 1][0];
        var nextLng = pList[i - 1][1];
        var temp = (lat * nextLng - lng * nextLat) / 2;
        area += temp;
        x += (temp * (lat + nextLat)) / 3;
        y += (temp * (lng + nextLng)) / 3;
      }
      x = x / area;
      y = y / area;
      return [x, y];
    },
    drawCoordinates(){
      let _this = this
      // 绘制图形下笔
      this.map.on("pm:drawstart", e => {
        if(!this.areaData){
          this.$message({
            type: 'warning',
            message: '请先操作列表中一条数据'
          });  
          this.map.pm.disableGlobalEditMode();
        }
      });
      // 绘制图形停笔
      this.map.on("pm:drawend", e => {
        // console.log(e, "停止绘制");
      });
      // 绘制完成返回layer  pm:edit 图形编辑/平移
      this.map.on("pm:create", e => {
        _this.updateData.relid
        e.layer.pm.enable({
          preventMarkerRemoval: false
        });
        _this.drawLayerData.layer = e.layer;
        _this.updateData.geom = WKT.convert(_this.drawLayerData.layer.toGeoJSON().geometry);
        
        //计算多边形面积
        let drawArea = _this.drawLayerData.layer.toGeoJSON().geometry.coordinates
        
        let polygons = _this.$turf.polygon(drawArea);
        this.polygonArea = parseFloat(_this.$turf.area(polygons)).toFixed(2) + '㎡';
        // console.log('图斑面积',this.polygonArea)
        let polygonAreaData = {
          polygonArea: this.polygonArea,
          id: this.areaData.id
        }
        this.$emit('polygonArea',polygonAreaData)
        this.$confirm('确定保存此图斑?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.submitForm()
        }).catch(() => {
          this.map.removeLayer(this.drawLayerData.layer);
          polygonAreaData.polygonArea = 0
          this.$emit('polygonArea',polygonAreaData)
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        });

        //把编辑操作写在外面 
         e.layer.on("pm:edit", v => {
            let gemoData = WKT.convert(_this.drawLayerData.layer.toGeoJSON().geometry);
            _this.getLayerData(_this.layerId,gemoData).then(res =>{
              _this.submitUpdate(_this.layerId,gemoData);
            })
          });
          e.layer.on("click", function()  {
            e.layer.pm.enable({
              allowSelfIntersection: false,
            });
          })
          this.map.pm.disableGlobalEditMode();
      });
      // 移除绘制的图形
      this.map.on('pm:remove', e => {
        _this.drawLayerData = {}
      });

      
    },

    //添加数据
    submitForm(){
      this.updateData.relid = this.areaData.id

      addIllegalBuildeLayer(this.updateData).then(res =>{
        if(res.code === 200){
          this.layerId = res.result;
          this.$message({
            type: 'success',
            message: '保存成功!'
          });
        }
      })
    },

    getLayerData(gid){
      return new Promise((resolve,rej)=>{
        loadIllegalBuildeLayerData({gid}).then(res =>{
          if(res.code === 200){
            this.updateData = res.result;
          }
          resolve(111);
        })
      })
    },

    //编辑图层数据
    submitUpdate(id,gid,gemo){
      this.updateData.relid = id;
      this.updateData.gid = gid;
      this.updateData.geom = gemo;
      return new Promise((resolve,reject)=>{
        updateIllegalBuildeLayer(this.updateData).then(res =>{
          if(res.code === 200){
             this.$message({
                  type: 'success',
                  message: '保存成功'
              });
               this.tclayerData.pm.disable();
             this.saveEditBtn = false;
          }
          resolve(111);
        })
      })
    },

    //获取图层信息
    getLayerGeoJson(data){
      this.openLayersGid = ''
      this.openLayersDatas = ''
      return new Promise((res,rej) =>{
        loadAllDroneGeoJson().then(res =>{
          if(res.code === 200){
            console.log("getGeojson",res);
              L.geoJSON().clearLayers().addTo(this.map); 
              let layer = L.geoJSON(res.result, {
                ...layerStyle.selectLayerGroup.style
              })
              // layer.addTo(this.map)
              this.tclayerDataBeforeEdit = layer;
              this.tclayerData = layer
              this.bindLayerEdit(layer)
          }
        })
      })

    },
    bindLayerEdit(layer) {
      layer.on("click", (e) => {
        let gid = e.layer.feature.properties.gid
        let relid = e.layer.feature.properties.relid
        this.openLayersGid = gid
        this.openLayersDatas = e
        // this.tclayerData.pm.enable();
        // this.saveEditBtn = true;
        this.getFormData(relid)
      })
      this.tclayerData.on("pm:edit",(e)=>{
        // console.log(e);
        this.editId = e.layer.feature.properties.gid;
        this.editData = WKT.convert(e.layer.toGeoJSON().geometry);
      })
    },
    getFormData(relid){
        getMethodCommon('/DroneCaseinfo/GetCaseInfo',{id: relid}).then(res => {
         
            this.handleForm = res.result.info
            //  console.log("ressss",this.handleForm)
            this.ruleFormId = res.result.info.id
            this.formsVisible = true
        })
    },
    saveEdit(){

      if(this.editData !=null && this.editId !=null){
        this.submitUpdate(this.reildId,this.editId,this.editData);

      }
      
    },
    cancelEdit(){
       this.saveEditBtn = false;
      this.map.removeLayer(this.tclayerData);
      this.tclayerData = [];
      this.getLayerGeoJson(this.caseData);
      this.map.addLayer(this.tclayerData);
      this.tclayerData.pm.disable();
     
    },
    removeLayer(){
      this.formsVisible = false
      if(!this.openLayersGid){
        this.$message({
            type: 'info',
            message: '请选择需删除的图斑'
        });
        return    
      }
      this.$confirm('确定删除此图斑？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.delLayer(this.openLayersGid)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    delLayer(id){
      DeleteDroneLayers({gid:id}).then(res =>{
        if(res.code === 200){
            this.$message({
              type: 'success',
              message: '删除成功'
            });   
            this.map.removeLayer(this.openLayersDatas.layer)
        }
      })
    }
        
  }
  
}
</script>

<style scoped>
.myDivIcon{

}
.diacontain{
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
}
.diacontainer{
  width: 100%;
  height: 100%;
  background: #000;
  opacity: 0.5;
  position: absolute;
  top:0;
  left: 0;
  z-index: 99999;
}
.diabox{
  width: 600px;
  height: 820px;
  position: absolute;
  left: 50%;top: 50%;
  margin-left: -300px;
  margin-top: -455px;
  background: #fff;
  border-radius: 5px;
  z-index: 99999;
  overflow: hidden;
}
.diabox .diatitle{
  height: 35px;
  line-height: 35px;
  border-bottom: 1px solid #eee;
  padding: 0 20px;
  background: #f8f8f8;
}
.diabox .diatitle .flex{
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.diabox .diatitle span{
  font-size: 14px;
  color: #333;
}
.diabox .diatitle i{
  font-size: 14px;
  color: #0a76a4;
  cursor: pointer;
}
.diabox .diacontent{
  height: 785px;
  padding: 10px;
  font-size: 14px;
  overflow: hidden;
}
#map {
  width: 100%;
  height: 100vh;
  z-index: 1;
}
.editDialogClass{
  width: 300px;
  height: 500px;
  color: #fff;
  top:50px;
  background: rgba(17,26,25,0.6);
  overflow-y: hidden;
  position: absolute;
}
.editDialogClass .el-dialog__header{
  color: #fff;
  background-color: rgba(17,26,25,0.9);
}
.editDialogClass .el-dialog__title{
  color: #fff;
  background-color: rgba(17,26,25,0.9);
}
.editDialogClass .el-dialog__body{
  color: #fff;
  background-color: rgba(17,26,25,0.9);
}
.drawbutton{
  position: absolute;
  right: 50px;
  top: 10px;
  z-index: 99;
}
</style>
