<!--  -->
<template>
  <div class="mapbox">
    <div id="container"></div>
    <div id="map" v-show="canvasdisplay" v-loading="loading">
      <!-- <div class="ol-toggle-options ol-unselectable">
            <a title="Toggle options toolbar" onClick="toggleControlPanel()"
                href="#toggle">...</a>
        </div> -->
      <div class="mapdel" @click="canvasdisplay = false">×</div>
    </div>
    <div id="wrapper">
      <div id="location"></div>
      <div id="scale"></div>
      <!-- <div id="nodelist">
            <em>Click on the map to get feature info</em>
        </div> -->
    </div>
    <div class="listBox">
      <div class="projectSearch">
        <div>项目列表</div>
        <div>
          <el-input
            size="small"
            placeholder="请输入项目名称"
            v-model="input"
            suffix-icon="el-icon-search"
            @change="getEquipList"
            clearable
          >
          </el-input>
        </div>
      </div>
      <div class="inner">
        <div class="scroll">
          <el-scrollbar>
            <div class="equipList">
              <div
                class="item"
                @click="equipLocate(item)"
                @dblclick="enterBase(item.uid)"
                v-for="item in mapData"
                :key="item.uuid"
              >
                <img
                  src="../../../../static/images/baseIcon.png"
                  width="25px"
                  alt=""
                />
                {{ item.projectname }}
              </div>
              <div class="item noDate" v-if="!mapData.length">暂无数据</div>
            </div>
          </el-scrollbar>
        </div>
      </div>
    </div>
    <el-dialog
      title="一号基地"
      :visible.sync="dialogVisible"
      width="30%"
      top="15%"
    >
      <div class="baseinfobox">
        <p>负责人：老张</p>
        <p>联系方式：12021090909</p>
        <p>面积：50亩</p>
        <p>地址：河南省郑州市金水区</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="sureclick">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="设备信息"
      :visible.sync="dialogbaseinfo"
      width="30%"
      top="15%"
    >
      <div class="baseinfobox">
        <p>设备名称：杀虫灯</p>
        <p>设备id：1111111111111111</p>
        <p>地址：河南省郑州市金水区</p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogbaseinfo = false">取 消</el-button>
        <el-button type="primary" @click="dialogbaseinfo = false">确 定</el-button>
      </span>
    </el-dialog>
    <div id="marker" style="width: 60px; height: 17px"></div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      map: null,
      polyEditor: null,
      path: [
        [113.68140126451851, 34.81200282135321],
        [113.68242785774319, 34.81199264120153],
        [113.68244463980199, 34.81117921221168],
        [113.68139715166922, 34.81116052257837],
      ],
      marker: null,
      markers: [],
      markerstwo: [],
      polygon: null,
      canvasdisplay: false,
      dialogVisible: false,
      loading: false,
      input: "", //基地搜索框
      mapData: [
        {
          projectname: "一号基地",
          uuid: 1,
        },
        {
          projectname: "二号基地",
          uuid: 2,
        },
        {
          projectname: "三号基地",
          uuid: 3,
        },
        {
          projectname: "四号基地",
          uuid: 4,
        },
      ],
      dialogbaseinfo:false,//设备信息弹框
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    //初始化地图事件
    initmap() {
      this.map = new AMap.Map("container", {
        resizeEnable: true,
        expandZoomRange: true,
        center: [113.681471, 34.810371], //中心点
        zoom: 15, //初始化缩放等级
        zooms: [3, 24], //设置最大、最小缩放等级
        layers: [new AMap.TileLayer.Satellite()], //加载卫星图
      });
      this.map.on("click", (e) => {
        console.log(e.lnglat);
        // var arr = [e.lnglat.lng, e.lnglat.lat];
        // this.addmarker(e.lnglat.lng, e.lnglat.lat);
        // this.path.push(arr);
      });
      this.addpolygon();
      this.addmarker();
    },
    //添加标点事件
    addmarker() {
      var marker = new AMap.Marker({
        icon: "../../../../static/images/jidi2.png",
        position: [113.68189478963615, 34.81164827843166],
      });
      marker.on("click", (e) => {
        this.dialogbaseinfo = true;
        // this.canvasdisplay = true;
      });
      // marker.setMap(this.map);
      this.map.add(marker);
      // this.marker = marker
      this.markers.push(marker);
    },
    //点击标点事件
    // updateMarker(lng, lat, marker) {
    //   console.log(lng);
    //   // 自定义点标记内容
    //   var markerContent = document.createElement("div");
    //   // 点标记中的图标
    //   var markerImg = document.createElement("img");
    //   markerImg.className = "markerlnglat";
    //   markerImg.src = "http://webapi.amap.com/theme/v1.3/markers/n/mark_r.png";
    //   markerContent.appendChild(markerImg);

    //   // 点标记中的文本
    //   // var markerSpan = document.createElement("span");
    //   // markerSpan.className = "marker";
    //   // markerSpan.innerHTML = "Hi，我换新装备啦！";
    //   // markerContent.appendChild(markerSpan);

    //   marker.setContent(markerContent); //更新点标记内容
    //   marker.setPosition([lng, lat]); //更新点标记位置
    //   this.markerstwo.push(marker);
    // },
    //初始化圈地
    addpolygon() {
      var polygon = new AMap.Polygon({
        path: this.path,
        strokeColor: "#FF33FF", //外围边框颜色
        strokeWeight: 6,
        strokeOpacity: 0.2,
        fillOpacity: 0.4,
        fillColor: "#1791fc", //内部颜色
        zIndex: 50,
      });
      polygon.on("click", (e) => {
        this.dialogVisible = true;
        console.log(e);
      });
      this.polygon = polygon;
      this.map.add(polygon);
      // 缩放地图到合适的视野级别
      this.map.setFitView([polygon]);
    },
    //   var polyEditor = new AMap.PolyEditor(this.map, polygon);
    //   this.polyEditor = polyEditor;
    //   polyEditor.on("addnode", function (event) {
    //     console.log("触发事件：addnode");
    //   });

    //   polyEditor.on("adjust", function (event) {
    //     console.log("触发事件：adjust");
    //   });

    //   polyEditor.on("removenode", function (event) {
    //     console.log("触发事件：removenode");
    //   });

    //   polyEditor.on("end", function (event) {
    //     console.log("触发事件： end");
    //   });
    // },
    // //创建新的地块
    // polyEditoradd() {
    //   if(this.polygon){
    //     this.$message({
    //       message: "亲,您已存在一个地块了！",
    //       type: "warning",
    //     });
    //   }else{
    //     if (this.path.length<3) {
    //     this.$message({
    //       message: "亲,您还没有选定地块的区域哦！",
    //       type: "warning",
    //     });
    //   } else {
    //     // this.addpolygon();
    //     this.deleteall();
    //   }
    //   }
    // },
    // //开始圈地
    // polyEditoropen() {
    //   if (this.path.length == 0) {
    //     this.$message({
    //       message: "亲,您还没有创建地块哦！",
    //       type: "warning",
    //     });
    //   } else {
    //     this.polyEditor.open();
    //   }
    // },
    // //结束圈地
    // polyEditorclose() {
    //   if (this.path.length == 0) {
    //     this.$message({
    //       message: "亲,您还没有创建地块哦！",
    //       type: "warning",
    //     });
    //   } else {
    //     this.polyEditor.close();
    //   }
    // },
    // //删除地块
    // polyEditordel() {
    //   if (this.polygon) {
    //     this.$message({
    //       message: "亲,您还没有创建地块哦！",
    //       type: "warning",
    //     });
    //   } else {
    //     this.map.remove(this.polygon);
    //   }
    // },
    // 切片转经度
    tile2lon(x, z) {
      return (x / Math.pow(2, z)) * 360 - 180;
    },
    // 切片转纬度
    tile2lat(y, z) {
      var n = Math.PI - (2 * Math.PI * y) / Math.pow(2, z);
      return (180 / Math.PI) * Math.atan(0.5 * (Math.exp(n) - Math.exp(-n)));
    },
    addWMSLayer() {
      var that = this;
      var resolutions = [];
      for (var i = 0; i < 19; i++) {
        resolutions[i] = Math.pow(2, 18 - i);
      }
      var tileLayer = new AMap.TileLayer({
        tileSize: 256,
        tileUrl: function (x, y, z) {
          let xmin = that.tile2lon(x, z);
          let xmax = that.tile2lon(x + 1, z);
          let ymin = that.tile2lat(y + 1, z);
          let ymax = that.tile2lat(y, z);
          // console.log(xmin, ymin)
          // 转换对应坐标
          // console.log(xmin, ymin);
          // console.log(xmax, ymax);
          let t1 = gcoord.transform(
            [xmin, ymin],
            gcoord.GCJ02,
            gcoord.EPSG3857
          );
          let t2 = gcoord.transform(
            [xmax, ymax],
            gcoord.GCJ02,
            gcoord.EPSG3857
          );
          // console.log(t1,t2)
          // 查询对象
          let url = "http://192.168.1.17:18080/geoserver/zhai/wms?";
          let params = {
            service: "WMS",
            version: "1.3.0",
            transparent: true,
            request: "GetMap",
            layers: "zhai:result",
            width: 769,
            height: 620,
            srs: "EPSG:3857",
            format: "image/png",
            bbox: [t1[0], t1[1], t2[0], t2[1]].join(","),
          };
          // 构建查询字符串
          let str = that.objToParams(params);

          return url + str;
        },
        zIndex: 10,
      });
      this.map.add(tileLayer);
      // var url =
      //   "https://webapi.amap.com/maps?v=1.4.15&key=27273b81090f78759e4057f94474516f&plugin=AMap.PolyEditor";
      // var jsapi = document.createElement("script");
      // jsapi.charset = "utf-8";
      // jsapi.src = url;
      // document.head.appendChild(jsapi);
    },
    //构建查询字符串
    objToParams(obj) {
      return Object.keys(obj)
        .map(function (key) {
          return ""
            .concat(encodeURIComponent(key), "=")
            .concat(encodeURIComponent(obj[key]));
        })
        .join("&");
    },
    //添加canvas 实现方法查看
    addcanvas() {
      let t1 = gcoord.transform(
        [113.67756042972206, 34.80739645121581],
        gcoord.GCJ02,
        gcoord.EPSG3857
      );
      let t2 = gcoord.transform(
        [113.68402446359391, 34.8139473227472],
        gcoord.GCJ02,
        gcoord.EPSG3857
      );
      console.log(t1, t2);
      var bounds = [t1[0], t1[1], t2[0], t2[1]];
      console.log(bounds);

      var format = "image/png";
      var mousePositionControl = new ol.control.MousePosition({
        // className: "custom-mouse-position",
        // target: document.getElementById("location"),
        // coordinateFormat: ol.coordinate.createStringXY(5),
        // undefinedHTML: "&nbsp;",
      });
      var source = new ol.source.ImageWMS({
        ratio: 1,
        url: "http://192.168.1.17:18080/geoserver/zhai/wms",
        params: {
          FORMAT: format,
          VERSION: "1.1.1",
          STYLES: "",
          LAYERS: "zhai:result",
          exceptions: "application/vnd.ogc.se_inimage",
        },
      });

      var untiled = new ol.layer.Image({
        source: source,
      });
      source.on("imageloadend", (val) => {
        // console.log(val);
        this.loading = false;
      });
      source.on("imageloaderror", function () {
        alert(11111);
      });
      var source2 = new ol.source.TileWMS({
        url: "http://192.168.1.17:18080/geoserver/zhai/wms",
        params: {
          FORMAT: format,
          VERSION: "1.1.1",
          tiled: true,
          STYLES: "",
          LAYERS: "zhai:result",
          exceptions: "application/vnd.ogc.se_inimage",
          tilesOrigin: bounds[0] + "," + bounds[1], //bounds 的第一项
          bbox: "",
        },
      });
      var tiled = new ol.layer.Tile({
        visible: false,
        source: source2,
      });
      var createLabelStyle = function (feature) {
        //返回一个样式
        return new ol.style.Style({
          image: new ol.style.Icon({
            //控制标注图片和文字之间的距离
            anchor: [0.5, 60],
            //标注样式的起点位置
            anchorOrigin: "top-right",
            //X方向单位：分数
            anchorXUnits: "fraction",
            //Y方向单位：像素
            anchorYUnits: "pixels",
            //偏移起点位置的方向
            offsetOrigin: "top-right",
            //透明度
            opacity: 0.75,
            //图片路径
            src: "../../../../static/images/jidi2.png",
          }),
          //文本样式
          text: new ol.style.Text({
            //对齐方式
            textAlign: "center",
            //文本基线
            textBaseline: "middle",
            //字体样式
            font: "normal 14px 微软雅黑",
            //文本内容
            text: feature.get("name"),
            //填充样式
            fill: new ol.style.Fill({
              color: "#aa3300",
            }),
            //笔触
            stroke: new ol.style.Stroke({
              color: "#ffcc33",
              width: 2,
            }),
          }),
        });
      };
      var beijing = gcoord.transform(
        [113.68258608341216, 34.811427520345376],
        gcoord.GCJ02,
        gcoord.EPSG3857
      );
      var map = new ol.Map({
        controls: ol.control
          .defaults({
            attribution: false,
          })
          .extend([mousePositionControl]),
        target: "map",
        layers: [untiled, tiled],
        view: new ol.View({
          // projection: projection,
          // center: beijing,
          // zoom: 6,
          // minZoom: 2,
        }),
      });
      //初始化要素
      var iconFeature = new ol.Feature({
        //点要素
        geometry: new ol.geom.Point(beijing),
        //名称属性
        name: "设备一号",
        //人口属性
        // population: 2115,
      });
      //为点要素添加样式
      iconFeature.setStyle(createLabelStyle(iconFeature));
      //初始化矢量数据源
      var vectorSource = new ol.source.Vector({
        //指定要素
        features: [iconFeature],
      });

      //初始化矢量图层
      var vectorLayer = new ol.layer.Vector({
        //数据源
        source: vectorSource,
      });

      //将矢量图层添加到map中
      map.addLayer(vectorLayer);
      //初始化覆盖层标注
      // var markerclick = document.getElementById("marker");
      // var marker = new ol.Overlay({
      //   //位置坐标
      //   position: beijing,
      //   //覆盖层如何与位置坐标匹配
      //   positioning: "center-center",
      //   //覆盖层的元素
      //   element: markerclick, //ToDo 此处不能用JQuery方式$('#marker')获取元素
      //   //事件传播到地图视点的时候是否应该停止
      //   stopEvent: false,
      // });
      // map.addOverlay(marker);
      // console.log(markerclick);
      // markerclick.addEventListener("click", function (e) {
      //   //生效
      //   console.log(e);
      // });
      // markerclick.on("click", function () {
      //   //生效
      //   alert("点击地图覆盖物!");
      // });
      // map.getView().on("change:resolution", function (evt) {
      //   var resolution = evt.target.get("resolution");
      //   var units = map.getView().getProjection().getUnits();
      //   // console.log(units)
      //   var dpi = 25.4 / 0.28;
      //   // console.log(ol.proj)
      //   var mpu = ol.proj.Units.METERS_PER_UNIT[units];
      //   var scale = resolution * mpu * 39.37 * dpi;
      //   if (scale >= 9500 && scale <= 950000) {
      //     scale = Math.round(scale / 1000) + "K";
      //   } else if (scale >= 950000) {
      //     scale = Math.round(scale / 1000000) + "M";
      //   } else {
      //     scale = Math.round(scale);
      //   }
      //   document.getElementById("scale").innerHTML = "Scale = 1 : " + scale;
      // });
      // console.log(map.getSize())
      map.getView().fit(bounds, [768, 754]);
    },
    //基地搜索
    getEquipList() {},
    //基地点击
    equipLocate() {},
    //基地双击
    enterBase() {},
    sureclick() {
      this.dialogVisible = false;
      this.canvasdisplay = true;
      var canvar = document.getElementsByClassName("ol-viewport");
      console.log(canvar);
      if (canvar.length == 0) {
        this.loading = true;
        this.addcanvas();
      }
    },
  },
  beforeCreate() {}, //生命周期 - 创建之前
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  beforeMount() {}, //生命周期 - 挂载之前
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    this.initmap();
    this.addWMSLayer();
  },
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang="less" scoped>
.mapbox {
  height: 100%;
  position: relative;
}
#container {
  height: 100%;
}
.input-card {
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: #fff;
  background-clip: border-box;
  border-radius: 3px;
  width: 264px;
  border-width: 0;
  border-radius: 4.8px;
  box-shadow: 0 2px 6px 0 rgba(116, 114, 245, 0.5);
  position: fixed;
  bottom: 12px;
  right: 12px;
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
  padding: 9px 15px;
  .btn {
    display: inline-block;
    font-weight: 400;
    text-align: center;
    white-space: nowrap;
    vertical-align: middle;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    border: 1px solid transparent;
    // transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,
    //   border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
    background-color: transparent;
    background-image: none;
    color: #25a5f7;
    border-color: #25a5f7;
    padding: 3px 6px;
    line-height: 1.5;
    border-radius: 12px;
    -webkit-appearance: button;
    cursor: pointer;
    font-size: 12px;
    margin-bottom: 5px;
    outline-color: #fff;
  }
  .btn:hover {
    background-color: #25a5f7;
    color: #fff;
  }
}
.ol-zoom {
  top: 52px;
  /* display: none; */
}

.ol-toggle-options {
  z-index: 1000;
  background: rgba(255, 255, 255, 0.4);
  border-radius: 4px;
  padding: 2px;
  position: absolute;
  left: 8px;
  top: 8px;
  display: none;
}

body {
  font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
  font-size: small;
}

iframe {
  width: 100%;
  height: 250px;
  border: none;
}

#map {
  clear: both;
  position: absolute;
  top: 0;
  left: 0;
  width: 768px;
  height: 754px;
  border-right: 4px solid #182037;
  border-bottom: 4px solid #182037;
  .mapdel {
    position: absolute;
    top: 0;
    right: 0;
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background-color: rgba(128, 128, 128, 0.8);
    text-align: center;
    line-height: 30px;
    font-size: 25px;
    color: #fff;
    z-index: 99;
  }
}

#wrapper {
  width: 768px;
  position: relative;
  z-index: 999999;
  background-color: #fff;
  display: none;
}

#location {
  float: right;
}

/* Styles used by the default GetFeatureInfo output, added to make IE happy */
table.featureInfo,
table.featureInfo td,
table.featureInfo th {
  border: 1px solid #ddd;
  border-collapse: collapse;
  margin: 0;
  padding: 0;
  font-size: 90%;
  padding: 0.2em 0.1em;
}

table.featureInfo th {
  padding: 0.2em 0.2em;
  font-weight: bold;
  background: #eee;
}

table.featureInfo td {
  background: #fff;
}

table.featureInfo tr.odd td {
  background: #eee;
}

table.featureInfo caption {
  text-align: left;
  font-size: 100%;
  font-weight: bold;
  padding: 0.2em 0.2em;
}
.baseinfobox {
  padding-left: 30px;
  p {
    margin-bottom: 10px;
  }
}
.listBox {
  position: absolute;
  overflow: hidden;
  width: 4.25rem;
  height: 90%;
  margin-top: 16px;
  border-radius: 6px;
  background: rgba(255, 255, 255, 0.58);
  box-shadow: 0px 3px 9px 0px #a7a7a7;
  right: 20px;
  top: 0;
  .projectSearch {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0.15rem;
    background: #182037;
    color: #fff;
    font-size: 0.175rem;
    border-radius: 6px 6px 0 0;
    /deep/.el-input {
      width: 2.5rem;
    }
  }
  .inner {
    position: absolute;
    top: 57px;
    bottom: -18px;
    left: 0;
    right: 0;
    .scroll {
      height: 100%;
      overflow: auto;
      .equipList {
        .item {
          padding: 0.175rem;
          color: #454545;
          font-size: 0.175rem;
          // background: red;
          cursor: pointer;
          img {
            vertical-align: middle;
            margin-right: 2px;
          }
          &:hover {
            background: #182037;
            color: #fff;
          }
        }
        .noDate {
          text-align: center;
        }
        .item.active {
          background: darkblue;
        }
      }
    }
    .scroll {
      height: 100%;
      overflow-y: hidden;
    }
    .el-scrollbar {
      height: 100%;
    }
    .el-scrollbar__bar {
      &.is-vertical {
        width: 100px; //滚动条宽度
      }
    }
    .el-scrollbar__wrap {
      overflow-y: auto;
      overflow-x: hidden;
    }
    .el-scrollbar__thumb {
      // 可设置滚动条颜色
      background: red;
    }
  }
}
</style>