<template>
  <div class="home_wrapper">
    <div class="map_main" id="mapWrap"></div>

    <div class="top_address" @click="showAddress=true">
      <i class="address_icon"></i>
      <p>{{deptName}}</p>
    </div>

    <!--选择当前区域弹窗-->
    <van-popup v-model="showAddress" position="bottom">
      <van-cascader
        v-model="villageValue"
        title="请选择"
        :options="addrOptions"
        @close="showAddress = false"
        @finish="onConfirmDept"
        active-color="#1989fa"
        :field-names="hcAreaInfoFieldName"
      />
    </van-popup>

    <!--当前区域详情弹窗-->
    <van-popup v-model="show" position="bottom" :overlay="false" round>
      <div class="pop_main">

        <div class="pop_title">
          <i class="address_icon"></i>
          <p>{{deptName}}</p>
        </div>

        <div class="pop_content">
          <div class="pop_content_left">
            <img src="../../../static/images/plotPremises/plotPremises_icon_01.png" alt="">
            <div class="pop_content_left_box">
              <div>
                <p>农房 <span>(栋)</span></p>
                <p class="num">{{detail.zzs}}</p>
              </div>
              <span class="border"></span>
              <div>
                <p>可租 <span>(栋)</span></p>
                <p class="num" @click="deptId == 100?'':(showList = true,activeName='nf')">{{detail.kzs}}</p>
              </div>
            </div>
          </div>
          <div class="pop_content_left">
            <img src="../../../static/images/plotPremises/plotPremises_icon_02.png" alt="">
            <div class="pop_content_left_box">
              <div>
                <p>农地 <span>(亩)</span></p>
                <p class="num">{{detail.landArea}}</p>
              </div>
              <span class="border"></span>
              <div>
                <p>可租 <span>(亩)</span></p>
                <p class="num" @click="deptId == 100?'':(showList = true,activeName='nd')">{{detail.rentableArea}}</p>
              </div>
            </div>
          </div>
        </div>

      </div>
    </van-popup>

    <!--租地详情弹窗-->
    <van-popup v-model="showZD" closeable position="bottom" :closed="show=true" :overlay="false" round>
      <div class="pop_main">

        <div class="pop_title">
          <i class="address_icon"></i>
          <p>{{deptName}}-{{ndItem.id}}</p>
        </div>

        <div class="pop_content_zd">
          <img src="../../../static/images/plotPremises/plotPremises_img.png" alt="">

          <div class="pop_content_zd_right">
            <!-- <van-row type="flex" justify="space-between">
              <van-col>租地位置：</van-col>
              <van-col>{{deptName}}</van-col>
            </van-row> -->
            <van-row type="flex" justify="space-between">
              <van-col>租地编号：</van-col>
              <van-col class="num">{{ndItem.id}}</van-col>
            </van-row>
            <van-row type="flex" justify="space-between">
              <van-col>租地面积：</van-col>
              <van-col class="num">{{ndItem.scmjm}}亩</van-col>
            </van-row>
            <van-row type="flex" justify="space-between">
              <van-col>咨询代表：</van-col>
              <van-col>{{ deptInfo.leader }}</van-col>
            </van-row>
            <van-row type="flex" justify="space-between">
              <van-col>咨询电话：</van-col>
              <van-col class="num">{{ deptInfo.phone }}</van-col>
            </van-row>
          </div>

        </div>

      </div>
    </van-popup>

    <!--租房详情弹窗-->
    <van-popup v-model="showZF" closeable position="bottom" :closed="show=true" :overlay="false" round>
      <div class="pop_main">

        <div class="pop_title">
          <i class="address_icon"></i>
          <p>{{deptName}}-{{nfItem.id}}</p>
        </div>

        <div class="pop_content_zd">
          <img src="../../../static/images/plotPremises/plotPremises_img.png" alt="">

          <div class="pop_content_zd_right">
            <!-- <van-row type="flex" justify="space-between">
              <van-col>租房位置：</van-col>
              <van-col>{{deptName}}</van-col>
            </van-row> -->
            <van-row type="flex" justify="space-between">
              <van-col>租房编号：</van-col>
              <van-col class="num">{{nfItem.id}}</van-col>
            </van-row>
            <van-row type="flex" justify="space-between">
              <van-col>租房面积：</van-col>
              <van-col class="num">{{nfItem.zdmj}}㎡</van-col>
            </van-row>
            <van-row type="flex" justify="space-between">
              <van-col>咨询代表：</van-col>
              <van-col>{{ deptInfo.leader }}</van-col>
            </van-row>
            <van-row type="flex" justify="space-between">
              <van-col>咨询电话：</van-col>
              <van-col class="num">{{ deptInfo.phone }}</van-col>
            </van-row>
          </div>

        </div>

      </div>
    </van-popup>

    <!--农房农地右侧列表弹窗-->
    <van-popup v-model="showList" close-icon="../../../static/images/plotPremises/plotPremises_icon_03.png" closeable position="right" :closed="show=true" :overlay="false" round :style="{ width: '45%' , height: '60%' , background:'#ffffff' }">
      <div class="pop_main_right">

        <p class="pop_title" :style="{color:activeName=='nf'?'#1B65F8':'#FF7321'}">{{activeName=='nf'?'待租农房':'待租农地'}}</p>

        <div class="pop_content_right" v-if="activeName=='nf'">
          <van-row>
            <van-col span="12" class="num">编号</van-col>
            <van-col span="12" style="text-align: left;">面积（㎡）</van-col>
          </van-row>
          <!--     待租农房列表     -->
          <van-row v-for="(item,index) in detail.rentableHomestead"
                   :key="index"
                   @click="listChange(index,'nf',item)"
                   :class="{ active: selectChooseOrder == index }"
                   align="center"
          >
            <van-col span="12" class="num">{{item.id}}</van-col>
            <van-col span="12" style="text-align: left;" class="num">{{item.zdmj}}</van-col>
          </van-row>
        </div>

        <div class="pop_content_right" v-else>
          <van-row>
            <van-col span="12" class="num">编号</van-col>
            <van-col span="12" style="text-align: left;">面积（亩）</van-col>
          </van-row>
          <!--     待租农房列表     -->
          <van-row v-for="(item,index) in detail.rentableLand"
                   :key="index"
                   @click="listChange(index,'nd',item)"
                   :class="{ active: selectChooseOrder == index }"
                   align="center"
          >
            <van-col span="12" class="num">{{item.id}}</van-col>
            <van-col span="12" style="text-align: left;" class="num">{{item.scmjm}}</van-col>
          </van-row>
        </div>

        <div class="pop_btn_right">
          <p :style="{background:activeName=='nf'?'#1B65F8':'',color:activeName=='nf'?'#ffffff':''}" @click="tabChange('nf')">农房</p>
          <p :style="{background:activeName=='nd'?'#FF7321':'',color:activeName=='nd'?'#ffffff':''}" @click="tabChange('nd')">农地</p>
        </div>


      </div>
    </van-popup>

<!--    <van-popup v-model="showAddress" position="bottom" round>-->
<!--      <van-picker show-toolbar title="村镇选择" :columns="columns" />-->
<!--    </van-popup>-->

  </div>
</template>

<script>
import $ from "jquery";
import { getConfigKey } from "@/utils/data";
import { getDept , treeselect , plotPremisesStatistics } from "@/api/plotPremisesMobile";

export default {
  data() {
    return {
      show:true,
      showZD:false,
      showZF:false,
      showList:false,
      showAddress:false,
      activeName:'nf',
      selectChooseOrder:-1,
      addrOptions: [],

      map: "",                                          // 地图
      // countyBorder: "",                                 // 区县边界
      // townBorder: "",                                   // 乡镇边界
      // villageBorder: "",                                // 村边界
      borderLayer: "",                                  // 区域边界图层
      deptLayer: "",                                    // 坐标点图层
      userRole: "",                                     // 记录用户身份
      cityId: null,                                     // 记录市的deptId
      countyId: null,                                   // 记录区县的deptId
      townId: null,                                     // 记录乡镇的deptId
      currentDeptLevel: null,                           // 当前所处的部门级别

      mapGeoServerUrl: "",                              // 加载geoserver地址
      countyBorderLayerName: "",                        // 区县边界图层名称
      townBorderLayerName: "",                          // 乡镇边界图层名称
      villageBorderLayerName: "",                       // 村边界图层名称

      landLayer: "",                                    // 地块图层
      homesteadLayer: "",                               // 宅基地图层
      selectedLayer: "",                                // 选中的图层
      deptInfo: {
        leader: null,                                   // 联系人
        phone: null                                     // 电话
      },

      deptName:'',
      deptId:'',
      detail:{},
      villageValue: "",
      hcAreaInfoFieldName: {
        text: "label",
        value: "value",
        children: "children",
      },
      deptOptions:[],
      nfItem:{},
      ndItem:{},
    };
  },
  created() {

  },
  mounted() {
    // 获取geoserver的地址
    this.getGeoServerUrl();
    // 获取区县边界图层名称
    this.getCountyBorderLayerName();
    // 获取乡镇边界的图层名称
    this.getTownBorderLayerName();
    // 获取村边界的图层名称
    this.getVillageBorderLayerName();
    // 获取部门下拉树列表
    treeselect().then(response => {
      this.addrOptions = response.data;
      this.deptId = response.data[0].id;
      this.deptName = response.data[0].label;
      // 初始化地图
      this.initMap();
      this.getData();
    });
  },
  methods: {
    getData(){
      plotPremisesStatistics({deptId:this.deptId}).then(response => {
        this.detail = response.data;
      });
    },
    onConfirmDept({ selectedOptions }){
      this.deptId = selectedOptions[selectedOptions.length-1].id;
      this.deptName = selectedOptions.map((option) => option.label).join('/');
      this.getData();
      this.showAddress = false;
      this.drawMap(selectedOptions);
      this.deptInfo.leader = null;
      this.deptInfo.phone = null;
      getDept(this.deptId).then(res => {
        this.deptInfo.leader = res.data.leader;
        this.deptInfo.phone = res.data.phone;
      });
    },

    tabChange(name){
      this.activeName = name;
      this.selectChooseOrder = -1;
    },
    listChange(id,type,data){
      this.selectChooseOrder = id;
      this.show = false;
      this.showZF = false;
      this.showZD = false;
      if (type=='nf') {
        this.showZF = true;
        this.nfItem = data;
      }
      if (type=='nd') {
        this.showZD = true;
        this.ndItem = data;
      }

      if (this.selectedLayer) {
        this.map.removeLayer(this.selectedLayer);
        this.selectedLayer = '';
      }
      if (data.theGeom) {
        this.selectedLayer = new ol.layer.Vector({
          source: new ol.source.Vector({
            features: new ol.format.GeoJSON().readFeatures("{\n" +
              "    \"type\": \"Feature\",\n" +
              "    \"geometry\":" + data.theGeom + ",    \"properties\":" + JSON.stringify(data.id) + "}"),
          }),
          name: 'selectedLayer',
          style: new ol.style.Style({
            fill: new ol.style.Fill({
              //矢量图层填充颜色，以及透明度
              color: "rgba(255, 84, 87, 0.5)",
            }),
            stroke: new ol.style.Stroke({
              //边界样式
              color: "#ff5457",
              width: 2,
            }),
          }),
        });
        this.map.addLayer(this.selectedLayer);
        let center = ol.extent.getCenter(this.selectedLayer.getSource().getExtent());
        this.map.getView().animate({
          center: center,             // 中心点
          zoom: 17,                   // 缩放级别
          rotation: undefined,        // 缩放完成view视图旋转弧度
          duration: 500,              // 缩放持续时间，默认不需要设置
        });
      }
    },
    //获取geoserver的地址
    getGeoServerUrl() {
      getConfigKey("system.geoServer.url").then(response => {
        this.mapGeoServerUrl = response.msg;
      });
    },
    //获取区县边界的图层名称
    getCountyBorderLayerName() {
      getConfigKey("geoserver.layer.countyBorder").then(response => {
        this.countyBorderLayerName = response.msg;
      });
    },
    //获取乡镇边界的图层名称
    getTownBorderLayerName() {
      getConfigKey("geoserver.layer.townBorder").then(response => {
        this.townBorderLayerName = response.msg;
      });
    },
    //获取村边界的图层名称
    getVillageBorderLayerName() {
      getConfigKey("geoserver.layer.villageBorder").then(response => {
        this.villageBorderLayerName = response.msg;
      });
    },
    // 初始化地图
    initMap() {
      const dept = this.addrOptions[0];
      // 定义地图中心坐标
      let mapCenterLocation;
      if (dept.lng && dept.lat) {
        mapCenterLocation = [dept.lng, dept.lat];
      } else {
        mapCenterLocation = [116.391458, 39.902377];
      }

      document.getElementById("mapWrap").innerHTML = "";
      // 定义地图投影
      let projection = new ol.proj.Projection({
        code: "EPSG:3857",
        units: "degrees",
      });
      // 定义地图图层
      let aerial = new ol.layer.Tile({
        source: new ol.source.XYZ({
          url: "http://t{0-7}.tianditu.com/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: "卫星影像图",
      });
      let yingxzi = new ol.layer.Tile({
        source: new ol.source.XYZ({
          url: "http://t{0-7}.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=cc4aba6e967096098249efa069733067",
        }),
        isGroup: true,
        name: "天地图文字标注--卫星影像图",
      });
      //加载地图
      this.map = new ol.Map({
        controls: ol.control.defaults({attribution: false, zoom: false, rotate: false}).extend([]),
        layers: [aerial, yingxzi],
        projection: projection,
        target: "mapWrap",
        view: new ol.View({
          center: ol.proj.fromLonLat(mapCenterLocation), // 地图中心坐标
          zoom: 9.5,
          minZoom: 1, //地图缩小限制
          maxZoom: 18, //地图放大限制
          // extent: [13481224.75161,5667110.83528,13811063.06278,5880284.11416]
        }),
        interactions: ol.interaction.defaults({
          doubleClickZoom: false,   // 双击放大地图
          // mouseWheelZoom: false,    // 鼠标滚轮放大地图
          // shiftDragZoom: false,     // shift + 鼠标左键拖拽 放大地图
        })
      });

      if (dept.deptLevel === '5') {
        // 登录身份为市级领导
        this.userRole = 'cityLeader';
        this.cityId = dept.id;
        this.currentDeptLevel = '5';
        // 添加区县边界
        this.addCountyBorder();
      } else if (dept.deptLevel === '4') {
        // 登录身份为县级领导
        this.userRole = 'countyLeader';
        this.countyId = dept.id;
        this.currentDeptLevel = '4';
        // 添加乡镇边界
        this.addTownBorder(dept.id);
        this.map.getView().setZoom(10.5);
      }
      // else if (dept.deptLevel === '3') {
      //   // 登录身份为镇级领导
      //   this.userRole = 'townLeader';
      //   this.townId = dept.id;
      //   this.currentDeptLevel = '3';
      //   // 添加村边界
      //   this.addVillageBorder(dept.id);
      //   this.map.getView().setZoom(12.5);
      // }
      if (dept.children) {
        this.addDeptLayer(dept.children);
      }

      this.map.on("click", (evt) => {
        let feature = this.map.forEachFeatureAtPixel(
          evt.pixel,
          (feature) => feature
        );
        if (feature) {
          // 镇级：加载村级坐标点
          if (feature.get('level') === 'deptPoint') {
            const deptId = feature.get('deptId');
            const deptLevel = feature.get('deptLevel');
            const lng = feature.get('lng');
            const lat = feature.get('lat');
            if (deptLevel === '4' || deptLevel === '3') {
              if (deptLevel === '4') {
                this.countyId = deptId;
                this.currentDeptLevel = '4';
                this.map.removeLayer(this.borderLayer);
                this.borderLayer = '';
                // 添加乡镇边界
                this.addTownBorder(deptId);
                this.map.getView().animate({
                  center: ol.proj.fromLonLat([lng, lat]), // 中心点
                  zoom: 10.5, // 缩放级别
                  rotation: undefined, // 缩放完成view视图旋转弧度
                  duration: 1000, // 缩放持续时间，默认不需要设置
                });
              } else if (deptLevel === '3') {
                this.townId = deptId;
                this.currentDeptLevel = '3';
                this.map.removeLayer(this.borderLayer);
                this.borderLayer = '';
                // 添加村边界
                const cqlFilter = "parent_id = '" + deptId + "'";
                this.addVillageBorder(cqlFilter);
                this.map.getView().animate({
                  center: ol.proj.fromLonLat([lng, lat]), // 中心点
                  zoom: 12.5, // 缩放级别
                  rotation: undefined, // 缩放完成view视图旋转弧度
                  duration: 1000, // 缩放持续时间，默认不需要设置
                });
              }
              const deptNode = this.findNode(this.addrOptions, deptId);
              if (deptNode && deptNode.children) {
                this.map.removeLayer(this.deptLayer);
                this.deptLayer = '';
                this.addDeptLayer(deptNode.children);
              }
            } else if (deptLevel === '2') {
              this.deptId = deptId;
              this.getData();
              let parentNodes = [];
              this.findParentNode(this.addrOptions, deptId, parentNodes);
              this.villageValue = deptId;
              this.deptName = parentNodes.map(node => node.label).join('/');
              this.currentDeptLevel = '2';
              this.map.removeLayer(this.borderLayer);
              this.borderLayer = '';
              // 添加村边界
              const cqlFilter = "dept_id = '" + deptId + "'";
              this.addVillageBorder(cqlFilter);

              let villagePoint = {
                id: deptId,
                label: feature.get('deptName'),
                lng: lng,
                lat: lat,
                deptLevel: deptLevel,
              };
              let depts = [];
              depts.push(villagePoint);
              this.map.removeLayer(this.deptLayer);
              this.deptLayer = '';
              this.addDeptLayer(depts);
              this.addLandLayer(deptId);
              this.addHomesteadLayer(deptId);
              this.map.getView().animate({
                center: ol.proj.fromLonLat([lng, lat]), // 中心点
                zoom: 17, // 缩放级别
                rotation: undefined, // 缩放完成view视图旋转弧度
                duration: 1000, // 缩放持续时间，默认不需要设置
              });
              getDept(deptId).then(res => {
                this.deptInfo.leader = res.data.leader;
                this.deptInfo.phone = res.data.phone;
              });
            }
          }
        } else {
          const viewResolution = this.map.getView().getResolution();
          const url1 = this.landLayer.getSource().getFeatureInfoUrl(evt.coordinate, viewResolution, 'EPSG:3857', {'INFO_FORMAT': 'application/json'});
          if (url1) {
            this.fetchUrl(url1);
          }
          const url2 = this.homesteadLayer.getSource().getFeatureInfoUrl(evt.coordinate, viewResolution, 'EPSG:3857', {'INFO_FORMAT': 'application/json'});
          if (url2) {
            this.fetchUrl(url2);
          }
        }
      });

      // 缩小地图，重新加载页面
      this.map.on("moveend", (evt) => {
        const zoom = this.map.getView().getZoom();
        if (this.userRole === 'cityLeader') {
          if (this.currentDeptLevel === '2' && zoom < 13) {
            this.currentDeptLevel = '3';
            this.map.removeLayer(this.borderLayer);
            this.borderLayer = "";
            const cqlFilter = "parent_id = '" + this.townId + "'";
            this.addVillageBorder(cqlFilter);

            this.map.removeLayer(this.deptLayer);
            this.deptLayer = "";
            const deptNode = this.findNode(this.addrOptions, this.townId);
            if (deptNode && deptNode.children) {
              this.addDeptLayer(deptNode.children);
            }

            this.map.removeLayer(this.landLayer);
            this.landLayer = "";
            this.map.removeLayer(this.homesteadLayer);
            this.homesteadLayer = "";
            if (this.selectedLayer) {
              this.map.removeLayer(this.selectedLayer);
              this.selectedLayer = "";
            }
            this.deptInfo.leader = null;
            this.deptInfo.phone = null;
          } else if (this.currentDeptLevel === '3' && zoom < 11) {
            this.currentDeptLevel = '4';
            this.map.removeLayer(this.borderLayer);
            this.borderLayer = "";
            this.addTownBorder(this.countyId);

            this.map.removeLayer(this.deptLayer);
            this.deptLayer = "";
            const deptNode = this.findNode(this.addrOptions, this.countyId);
            if (deptNode && deptNode.children) {
              this.addDeptLayer(deptNode.children);
            }
          } else if (this.currentDeptLevel === '4' && zoom < 9.5) {
            this.currentDeptLevel = '5';
            this.map.removeLayer(this.borderLayer);
            this.borderLayer = "";
            this.addCountyBorder();

            this.map.removeLayer(this.deptLayer);
            this.deptLayer = "";
            const deptNode = this.findNode(this.addrOptions, this.cityId);
            if (deptNode && deptNode.children) {
              this.addDeptLayer(deptNode.children);
            }
          }
        } else if (this.userRole === 'countyLeader') {
          if (this.currentDeptLevel === '2' && zoom < 13) {
            this.currentDeptLevel = '3';
            this.map.removeLayer(this.borderLayer);
            this.borderLayer = "";
            const cqlFilter = "parent_id = '" + this.townId + "'";
            this.addVillageBorder(cqlFilter);

            this.map.removeLayer(this.deptLayer);
            this.deptLayer = "";
            const deptNode = this.findNode(this.addrOptions, this.townId);
            if (deptNode && deptNode.children) {
              this.addDeptLayer(deptNode.children);
            }

            this.map.removeLayer(this.landLayer);
            this.landLayer = "";
            this.map.removeLayer(this.homesteadLayer);
            this.homesteadLayer = "";
            if (this.selectedLayer) {
              this.map.removeLayer(this.selectedLayer);
              this.selectedLayer = "";
            }
            this.deptInfo.leader = null;
            this.deptInfo.phone = null;
          } else if (this.currentDeptLevel === '3' && zoom < 11) {
            this.currentDeptLevel = '4';
            this.map.removeLayer(this.borderLayer);
            this.borderLayer = "";
            this.addTownBorder(this.countyId);

            this.map.removeLayer(this.deptLayer);
            this.deptLayer = "";
            const deptNode = this.findNode(this.addrOptions, this.countyId);
            if (deptNode && deptNode.children) {
              this.addDeptLayer(deptNode.children);
            }
          }
        }
      });
    },
    findNode(tree, deptId) {
      for (const node of tree) {
        if (node.id === deptId) return node;
        if (node.children) {
          const res = this.findNode(node.children, deptId);
          if (res) return res;
        }
      }
      return null;
    },
    findParentNode(tree, deptId, result) {
      for (let node of tree) {
        if (node.id === deptId) {
          result.unshift(node);
          return true;
        }
        if (node.children && node.children.length > 0) {
          let isFind = this.findParentNode(node.children, deptId, result);
          if (isFind) {
            result.unshift(node);
            return true;
          }
        }
      }
      return false;
    },
    fetchUrl(url) {
      fetch(url)
        .then(response => response.json())
        .then(data => {
          if (data.features.length > 0) {
            let arr = data.features[0].id.split(".");
            let tableName = arr[0];
            let id = arr[1];

            this.show = false;
            this.showList = false;
            this.showZF = false;
            this.showZD = false;
            if (tableName.startsWith("t_homestead_zjdzdxx")) {
              this.showZF = true;
              this.nfItem = {
                id: id,
                zdmj: data.features[0].properties.ZDMJ,
              };
            }
            if (tableName.startsWith("t_sys_dk")) {
              this.showZD = true;
              this.ndItem = {
                id: id,
                scmjm: data.features[0].properties.SCMJM,
              };
            }

            if (this.selectedLayer) {
              this.map.removeLayer(this.selectedLayer);
              this.selectedLayer = "";
            }
            this.selectedLayer = new ol.layer.Vector({
              source: new ol.source.Vector({
                features: new ol.format.GeoJSON().readFeatures(data)
              }),
              name: 'selectedLayer',
              style: new ol.style.Style({
                fill: new ol.style.Fill({
                  //矢量图层填充颜色，以及透明度
                  color: "rgba(255, 84, 87, 0.3)",
                }),
                stroke: new ol.style.Stroke({
                  //边界样式
                  color: "#ff5457",
                  width: 3,
                }),
              })
            });
            this.map.addLayer(this.selectedLayer);
            // this.map.getLayers().insertAt(4, this.selectedHomesteadLayer);
          }
        });
    },
    // 添加区县边界
    addCountyBorder() {
      this.borderLayer = new ol.layer.Image({
        source: new ol.source.ImageWMS({
          url: this.mapGeoServerUrl + '/wms',
          params: {
            LAYERS: this.countyBorderLayerName,
            SRID: 3857,
          }
        }),
        name: 'countyBorderLayer'
      });
      this.map.getLayers().insertAt(2, this.borderLayer);
    },
    // 添加乡镇边界
    addTownBorder(deptId) {
      this.borderLayer = new ol.layer.Image({
        source: new ol.source.ImageWMS({
          url: this.mapGeoServerUrl +  "/wms",
          params: {
            LAYERS: this.townBorderLayerName,
            // TILED: true,
            cql_filter: "parent_id = '" + deptId + "'",
            SRID: 3857,
          },
        }),
        name: 'townBorderLayer'
      });
      this.map.getLayers().insertAt(2, this.borderLayer);
    },
    // 添加村边界
    addVillageBorder(cqlFilter) {
      this.borderLayer = new ol.layer.Image({
        source: new ol.source.ImageWMS({
          url: this.mapGeoServerUrl + '/wms',
          params: {
            LAYERS: this.villageBorderLayerName,
            cql_filter: cqlFilter,
            SRID: 3857,
          },
        }),
        name: 'villageBorderLayer'
      });
      this.map.getLayers().insertAt(2, this.borderLayer);
    },
    // 创建矢量数据源
    addDeptLayer(depts) {
      const createFeatureStyle = function(feature) {
        return new ol.style.Style({
          image: new ol.style.Icon({
            //设置图标偏移
            anchor: [0.5, 1],
            //标注样式的起点位置
            anchorOrigin: "top-right",
            //X方向单位：分数
            anchorXUnits: "fraction",
            //Y方向单位：像素
            anchorYUnits: "pixels",
            //偏移起点位置的方向
            offsetOrigin: "top-right",
            //透明度
            opacity: 0.9,
            // rotation: (Math.PI / 180) * 20,
            //图片路径
            src: require("../../assets/images/plotPremises/mark.png"),
          }),
          text: new ol.style.Text({
            textAlign: "center", //位置
            textBaseline: "bottom", //基准线
            font: "normal 14px 微软雅黑", //文字样式
            text: feature.get("deptName"), //文本内容
            fill: new ol.style.Fill({
              //文本填充样式（即文字颜色)
              color: "#ffffff",
            }),
          }),
        });
      };
      let features = [];
      for (let i = 0; i < depts.length; i++) {
        let feature = new ol.Feature({
          geometry: new ol.geom.Point(
            ol.proj.fromLonLat([depts[i].lng, depts[i].lat])
          ),
          deptId: depts[i].id,
          deptName: depts[i].label,
          // orgCode: depts[i].orgCode,
          lat: depts[i].lat,
          lng: depts[i].lng,
          deptLevel: depts[i].deptLevel,
          level: 'deptPoint',
        });
        // 创建下级部门坐标点
        feature.setStyle(createFeatureStyle(feature));
        features.push(feature);
      }
      const vectorSource = new ol.source.Vector({
        features: features,
      });
      // 创建矢量图层
      this.deptLayer = new ol.layer.Vector({
        source: vectorSource,
        name: 'deptLayer'
      });
      // this.map.addLayer(this.deptLayer);
      this.map.getLayers().insertAt(3, this.deptLayer);
    },
    // 添加地块图层
    addLandLayer(deptId) {
      this.landLayer = new ol.layer.Image({
        source: new ol.source.ImageWMS({
          url: "http://218.59.175.43:8090/geoserver/zjd_dc/wms",     // 测试用的geoserver服务器链接，正式使用时需要换掉
          params: {
            LAYERS: "zjd_dc:t_sys_dk_mobile",                        // 测试用的图层，正式使用时要换成自己发布的图层
            cql_filter: "dept_id = '" + deptId + "'",
            SRID: 3857,
          }
        }),
        name: 'landLayer'
      });
      this.map.addLayer(this.landLayer);
      // this.map.getLayers().insertAt(3, this.landLayer);
    },
    // 添加宅基地图层
    addHomesteadLayer(deptId) {
      this.homesteadLayer = new ol.layer.Image({
        source: new ol.source.ImageWMS({
          url: "http://218.59.175.43:8090/geoserver/zjd_dc/wms",     // 测试用的geoserver服务器链接，正式使用时需要换掉
          params: {
            LAYERS: "zjd_dc:t_homestead_zjdzdxx_mobile",             // 测试用的图层，正式使用时要换成自己发布的图层
            cql_filter: "dept_id = '" + deptId + "'",
            SRID: 3857,
          }
        }),
        name: 'homesteadLayer'
      });
      this.map.addLayer(this.homesteadLayer);
      // this.map.getLayers().insertAt(3, this.homesteadLayer);
    },
    drawMap(selectedOptions) {
      const villageNode = selectedOptions[selectedOptions.length - 1];
      const ids = selectedOptions.map(option => option.id);

      this.currentDeptLevel = '2';
      this.townId = ids[ids.length - 2];
      this.countyId = ids[ids.length - 3];
      this.map.removeLayer(this.borderLayer);
      this.borderLayer = '';
      // 添加村边界
      const cqlFilter = "dept_id = '" + villageNode.id + "'";
      this.addVillageBorder(cqlFilter);

      let villagePoint = {
        id: villageNode.id,
        label: villageNode.label,
        lng: villageNode.lng,
        lat: villageNode.lat,
        deptLevel: villageNode.deptLevel,
      };
      let depts = [];
      depts.push(villagePoint);
      this.map.removeLayer(this.deptLayer);
      this.deptLayer = '';
      this.addDeptLayer(depts);

      if (this.landLayer) {
        this.map.removeLayer(this.landLayer);
        this.landLayer = '';
      }
      if (this.homesteadLayer) {
        this.map.removeLayer(this.homesteadLayer);
        this.homesteadLayer = '';
      }
      if (this.selectedLayer) {
        this.map.removeLayer(this.selectedLayer);
        this.selectedLayer = "";
      }
      this.addLandLayer(villageNode.id);
      this.addHomesteadLayer(villageNode.id);
      this.map.getView().animate({
        center: ol.proj.fromLonLat([villageNode.lng, villageNode.lat]), // 中心点
        zoom: 17, // 缩放级别
        rotation: undefined, // 缩放完成view视图旋转弧度
        duration: 1000, // 缩放持续时间，默认不需要设置
      });
    },
  },
};
</script>

<style scoped lang="scss">
  .home_wrapper {
    background: #e9e9e9;
    min-height: 100vh;
    width: 100vw;
  }
  .num{
    font-family: Arial;
  }
  .map_main{
    width: 100%;
    height: 100vh;
    /*background: url("../../../static/images/plotPremises/map_bg.png") no-repeat center;*/
    /*background-size: 100%;*/
  }
  /deep/ .van-popup{
    background: #F1F0F5;
  }
  /deep/ .van-popup--right{
    top: 35%;
    .van-icon__image{
      width: .7em;
      height: .7em;
      display: block;
    }
  }
  .top_address{
    display: flex;
    align-items: center;
    position: absolute;
    top: 5vh;
    left: 3vw;
    padding: 1vh 2vh;
    background: #ffffff;
    border-radius: 5vh;
    p{font-size: 1.5vh}
  }
  .address_icon {
    width: 13PX;
    height: 17PX;
    background: url("../../../static/images/plotPremises/positioning.png") no-repeat;
    background-size: 100% 100%;
    margin-right: 1vw;
  }
  .pop_main{
    padding: 2vh 3vw;
    .pop_title{
      display: flex;
      align-items: center;
      font-size: 2.2vh;
      line-height: 1;
    }
    .pop_content{
      display: flex;
      justify-content: space-between;
      margin-top: 2vh;
      .pop_content_left{
        background: #ffffff;
        width: 48%;
        padding: 1.5vh 3vw;
        border-radius: 15PX;
        .pop_content_left_box{
          display: flex;
          justify-content: space-between;
          margin-top: .5vh;
          .border{
            border-left: 2PX dashed #DFDFDF;
          }
          div{
            p{
              &:first-child{
                font-size: 2vh;
                color: #797979;
                span{
                  font-size: 1.5vh;
                }
              }
              &:last-child{
                font-size: 4vw;
                color: #333333;
              }
            }
            &:last-child{
              p:last-child{
                color: #1B65F8;
              }
            }
          }
        }
      }
    }
    .pop_content_zd{
      background: #ffffff;
      border-radius: 15PX;
      display: flex;
      justify-content: space-between;
      margin-top: 2vh;
      overflow: hidden;
      img{width: 40%;}
      .pop_content_zd_right{
        width: 60%;
        padding:1.5vh 2.5vh;
        font-size: 1.8vh;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
      }
    }
  }
  .pop_main_right{

    .pop_title{
      font-size: 2.2vh;
      color: #1B65F8;
      padding: 1.5vh;
    }

    .pop_content_right{
      font-size: 1.8vh;
      height: 48vh;
      overflow-y: scroll;
      .active{
        box-shadow:0px 0px 5px #999999;
      }
      .van-row{
        padding: 1vh 0;
      }
      .num{text-align: center;}
    }

    .pop_btn_right{
      display: flex;
      width: 100%;
      position: absolute;
      bottom: 0;
      p{
        padding: 1.5vh 0;
        text-align: center;
        font-size: 2vh;
        flex: 1;
        background: #E1E0E4;
        color: #9F9F9F;
      }
    }

  }
</style>
