<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>羊亭</p>
      <p>/北上夼</p>
    </div>

    <van-popup v-model="show" position="bottom" :overlay="false" round>
      <div class="pop_main">

        <div class="pop_title">
          <i class="address_icon"></i>
          <p>羊亭镇-北上夼村</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">352</p>
              </div>
              <span class="border"></span>
              <div>
                <p>可租 <span>(栋)</span></p>
                <p class="num" @click="showList = true,activeName='nf'">71</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">352</p>
              </div>
              <span class="border"></span>
              <div>
                <p>可租 <span>(亩)</span></p>
                <p class="num" @click="showList = true,activeName='nd'">71</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>羊亭镇-北上夼村-107</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>北上夼村</van-col>
            </van-row>
            <van-row type="flex" justify="space-between">
              <van-col>租地编号：</van-col>
              <van-col class="num">310</van-col>
            </van-row>
            <van-row type="flex" justify="space-between">
              <van-col>租地面积：</van-col>
              <van-col class="num">12亩</van-col>
            </van-row>
            <van-row type="flex" justify="space-between">
              <van-col>咨询代表：</van-col>
              <van-col>张村委</van-col>
            </van-row>
            <van-row type="flex" justify="space-between">
              <van-col>咨询电话：</van-col>
              <van-col class="num">13306310631</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>羊亭镇-北上夼村-107</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>北上夼村</van-col>
            </van-row>
            <van-row type="flex" justify="space-between">
              <van-col>租房编号：</van-col>
              <van-col class="num">310</van-col>
            </van-row>
            <van-row type="flex" justify="space-between">
              <van-col>租房面积：</van-col>
              <van-col class="num">12亩</van-col>
            </van-row>
            <van-row type="flex" justify="space-between">
              <van-col>咨询代表：</van-col>
              <van-col>张村委</van-col>
            </van-row>
            <van-row type="flex" justify="space-between">
              <van-col>咨询电话：</van-col>
              <van-col class="num">13306310631</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">
          <van-row>
            <van-col span="8" offset="4">编号</van-col>
            <van-col span="9" offset="3">面积</van-col>
          </van-row>
          <van-row v-for="(item,index) in 20"
                   :key="index"
                   @click="listChange(index)"
                   :class="{ active: selectChooseOrder == index }"
          >
            <van-col span="8" offset="4" class="num">101</van-col>
            <van-col span="9" offset="3" class="num">3亩</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 { treeselect } from "@/api/agriculturalTrusteeship";

export default {
  data() {
    return {
      show:true,
      showZD:false,
      showZF:false,
      showList:false,
      showAddress:false,
      activeName:'nf',
      selectChooseOrder:-1,
      columns: [
        {
          text: '浙江',
          children: [
            {
              text: '杭州',
              children: [{ text: '西湖区' }, { text: '余杭区' }],
            },
            {
              text: '温州',
              children: [{ text: '鹿城区' }, { text: '瓯海区' }],
            },
          ],
        },
        {
          text: '福建',
          children: [
            {
              text: '福州',
              children: [{ text: '鼓楼区' }, { text: '台江区' }],
            },
            {
              text: '厦门',
              children: [{ text: '思明区' }, { text: '海沧区' }],
            },
          ],
        },
      ],
      addrOptions: [],

      map: "",                                          // 地图
      // countyBorder: "",                                 // 区县边界
      // townBorder: "",                                   // 乡镇边界
      // villageBorder: "",                                // 村边界
      borderLayer: "",                                  // 区域边界图层
      deptLayer: "",                                    // 坐标点图层
      userRole: "",                                     // 记录用户身份
      cityId: null,                                     // 记录市的deptId
      countyId: null,                                   // 记录区县的deptId
      townId: null,                                     // 记录乡镇的deptId
      deptPointLevel: null,                             // 地图上显示的坐标点级别

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

  },
  mounted() {
    // 获取geoserver的地址
    this.getGeoServerUrl();
    // 获取区县边界图层名称
    this.getCountyBorderLayerName();
    // 获取乡镇边界的图层名称
    this.getTownBorderLayerName();
    // 获取村边界的图层名称
    this.getVillageBorderLayerName();
    // 获取部门下拉树列表
    treeselect().then(response => {
      this.addrOptions = response.data;
      // 初始化地图
      this.initMap();
    });
  },
  methods: {
    tabChange(name){
      this.activeName = name;
    },
    listChange(id){
      this.selectChooseOrder = id;
      this.show = false;
      this.showZF = false;
      this.showZD = true;
    },
    //获取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.deptPointLevel = '4';
        // 添加区县边界
        this.addCountyBorder();
      } else if (dept.deptLevel === '4') {
        // 登录身份为县级领导
        this.userRole = 'countyLeader';
        this.countyId = dept.id;
        this.deptPointLevel = '3';
        // 添加乡镇边界
        this.addTownBorder(dept.id);
        this.map.getView().setZoom(10.5);
      }
      // else if (dept.deptLevel === '3') {
      //   // 登录身份为镇级领导
      //   this.userRole = 'townLeader';
      //   this.townId = dept.id;
      //   this.deptPointLevel = '2';
      //   // 添加村边界
      //   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.deptPointLevel = '3';
                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.deptPointLevel = '2';
                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.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: '-1',                  // -1代表最末级的坐标点
              };
              this.deptPointLevel = '-1';         // -1代表最末级的坐标点
              let depts = [];
              depts.push(villagePoint);
              this.map.removeLayer(this.deptLayer);
              this.deptLayer = '';
              this.addDeptLayer(depts);
              this.map.getView().animate({
                center: ol.proj.fromLonLat([lng, lat]), // 中心点
                zoom: 16, // 缩放级别
                rotation: undefined, // 缩放完成view视图旋转弧度
                duration: 1000, // 缩放持续时间，默认不需要设置
              });
            }
          }
        }
      });

      // 缩小地图，重新加载页面
      this.map.on("moveend", (evt) => {
        const zoom = this.map.getView().getZoom();
        if (this.userRole === 'cityLeader') {
          if (this.deptPointLevel === '-1' && zoom < 13) {
            this.deptPointLevel = '2';
            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);
            }
          } else if (this.deptPointLevel === '2' && zoom < 11) {
            this.deptPointLevel = '3';
            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.deptPointLevel === '3' && zoom < 9.5) {
            this.deptPointLevel = '4';
            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.deptPointLevel === '-1' && zoom < 13) {
            this.deptPointLevel = '2';
            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);
            }
          } else if (this.deptPointLevel === '2' && zoom < 11) {
            this.deptPointLevel = '3';
            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;
    },
    // 添加区县边界
    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);
    },
  },
};
</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: 3vh;
                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;
      }
    }

    .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>
