<template>
    <div class="editor-map-about-container">
          <div class="map-search-container">
            <el-input 
              prefix-icon="el-icon-search" 
              v-model="areaSearch" 
              style="width:250px;margin-right:12px;" 
              size="small" 
              clearable 
              placeholder="请输入搜索的地名" 
              @keyup.enter.native="searchArea()" 
            ></el-input>
            
            <el-button type="primary" icon="el-icon-search" size="small"  @click="searchArea()">查询</el-button>
            <div class="search-result" v-if="searchResult.length>0 && areaSearch">
              <div class="search-result-item" v-for="(item,index) in searchResult" :key="index" @click="toSearchWhere(item)">
                <span>{{item.name}}</span>
                <span style="font-size:12px;color:#ccc;margin-left:8px;">{{item.address}}</span>
                <!-- <span style="float:right;margin-top:6px;"><i class="el-icon el-icon-map-location"></i></span> -->
              </div>
             
            </div>
          </div>
          <!-- 图层按钮组 -->
          <div class="layer-container">
            <div class="layer-button" @click="toggleLayer('tiandituzhuji')" :style="{'background':layerShow['tiandituzhuji'] == 'visible'?'#108eff':'none','color':layerShow['tiandituzhuji'] == 'visible'?'#fff':'#108eff'}"> <i class="el-icon el-icon-circle-check"></i> 电子底图</div>
            <div class="layer-button"  @click="toggleLayer('gaoqingyingxiang')" :style="{'background':layerShow['gaoqingyingxiang'] == 'visible'?'#108eff':'none','color':layerShow['gaoqingyingxiang'] == 'visible'?'#fff':'#108eff'}"> <i class="el-icon el-icon-circle-check"></i> 高清影像</div>
            <div class="layer-button"  @click="toggleLayer('xianjie')" :style="{'background':layerShow['xianjie'] == 'visible'?'#108eff':'none','color':layerShow['xianjie'] == 'visible'?'#fff':'#108eff'}"> <i class="el-icon el-icon-circle-check"></i> 费县县界</div>
          </div>
          <div id="mapEditorContainer" class="map-container">

          </div>
          <div class="form-container" >
            <div class="description-container">
                <el-form ref="form" :inline="true" label-position="top" label-width="100" size="small" >
                    <el-form-item v-for="(item,index) in columnData" :key="index" :label="item.label" >
                        <el-input v-model="formData[item.label]"  style="min-width:280px;"></el-input>
                    </el-form-item>

                    <br/>
                    <el-form-item size="mini" style="position:absolute;bottom:0px;width: calc( 100% - 40px);text-align:right;border-top:1px solid #108eff;padding:15px 0px;">
                        <div style="">
                            <el-button icon="el-icon el-icon-circle-close" @click="$emit('cancle')">取消</el-button>
                        <el-button type="primary" icon="el-icon el-icon-folder-checked" @click="save()">保存</el-button>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            
          </div>
        </div>
</template>
<script>
import axios from 'axios'
import MapboxDraw from "@mapbox/mapbox-gl-draw"
// import '@mapbox/mapbox-gl-draw/dist/mapbox-gl-draw.css'
// import 'mapbox-gl/dist/mapbox-gl.css';

import { postMethodCommon } from '../../../api/Api'
import WKT from 'terraformer-wkt-parser'

import * as turf from '@turf/turf'

export default {
    name:"Editor",
    props:["currentViewer","columnData","currentData","layerInfo","editType"],
    data(){
        return {
            attributeInfo:{
            "name": "2020年智能语音卡口监控点",
            "position": "东蒙镇贺乐石",
            "street": "东蒙镇",
            "lng": 118.0075,
            "lat": 35.42222222
            },
            formLable:['name', 'position', 'street', 'lng', 'lat'],
            globalMap:null,
            draw:null,
            customIcon:{
                iconUrl: 'https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png',
                iconSize: [40, 40], // 图标大小
                iconAnchor: [20, 20] // 图标锚点
            },
            layerShow:{
                tiandituzhuji:"visible",
                gaoqingyingxiang:"visible",
                xianjie:"visible"
            },
            areaSearch:null,//地名搜索关键字
            searchResult:[],
            geojson:{},
            formData:{},
        }
    },
    watch:{
        areaSearch(newVal,oldVal){
            if(newVal == null || newVal == ""){
            
                this.searchResult = [];
            }
        }
    },
    created(){
        if(this.editType == "edit"){
            this.getWkt();
        }
        this.formData = {...this.currentData}

        console.log("formData",this.formData);
    },
    mounted(){
        let _this = this;
        setTimeout(function(){
            _this.initMap();
        },500)
    },
    destroyed() {
        this.globalMap.remove()
    },
    methods:{
        getWkt(){
            postMethodCommon("/geoserver/transWkb",{geom:this.currentData.geom}).then(res=>{
                if(res.data.code == 200){
                    console.log(res.data.msg);
                    this.geojson = WKT.parse(res.data.msg);
                }
            })
        },
        save(){
            console.log("this.geojson",this.geojson);
            // let geom = WKT.convert(this.geojson.geometry);
            
            // this.formData.geom = geom;
            this.formData.geom = "MULTIPOLYGON (((117.92952273 35.37143486000007, 117.92947982000007 35.37134366000003, 117.92916052000008 35.37141554000004, 117.9292263200001 35.37156699000007, 117.92943120000005 35.371514890000064, 117.92954922 35.371483290000064, 117.92955761000005 35.37148104000004, 117.92952273 35.37143486000007)))"

            let saveFormData = {
               ...this.formData
            }

            saveFormData.tableName = this.layerInfo.tableName
            saveFormData.spaceType = this.layerInfo.spaceType

            if(this.editType == "edit"){
                postMethodCommon("/geoserver/updateLayerData",saveFormData).then(res=>{
                    if(res.data.code == 200){
                        this.$message({
                            type:"success",
                            message:"修改成功"
                        })
                    }
                })
            }else if(this.editType == "add"){
                postMethodCommon("/geoserver/insertLayerData",saveFormData).then(res=>{
                    if(res.data.code == 200){
                        this.$message({
                            type:"success",
                            message:"添加成功"
                        })
                    }
                })
            }
            
        },
        getGeoJson(){

        },
        searchArea(){
            // 地名搜索
            axios.get("https://restapi.amap.com/v3/place/text?count=10&key=ee24b622294b5bc659fb92fe81084776&keywords="+this.areaSearch).then(res=>{
                if(res.data.info == "OK"){
                this.searchResult = [];
                res.data.pois.forEach((item,index)=>{
                    if(index<10){
                        this.searchResult.push(item);
                    }
                })
                }
            })
        },
        toSearchWhere(item){
            this.loadSearchResultLayer(item);

            let lngLat = item.location.split(",");
            this.globalMap.flyTo({
                center: lngLat,
                zoom: 16,
                speed: 10, // 飞行速度
                curve: 1, // 飞行曲线
                easing(t) { // 飞行动画函数
                return t;
                }
            });

        },
        loadSearchResultLayer(item){
            let geojson ={
                "type": "FeatureCollection",
                "features": [
                    {
                        type: 'Feature',
                        geometry: {
                            "type": "Point",
                            "coordinates": item.location.split(",")
                        },
                        properties: {
                            name:item.name
                        }
                    }
                ]
            };
            if(this.globalMap.getSource("searchSource")){
                this.globalMap.getSource("searchSource").setData(geojson);
            }else{
                this.globalMap.addSource("searchSource",{
                type:"geojson",
                data:geojson
                })
            }
            let _this = this;
            if(this.globalMap.hasImage("searchIcon")){
                
            }else{
                this.globalMap.loadImage(
                'https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png',
                function(error, image) {
                    if (error) throw error;
                    _this.globalMap.addImage('searchIcon', image);
                }
                );
            }
            if(this.globalMap.getLayer("searchLayer")){

            }else{
                this.globalMap.addLayer({
                id: 'searchLayer',
                type: 'symbol',
                source: "searchSource",
                layout: {
                    'icon-image': 'searchIcon',
                    'icon-size':0.8,
                    'text-field': '{name}',
                    'text-offset': [0, 2],
                    'text-anchor': 'top',
                    'text-size':12
                },
                paint:{
                    "text-color":"#fff"
                }
                })
            }
        },
        initMap(){
            this.$mapboxgl.accessToken = "pk.eyJ1Ijoic2hpY2hhbzEyMyIsImEiOiJja3FobnI1aDEwNGF6Mm9vOXVhNnBzZmFhIn0.2fZKiMqCQHxVY74QShMEGQ";
            this.globalMap = new this.$mapboxgl.Map({
                container:"mapEditorContainer",
                center:[this.currentViewer.center.lng,this.currentViewer.center.lat],
                zoom:this.currentViewer.zoom,
                maxZoom:20,
                minZoom:5,
                pitch:this.currentViewer.pitch,
                style:"mapbox://styles/mapbox/satellite-v9",
                // style:"mapbox://styles/mapbox/streets-v11"
                // style:"mapbox://styles/mapbox/dark-v10"
                attributionControl: false,
                logoPosition: 'top-right',
                failIfMajorPerformanceCaveat: false,
                preserveDrawingBuffer: true,
                
            });

            let _this = this;
            
            
             _this.draw = new MapboxDraw({
                displayControlsDefault: false,
                controls: {
                    point: false,
                    line_string: false,
                    polygon: true,
                    trash: true
                },
                // defaultMode: 'draw_polygon'
            })

            

            this.globalMap.on("load",function(){
                
                // 飞行到中心点
                if(_this.editType == "edit"){
                    let bbox = turf.bbox(_this.geojson);
                    let center = turf.centerOfMass(turf.bboxPolygon(bbox)).geometry.coordinates;
                    _this.globalMap.flyTo({center:center,zoom:18})

                    _this.draw.set({
                        "type": "FeatureCollection",
                        "features": [
                            {
                                "type":"Feature",
                                "geometry":_this.geojson
                            }
                        ]
                    });
                }



               _this.loadGaoQingLayer();
                // _this.loadDianZiLayer();
                _this.loadXianJieLayer();
            })

          


            _this.globalMap.addControl(new this.$mapboxgl.NavigationControl(),'top-right');
            _this.globalMap.addControl(_this.draw,'top-right');

               _this.globalMap.on('draw.create', function (e) {
                console.log("eeeee",e)
                    var feature = e.features[0];
                    _this.geojson =feature;
                })

                _this.globalMap.on('draw.delete', function (e) {
                    console.log('draw.delete',e.features)
                })

                _this.globalMap.on('draw.combine', function (e) {
                    console.log('draw.combine', e.features)
                })

                _this.globalMap.on('draw.uncombine', function (e) {
                    console.log('draw.uncombine', e.features)
                })

                _this.globalMap.on('draw.update', function (e) {
                    console.log('draw.update', e.features)
                })

                _this.globalMap.on('draw.selectionchange', function (e) {

                    console.log('draw.selectionchange', e.features)

                })

                _this.globalMap.on('draw.modechange', function (e) {
                    console.log('draw.modechange', e.features)
                })

                _this.globalMap.on('draw.render', function (e) {
                    console.log('draw.render', e.features)
                })

                _this.globalMap.on('draw.actionable', function (e) {
                    console.log('draw.actionable', e.features)
                })

            
        },
        toggleLayer(layerName){
            let visibie = this.globalMap.getLayoutProperty(layerName, 'visibility');

            if(visibie == 'visible'){
                this.globalMap.setLayoutProperty(layerName,'visibility', 'none');
                this.layerShow[layerName] = "none"
            }else if(visibie == 'none'){
                this.globalMap.setLayoutProperty(layerName, 'visibility','visible');
                this.layerShow[layerName] = "visible"
            }
        },
        onSubmit(){

        },
        loadDianZiLayer(){
            this.globalMap.addLayer({
                'id': 'tiandituzhuji',
                'type': 'raster',
                'source':{
                    "type": "raster",
                    "tiles": ['http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=b6585bc41ee16251dbe6b1af64f375d9'],
                    "tileSize": 256,
                },
                'layout':{
                    'visibility':'visible'
                },
            })
        },
        loadGaoQingLayer(){
        this.globalMap.addLayer({
            'id': 'gaoqingyingxiang',
            'type': 'raster',
            'source': {
            'type': 'raster',
            'tiles': ["http://60.213.14.14:8060/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
            },
            'layout':{
            'visibility':'visible'
            },
            'paint': {

            }
            });
        },
        loadXianJieLayer(){
        this.globalMap.addLayer({
            id: 'xianjie',
            type: 'line',
            layout:{
                "visibility":"visible"
            },
            source: {
                type: 'geojson',
                data: 'http://175.27.168.120:8080/geoserver/feixian/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=feixian%3Axianjie&maxFeatures=50&outputFormat=application%2Fjson'
            },
            paint: {
                'line-width': 2,
                'line-color': 'orange'
            }
        });
        }
        }

}
</script>
<style scoped>
.editor-map-about-container{
  width:100%;
  height:100%;
  position:relative;
  /* background:hsl(212, 43%, 49%,0.5); */
  background:#284171;
}

.map-search-container{
  width:400px;
  height:40px;
  position:absolute;
  top:15px;
  /* right:330px; */
  left:20px;
  z-index:9999;
}

.search-result{
  width:372px;
  padding:0px 10px 20px 10px;
  min-height:120px;
  position:absolute;
  top:50px;
  left:0px;
  background:rgb(40, 65, 113,0.7);
  color:#fff;
  box-shadow: 0px 0px 5px #7688a8;
}

.search-result .search-result-item{
  width:100%;
  padding:10px;
  border-bottom:1px dashed rgba(16, 132, 241, 0.7);
  cursor:pointer;
}
.search-result .search-result-item:hover{
  color:#e9e9e9;
}

.layer-container{
  width:340px;
  height:40px;
  position:absolute;
  top:15px;
  right:0px;
  z-index:9999;
}

.layer-button{
  width:100px;
  height:30px;
  line-height:30px;
  background:#108eff;
  color:#fff;
  float:left;
  margin-right:12px;
  text-align:center;
  border:1px solid #108eff;
}
.map-container{
  width: calc( 100% - 30px);
  padding:0px 15px;
  height: calc( 100% - 375px);
  background:#ffffff;
  position:absolute;
  top:60px;
  left:15px;
}

.form-container{
  width: calc( 100% - 30px);
  height:300px;
  position:absolute;
  bottom:15px;
  left:15px;
  padding:15px 15px;
  background:hsl(212, 43%, 49%,0.5);
}
.description-container{
  width:100%;
  height:220px;
  overflow: hidden;
  overflow-y:auto;
}
::v-deep .mapboxgl-ctrl-top-right{
    width:50px;
    height:200px;
    z-index:99999999999;
}
::v-deep .mapboxgl-ctrl-group .mapboxgl-ctrl{
     display:block;
}
::v-deep .mapboxgl-ctrl{
    display:block;
}

::v-deep .mapboxgl-ctrl-navigation {
  position: absolute;
  top: 0;
  right: 0;
  padding: 10px;
}

.custom-icon {
  background-image: url('https://docs.mapbox.com/mapbox-gl-js/assets/custom_marker.png');
  background-size: cover;
  width: 30px;
  height: 30px;
  cursor: pointer;
}
</style>