<template>
  <div class="map-box">
    <div class="map-grid" ref="mapContainer"></div>
    <div class="menu-wrap">
      <div class="please-box">
        <span>请选择</span>
        <i class="el-icon-arrow-up" />
      </div>
      <el-tree
        :data="mapMenuData"
        node-key="id"
        default-expand-all
        show-checkbox
        :highlight-current="true"
        :expand-on-click-node="false"
        :check-on-click-node="true"
        :default-checked-keys="checkedKeys"
        @check-change="handleCheckClick"
        class="tree-box"
        ref="tree"
      >
        <span class="custom-tree-node" slot-scope="{ node }">
          <span class="tree-title-box">
            <span class="tree-title">{{ node.label }}</span>
          </span>
        </span>
      </el-tree>
      <el-pagination
            @current-change="handleCurrentChange"
            layout="->,total,prev,next"
            :total="total"
            :current-page="pageNum"
            class="pagi-box"
        ></el-pagination>
    </div>
  </div>
</template>
<script>
import WKT from "terraformer-wkt-parser";
import { getUserDefaultLoc } from '@/api/customRadar/customRadar.js'
export default {
  name: "BMapCreateFirstGrid",
  props: ["mapMenuData", "shapeIds","total","pageNum"],
  data() {
    return {
      checkedKeys: [],
      polygonArr: [],
      layerInfo: {
        strokeColor: "#2094ff",
        strokeWeight: 2,
        strokeOpacity: 0.8,
        strokeStyle: "solid",
        fillColor: "#2094ff",
        fillOpacity: 0.4,
      },
    };
  },
  watch: {
    mapMenuData: {
      handler(newVal) {
        this.showWKT(newVal);
      },
      deep: true,
    },
    checkedKeys: {
      handler(newVal, oldVal) {
        this.$emit("set-checkedkey", newVal);
      },
    },
    shapeIds(val) {
      this.checkedKeys = val;
      this.$refs.tree.setCheckedKeys(this.checkedKeys);
    },
    polygonArr(val) {
      if (val.length > 0 && this.shapeIds.length > 0) {
        this.shapeIds.map((shapeId) => {
          const item = val.find((v) => v.shapeId === shapeId);
          if (item) {
            item.polygon.setFillOpacity(0.2);
            item.polygon.setFillColor("red");
            item.polygon.setStrokeColor("red");
          }
        });
      }
    },
  },
  mounted() {
    this.initMap();
  },
  methods: {
    handleCurrentChange(num){
      this.$emit('handleCurrentChange',num);
    },
    // 初始化地图
    initMap() {
      this.mapLoading = true;
      this.map = new BMapGL.Map(this.$refs.mapContainer);
      getUserDefaultLoc().then((res) => {
        if (res.code === 200) {
          const locationAddress = res?.data?.address || '临海市'
          this.map.centerAndZoom(locationAddress, 14)
        }
      })
      this.map.enableScrollWheelZoom();
    },
    /**
     * 树节点被点击事件单选的逻辑不要了，要多选
     */
    handleCheckClick(data, checked, self) {
      this.checkedKeys = this.$refs.tree.getCheckedKeys();
      const item = this.polygonArr.find((v) => v.shapeId === data.shapeId);
      // 选中
      if (item) {
        if (checked) {
          // this.setAllFillColor();
          item.polygon.setFillOpacity(0.2);
          item.polygon.setFillColor("red");
          item.polygon.setStrokeColor("red");
          this.map.centerAndZoom(item.polygon.points[0].latLng, 14);
        } else {
          item.polygon.setFillOpacity(0.4);
          item.polygon.setFillColor(this.layerInfo.strokeColor);
          item.polygon.setStrokeColor(this.layerInfo.strokeColor);
        }
      }
      // this.$refs.tree.setCheckedNodes([]);
      // this.$refs.tree.setCheckedNodes([data]);
    },
    chooseColor() {},
    showWKT(data) {
      this.polygonArr = [];
      this.map.clearOverlays();
      data.map((item) => {
        if (item.disabled) return;
        const wkt = item.shapeWkt;
        const geojson = WKT.parse(wkt);
        this.renderPolygon(geojson.coordinates, item.shapeId);
      });
    },
    /**
     * 绘制多边形覆盖物
     */
    renderPolygon(coordinates, id) {
      const than = this;
      let points = [];
      coordinates.map((ring) => {
        points = ring.map((coord) => {
          return new BMapGL.Point(coord[0], coord[1]);
        });
      });
      const polygon = new BMapGL.Polygon(points, {
        ...this.layerInfo,
        shapeId: id, // 添加额外的属性
      });
      polygon.addEventListener("click", function (e) {
        than.handlerPolygon(e.target);
      });
      this.polygonArr.push({
        polygon: polygon,
        shapeId: id,
      });
      this.map.addOverlay(polygon);
      polygon.show();
      this.map.centerAndZoom(points[0], 14);
    },
    /**
     * 多边形点击事件
     */
    handlerPolygon(polygon) {
      const currentColor = polygon.getFillColor();
      const shapeId = polygon._config.shapeId;
      const shapeItem = this.mapMenuData.find(
        (shape) => shape.shapeId === shapeId
      );
      if (shapeItem) {
        if (this.checkedKeys.includes(shapeItem.shapeId)) {
          const index = this.checkedKeys.findIndex(
            (v) => v === shapeItem.shapeId
          );
          if (index > -1) this.checkedKeys.splice(index, 1);
        } else {
          this.checkedKeys = [...this.checkedKeys, shapeItem.shapeId];
        }
        this.$refs.tree.setCheckedKeys(this.checkedKeys);
      } else {
        this.$message({
          type: "info",
          message: "未找到图形信息",
        });
      }
      if (currentColor === this.layerInfo.strokeColor) {
        // this.setAllFillColor();
        polygon.setFillOpacity(0.2);
        polygon.setFillColor("red");
        polygon.setStrokeColor("red");
      } else {
        polygon.setFillOpacity(0.4);
        polygon.setFillColor(this.layerInfo.strokeColor);
        polygon.setStrokeColor(this.layerInfo.strokeColor);
        // this.setAllFillColor();
      }
    },
    setAllFillColor() {
      const overlays = this.map.getOverlays();
      overlays.map((overlay) => {
        const currentColor = overlay.getFillColor();
        if (currentColor === this.layerInfo.strokeColor) return;
        overlay.setFillOpacity(0.4);
        overlay.setFillColor(this.layerInfo.strokeColor);
        overlay.setStrokeColor(this.layerInfo.strokeColor);
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.map-box {
  position: relative;
  .map-grid {
    width: 100%;
    height: 650px;
    margin-bottom: 10px;
  }
  .menu-wrap {
    height: 650px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    background-color: rgba(0, 0, 0, 0.75);
    width: 250px;
    z-index: 200;
    position: absolute;
    left: 0;
    top: 0;
    overflow: hidden;
    ::v-deep
      .el-tree--highlight-current
      .el-tree-node.is-current
      > .el-tree-node__content {
      background-color: transparent;
    }

    ::v-deep .el-tree-node__content:hover {
      background-color: transparent;
    }
    .please-box {
      height: 40px;
      line-height: 40px;
      padding: 0 10px;
      color: #fff;
      border-bottom: 1px solid #4886f8;
      margin-bottom: 10px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
    }
    .tree-box {
      overflow-y: scroll;
      overflow-x: hidden;
      height: calc(100% - 51px);
      width: 260px;
      background: transparent;
      color: #fff;
      // ::v-deep .el-checkbox__inner {
      //   border-radius: 50%;
      // }
      .tree-title {
        width: 200px;
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
      ::v-deep .is-checked .tree-title {
        color: #4886f8;
      }
      ::v-deep .el-checkbox__input.is-disabled .el-checkbox__inner {
        background-color: #b9b9b9;
        border-color: #959595;
        cursor: not-allowed;
      }
    }
  }
}
.pagi-box{
  background:transparent;
  position: relative;
  color: #fff;
  top: -166px;
  // right: 40px;
  ::v-deep .el-pagination__total{
    color: #fff;
  }
  ::v-deep .btn-prev{
    color: #fff;
    background-color:transparent;
  }
  ::v-deep .btn-next{
    color: #fff;
    background-color:transparent;
  }
  ::v-deep  button:disabled{
    color:#C0C4CC;
    background-color:transparent;
  }
}
</style>
