<template>
  <div>
<!--    <p class="fuTitle">地块位置绘制</p>-->
    <div id="full-screen-acceptance" style="width: 100%;height:71vh; position: relative;">
        <div :id=this.uuidMap style="width: 100%;height: 100%"></div>
        <div id='land-btn-wrap'>
            <!--<el-button :id=this.drawingPolygonMap style="background-color:#D0EEFF;color:#1E88C7" @click="" type="primary">画图</el-button>-->
            <!--<input id="drawRemove" type="button" class="ant-btn ant-btn-red" value="取消"/>&nbsp;&nbsp;-->
            <!--<el-button :id=this.drawingPolygonMap style="background-color:#D0EEFF;color:#1E88C7" type="primary">重置图层</el-button>-->
            <input :id="locationMap" type="button" class="ant-btn ant-btn-red" value="定位"/>&nbsp;&nbsp;
            <input :id="this.drawingPolygonMap" class="ant-btn ant-btn-red" type="button" value="画图"/>&nbsp;&nbsp;
            <input :id="this.drawingResetMap" type="button" class="ant-btn ant-btn-red" value="重置"/>&nbsp;&nbsp;
        </div>

        <div v-if="hasSelectLocationMode" class="location-mode-chooser-btn"><input type="button" class="ant-btn ant-btn-red" value="选择定位方式" @click="selectLocationMode"/></div>
      </div>
    <div style="font-size: 13px; padding-top: 5px;">备注：绿色地块表示该地块，蓝色表示本账套已标记的其他地块</div>
    <div id="info" style="display: none"></div>
  </div>
</template>

<script>
  import {getQueryLand} from "@/api/homesteadSurvey/zjdzd";
import $ from "jquery";
  import { getConfigKey } from "@/api/system/config";
  import {Toast} from "vant";

export default {
  components: {
    getQueryLand,
  },
  data() {
    return {
      closeMoule: null,
      uuidMap: this.guidProduct(),
      drawingPolygonMap: this.guidProduct(),
      drawingResetMap: this.guidProduct(),
      locationMap: this.guidProduct(),
      mapGeoServerUrl: "",            // geoserver地址
      villageBorderLayerName: "",     // 乡镇边界图层名称
    };
  },
  props: ['theGeom','message', 'resourceId', 'resourceList'],
  created() {
    // 获取geoserver的地址
    this.getGeoServerUrl();
    // 获取村边界的图层名称
    this.getVillageBorderLayerName();
  },
  computed: {
    isAndroid() {
      return !!window._Native_object;
    },
    hasSelectLocationMode() {
      return this.isAndroid && typeof(window._Native_object.SelectLocationMode) === 'function';
    },
    hasGetLocationTimeout() {
      return this.isAndroid && typeof(window._Native_object.GetLocationTimeout) === 'function';
    },
    hasGetLocationMode() {
      return this.isAndroid && typeof(window._Native_object.GetLocationMode) === 'function';
    },
  },
  methods: {
    // 获取geoserver的地址
    getGeoServerUrl() {
      getConfigKey("system.geoServer.url").then(response => {
        this.mapGeoServerUrl = response.msg;
      });
    },
    // 获取村边界的图层名称
    getVillageBorderLayerName() {
      getConfigKey("geoserver.layer.villageBorder").then(response => {
        this.villageBorderLayerName = response.msg;
      });
    },
    //地图加载
    formSubmit(){
       //父组件监听的名字必须是formSubmit
      // 子组件调用父组件的方法并传参
      if(this.closeMoule =="" || this.closeMoule == null){
        this.$emit('formSubmit', null);
      }else{
        this.$emit('formSubmit', JSON.stringify(this.closeMoule));
      }
    },
    guidProduct(){
      return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0,
          v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
      });
    },
    selectLocationMode() {
      if(this.hasSelectLocationMode)
      {
        let res = window._Native_object.SelectLocationMode();
        console.log('当前选择定位模式: ' + res);
      }
    },
    getLocationMode() {
      let mode = '';
      if(this.hasGetLocationMode)
      {
        mode = window._Native_object.GetLocationMode();
      }
      console.log('当前选择定位模式: ' + mode);
      return mode;
    },
    getLocationTimeout() {
      let timeout = 30000;
      if(this.isAndroid)
      {
        let to = window._Native_object.GetLocationTimeout();
        if(to <= 0)
          to = 30000;
        timeout = to;
      }
      console.log('当前选择定位超时: ' + timeout);
      return timeout;
    },
    getCurrentLocation(callback) {
      // 1. 首先尝试Android宿主端
      if(this.isAndroid) // Android层注入全局对象
      {
        let mode = this.getLocationMode();
        if(mode !== 'h5')
        {
          console.log('使用Native获取定位');
          let coord = window._Native_object.GetLocation(null);
          console.log('Native坐标: ' + coord);
          if(coord)
          {
            let arr = coord.split(',');
            let res = {
              code: 200,
              data: {
                lng: arr[0],
                lat: arr[1],
              },
            };
            callback(res);
            return;
          }
        }
      }

      // 2. 再尝试浏览器
      if (navigator.geolocation) {
        console.log('使用浏览器获取定位');
        const loading = Toast.loading({
          message: '定位中...',
          duration: 0,
        });
        let timeout = this.getLocationTimeout();
        navigator.geolocation.getCurrentPosition(
          (position) => {
            const { latitude, longitude } = position.coords;
            console.log('浏览器定位结果: 经纬度=' + longitude + ', ' + latitude);
            let res = {
              code: 200,
              data: {
                lng: longitude,
                lat: latitude,
              },
            };
            loading.clear();
            callback(res);
          },
          (error) => {
            loading.clear();
            console.log('定位失败: ' + error.message);
            getQueryLand().then(callback);
          },
          { enableHighAccuracy: true, timeout: timeout }
        );
        return;
      }

      // 最后使用地区坐标
      console.log('使用地区坐标定位');
      getQueryLand().then(callback);
    },
    getDeptLocation(callback) {
      getQueryLand().then((response) => {
        if (response.code == 200) {
          let InsertCode = response.data;
          if (InsertCode != null) {
            var lat = InsertCode.lat;
            var lng = InsertCode.lng;
            if(lat !=null && lng !=null && lat !="" && lng !=""){
              callback(response);
              return;
            }
          }
        }
        this.getCurrentLocation(callback);
      });
    },
    //地图查看
    drawingPaceCountryLine() {
      //加载地图编辑
      var that = this;
      var map;
      //var hc_land;
      var draw; // global so we can remove it later
      var vector_drawing;

      var mark_layer = null;
      function addMark(lng, lat) {
        if(!mark_layer)
        {
          mark_layer = new ol.layer.Vector({
            source: new ol.source.Vector(),
          });
          map.addLayer(mark_layer);
        }
        else
          mark_layer.getSource().clear();

        let newFeature = new ol.Feature({
          geometry: new ol.geom.Point(ol.proj.fromLonLat([lng, lat])), //几何信息
          //name: "标注点",
        });
        newFeature.setStyle(new ol.style.Style({
          image: new ol.style.Icon({
            //设置图标偏移
            anchor: [0.5, 0.5],
            //标注样式的起点位置
            anchorOrigin: "top-right",
            //X方向单位：分数
            anchorXUnits: "fraction",
            //Y方向单位：像素
            anchorYUnits: "fraction",
            //偏移起点位置的方向
            offsetOrigin: "top-right",
            //透明度
            opacity: 0.9,
            //图片路径
            src: require('../../assets/images/location/mark.png'),
          }),
          zIndex: 9999,
        }));
        mark_layer.getSource().addFeature(newFeature);
      }

      if (that.message != null && that.message != ""
        && that.message != undefined) {
        document.getElementById(that.uuidMap).innerHTML = '';
        var hc_land;
        var hc_landFuther;
        var draw; // global so we can remove it later
        var vector_drawing;
        var projection = new ol.proj.Projection({
          //地图投影类型
          code: "EPSG:3857",
          units: "degrees",
          //extent:extent
        });

        var aerial = new ol.layer.Tile({
          source: new ol.source.XYZ({
            url: "http://t0.tianditu.gov.cn/img_w/wmts?" +
              "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
              "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=cc4aba6e967096098249efa069733067",
          }),
          isGroup: true,
          name: "卫星影像图",
        });

        var yingxzi = new ol.layer.Tile({
          source: new ol.source.XYZ({
            url: "https://t0.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=cc4aba6e967096098249efa069733067",
          }),
          isGroup: true,
          name: "天地图文字标注--卫星影像图",
        });
        //加载地图
        map = new ol.Map({
          controls: ol.control.defaults({attribution: false, zoom: false, rotate: false}).extend([]), //隐藏放大缩小按钮
          layers: [aerial, yingxzi],
          projection: projection,
          target: that.uuidMap,
          view: new ol.View({
            //center: ol.proj.fromLonLat([115.452752, 31.789033]),
            zoom: 15,
            minZoom: 5, //地图缩小限制
            maxZoom: 18.3, //地图放大限制
          }),
        });

        // 添加村边界
        let mapBorder = new ol.layer.Image({
          source: new ol.source.ImageWMS({
            url: this.mapGeoServerUrl + '/wms',
            params: {
              LAYERS: this.villageBorderLayerName,
              cql_filter: "dept_id = '" + this.$store.state.user.loginDeptId + "'",
              SRID: 3857,
            },
          }),
          name: 'villageBorderLayer'
        });
        map.addLayer(mapBorder);

        // 添加已经存在的资源图层
        let vectorSource = new ol.source.Vector();
        for (let resource of this.resourceList) {
          if (resource.theGeom && resource.id !== this.resourceId) {
            let feature = new ol.Feature({
              geometry: new ol.geom.MultiPolygon(JSON.parse(resource.theGeom).coordinates),
              // permanentName: permanent.name
            });
            vectorSource.addFeature(feature);
          }
        }

        let resourceLayer = new ol.layer.Vector({
          source: vectorSource,
          style:  (feature, resolution) => {
            return new ol.style.Style({
              fill: new ol.style.Fill({
                //矢量图层填充颜色，以及透明度
                color: "rgba(0, 218, 255, 0.3)",
              }),
              stroke: new ol.style.Stroke({
                //边界样式
                color: "#00DAFF",
                width: 3,
              }),
            })
          }
        });
        map.addLayer(resourceLayer);

        //图层查询定位开始 ---------start
        if(this.message.substring(0,1) =="{"){
          // var theGeomMap =this.message.replace("Point", "MultiPolygon");
          // var pointLeft = theGeomMap.replace("[", "[[[[");
          // var pointRight = pointLeft.replace("]", "]]]]");
          hc_land = new ol.layer.Vector({
            title: "add Layer",
            source: new ol.source.Vector({
              projection: projection,
              features: new ol.format.GeoJSON().readFeatures("{\n" +
                "    \"type\": \"Feature\",\n" +
                "    \"geometry\":" + this.message + "}"),
            }),
            style: new ol.style.Style({
              fill: new ol.style.Fill({
                //矢量图层填充颜色，以及透明度
                color: "rgba(204, 255, 204,0.3)",
              }),
              stroke: new ol.style.Stroke({
                //边界样式
                color: "#47c68f",
                width: 3,
              }),
            }),
          });
          map.addLayer(hc_land);
          var maxXMap = hc_land.values_.source.featuresRtree_.rbush_.data.maxX;
          var maxYMap = hc_land.values_.source.featuresRtree_.rbush_.data.maxY;
          var minXMap = hc_land.values_.source.featuresRtree_.rbush_.data.minX;
          var minYMap = hc_land.values_.source.featuresRtree_.rbush_.data.minY;
          //定位查询位置
          var center = ol.extent.getCenter([maxXMap, maxYMap, minXMap, minYMap]); //获取边界区域的中心位置
          map.getView().animate({
            // 只设置需要的属性即可
            center: center, // 中心点
            zoom: 17.9, // 缩放级别
            rotation: undefined, // 缩放完成view视图旋转弧度
            duration: 1000, // 缩放持续时间，默认不需要设置
          });
        }
        // if(this.message.substring(0,1) =="["){
        //   var zbNew = JSON.stringify({"type": "MultiPolygon", "coordinates": [[[this.message.replaceAll("\"","")]]]});
        //   var leftJoin = zbNew.replace("\"[","[");
        //   var rightJoin = leftJoin.replace("\"]","]");
        //   hc_landFuther = new ol.layer.Vector({
        //     title: "add Layer",
        //     source: new ol.source.Vector({
        //       projection: projection,
        //       features: new ol.format.GeoJSON().readFeatures("{\n" +
        //         "    \"type\": \"Feature\",\n" +
        //         "    \"geometry\":" + rightJoin + "}"),
        //     }),
        //     style: new ol.style.Style({
        //       fill: new ol.style.Fill({
        //         //矢量图层填充颜色，以及透明度
        //         color: "rgba(204, 255, 204,0.3)",
        //       }),
        //       stroke: new ol.style.Stroke({
        //         //边界样式
        //         color: "#47c68f",
        //         width: 3,
        //       }),
        //     }),
        //   });
        //   map.addLayer(hc_landFuther);
        //   var maxXMap = hc_landFuther.values_.source.featuresRtree_.rbush_.data.maxX;
        //   var maxYMap = hc_landFuther.values_.source.featuresRtree_.rbush_.data.maxY;
        //   var minXMap = hc_landFuther.values_.source.featuresRtree_.rbush_.data.minX;
        //   var minYMap = hc_landFuther.values_.source.featuresRtree_.rbush_.data.minY;
        //   //定位查询位置
        //   var center = ol.extent.getCenter([maxXMap, maxYMap, minXMap, minYMap]); //获取边界区域的中心位置
        //   map.getView().animate({
        //     // 只设置需要的属性即可
        //     center: center, // 中心点
        //     zoom: 17.9, // 缩放级别
        //     rotation: undefined, // 缩放完成view视图旋转弧度
        //     duration: 1000, // 缩放持续时间，默认不需要设置
        //   });
        // }
        //图层查询定位结束 ---------end
        //开始绘制地图
        $("#"+this.drawingPolygonMap).click(function () {
          map.removeLayer(hc_land);
          //map.removeLayer(hc_landFuther);
          map.removeLayer(vector_drawing);
          //that.closeMoule = null;
          map.removeInteraction(draw);
          //var source = new ol.source.Vector({wrapX: false});
          vector_drawing = new ol.layer.Vector({
            source: new ol.source.Vector(),
          });
          map.addLayer(vector_drawing);

          function addInteraction() {
            draw = new ol.interaction.Draw({
              source: vector_drawing.getSource(),
              type: "Polygon"
            });
            draw.on('drawend', function (evt) {
              var feature = evt.feature;
              var geometry = feature.getGeometry();
              var coordinate = geometry.getCoordinates();
              that.closeMoule = coordinate;
              that.formSubmit();
            });
            map.addInteraction(draw);
          }

          addInteraction();
        });
        //清除画图鼠标点击事件
        // $("#drawRemove").click(function () {
        //   //map.addLayer(hc_land);
        //   map.removeInteraction(draw);
        //   //map.removeLayer(vector_drawing);
        // });
        //还原之前图层
        $("#"+this.drawingResetMap).click(function () {
          if(that.closeMoule !=null) {
            map.removeLayer(vector_drawing);
            //map.removeLayer(hc_landFuther);
            map.removeInteraction(draw);
            map.addLayer(hc_land);
            //map.addLayer(hc_landFuther);
           // that.closeMoule = null;
            that.formSubmit();
          }
        });
        $("#" + this.locationMap).click(function () {
          that.getCurrentLocation(res => {
            if (res.code == 200) {
              let lat = res.data.lat;
              let lng = res.data.lng;
              if(lat && lng){
                Zb = [lng,lat];
              }else {
                Zb =[115.452752, 31.789033];
              }
              addMark(lng,lat);
              map.getView().animate({
                // 只设置需要的属性即可
                center: ol.proj.fromLonLat(Zb), // 中心点
                zoom: 18, // 缩放级别
                rotation: undefined, // 缩放完成view视图旋转弧度
                duration: 1000, // 缩放持续时间，默认不需要设置
              });
            }
          });
        });
      } else{
        //this.closeMoule = null;
        document.getElementById(that.uuidMap).innerHTML = '';
        var projection = new ol.proj.Projection({
          //地图投影类型
          code: "EPSG:3857",
          units: "degrees",
          //extent:extent
        });

        var aerial = new ol.layer.Tile({
          source: new ol.source.XYZ({
            url: "http://t0.tianditu.gov.cn/img_w/wmts?" +
              "SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles" +
              "&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=cc4aba6e967096098249efa069733067",
          }),
          isGroup: true,
          name: "卫星影像图",
        });

        var yingxzi = new ol.layer.Tile({
          source: new ol.source.XYZ({
            url: "https://t0.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=cc4aba6e967096098249efa069733067",
          }),
          isGroup: true,
          name: "天地图文字标注--卫星影像图",
        });
        //获取坐标是否存在
        var Zb;
        this.getDeptLocation((response) => {
          if (response.code == 200) {
            let InsertCode = response.data;
            if (InsertCode != null) {
              var lat = InsertCode.lat;
              var lng = InsertCode.lng;
              if(lat !=null && lng !=null && lat !="" && lng !=""){
                Zb = [lng,lat];
              }else {
                Zb =[115.452752, 31.789033];
              }
              //加载地图
              map = new ol.Map({
                controls: ol.control.defaults({attribution: false, zoom: false, rotate: false}).extend([]), //隐藏放大缩小按钮
                layers: [aerial, yingxzi],
                projection: projection,
                logo: 'false',
                target: that.uuidMap,
                view: new ol.View({
                  center: ol.proj.fromLonLat(Zb),
                  //center: ol.proj.fromLonLat([115.452752, 31.789033]),
                  zoom: 16.9,
                  minZoom: 5, //地图缩小限制
                  maxZoom: 18, //地图放大限制
                }),
              });

              // 添加村边界
              let mapBorder = new ol.layer.Image({
                source: new ol.source.ImageWMS({
                  url: this.mapGeoServerUrl + '/wms',
                  params: {
                    LAYERS: this.villageBorderLayerName,
                    cql_filter: "dept_id = '" + this.$store.state.user.loginDeptId + "'",
                    SRID: 3857,
                  },
                }),
                name: 'villageBorderLayer'
              });
              map.addLayer(mapBorder);

              // 添加已经存在的资源图层
              let vectorSource = new ol.source.Vector();
              for (let resource of this.resourceList) {
                if (resource.theGeom && resource.id !== this.resourceId) {
                  let feature = new ol.Feature({
                    geometry: new ol.geom.MultiPolygon(JSON.parse(resource.theGeom).coordinates),
                    // permanentName: permanent.name
                  });
                  vectorSource.addFeature(feature);
                }
              }

              let resourceLayer = new ol.layer.Vector({
                source: vectorSource,
                style:  (feature, resolution) => {
                  return new ol.style.Style({
                    fill: new ol.style.Fill({
                      //矢量图层填充颜色，以及透明度
                      color: "rgba(0, 218, 255, 0.3)",
                    }),
                    stroke: new ol.style.Stroke({
                      //边界样式
                      color: "#00DAFF",
                      width: 3,
                    }),
                  })
                }
              });
              map.addLayer(resourceLayer);
            }
          }
        });

        //图层查询定位结束 ---------end
        //开始绘制地图
        $("#"+this.drawingPolygonMap).click(function () {
          //that.closeMoule = null;
          map.removeInteraction(draw);
          //var source = new ol.source.Vector({wrapX: false});
          vector_drawing = new ol.layer.Vector({
            source: new ol.source.Vector(),
          });
          map.addLayer(vector_drawing);

          function addInteraction() {
            draw = new ol.interaction.Draw({
              source: vector_drawing.getSource(),
              type: "Polygon"
            });
            draw.on('drawend', function (evt) {
              var feature = evt.feature;
              var geometry = feature.getGeometry();
              var coordinate = geometry.getCoordinates();
              that.closeMoule = coordinate;
              that.formSubmit();
            });
            map.addInteraction(draw);
          }

          addInteraction();

        });
        //清除画图鼠标点击事件
        // $("#drawRemove").click(function () {
        //   //map.addLayer(hc_land);
        //   map.removeInteraction(draw);
        //   //map.removeLayer(vector_drawing);
        // });
        //还原之前图层
        $("#"+this.drawingResetMap).click(function () {
          map.removeInteraction(draw);
          map.removeLayer(vector_drawing);
          //that.closeMoule = null;
          that.formSubmit();
        });
        $("#" + this.locationMap).click(function () {
          that.getCurrentLocation(res => {
            if (res.code == 200) {
              let lat = res.data.lat;
              let lng = res.data.lng;
              if(lat && lng){
                Zb = [lng,lat];
              }else {
                Zb =[115.452752, 31.789033];
              }
              addMark(lng,lat);
              map.getView().animate({
                // 只设置需要的属性即可
                center: ol.proj.fromLonLat(Zb), // 中心点
                zoom: 18, // 缩放级别
                rotation: undefined, // 缩放完成view视图旋转弧度
                duration: 1000, // 缩放持续时间，默认不需要设置
              });
            }
          });
        });
      }
    },
  },
  watch: {},
};
</script>

<style scoped>
#that.message {
  width: 100%;
  height: 100%;
}
.fuTitle {
  border-top: 1px solid #e9e9e9;
  text-align: center;
  padding: 10px 0px 0px 0px;
  font-size: 18px;
  color: #999;
}
.ant-btn-red {
  position: relative;
  display: inline-block;
  background: #D0EEFF;
  border: 1px solid #99D3F5;
  border-radius: 4px;
  padding: 4px 12px;
  overflow: hidden;
  color: #1E88C7;
  text-decoration: none;
  text-indent: 0;
  line-height: 30px;
  font-size: 28px;
  margin: 5px 0 5px;
}
#land-btn-wrap{
  position: relative;
  width: 25%;
  left: 75%;
  bottom: 100%;
  z-index: 2000;
  padding-top: 5%;
}
.location-mode-chooser-btn {
  position: absolute;
  right: 0;
  bottom: 0;
  z-index: 2000;
}
</style>
