<template>
  <div class="page">
    <!-- 地图 -->
    <v-map class="map" ref="map" :view="view" :interactions="interactions" @contextmenu.prevent>
      <!-- 底图 -->
      <v-tile :tile-type="tileType" :z-index="0"></v-tile>
      <!-- 驻勤点点位 -->
      <v-vector ref="stationLayer" layer-id="stationLayer" :features="layers.stationLayer.features" :z-index="2"></v-vector>
      <v-vector ref="pointLayer" layer-id="pointLayer" :features="layers.pointLayer.features" :z-index="2"></v-vector>
      <!-- <v-vector 
        :source="layers.pointLayer.source"
        :style="layers.pointLayer.style">
      </v-vector> -->
      <!-- 电子围栏图层 -->
      <v-vector
        ref="railLayer"
        layer-id="railLayer"
        :feature-style="layers.railLayer.style"
        :features="layers.railLayer.features"
        :z-index="2"
        @singleclick="clickRail"
        @change="onRailLayerChange"
      ></v-vector>
      <!-- 绘制电子围栏 -->
      <v-draw
        ref="drawLayer"
        :type="drawType"
        :feature-style="layers.railLayer.style"
        :end-right="true"
        :clear="true"
        :z-index="3"
        draw-once
        editable
        @drawend="drawend"
      ></v-draw>
    </v-map>
    <!-- 电子围栏增加修改弹框 -->
    <electronic-fence-edit-dialog
      ref="electronicFenceEdit"
      v-show="showFenceEdit"
      :info="info"
      :electronic-fence-info="electronicFenceInfo"
      :station-id="stationId"
      :station-visible="false"
      @cancel="electronicFenceEditCancel"
      @cleanFigure="cleanDrawFigure"
      @draw="drawRail"
    >
    </electronic-fence-edit-dialog>
  </div>
</template>

<script>
import { utils, VMap, VTile, VVector, VDraw } from "v-ol-map";
import "v-ol-map/lib/v-ol-map.css";
import { Message } from "element-ui";
import { deleteRailAccess, getRailDetailAccess, searchRailAccess } from "@/api/security-station-rails-controller";
import electronicFenceEditDialog from "@/components/electronicFenceEdit.vue";

export default {
  name: "rail",
  components: {
    VMap,
    VTile,
    VVector,
    VDraw,
    electronicFenceEditDialog,
  },
  data() {
    return {
      view: {
        city: "晋城",
        zoom: 11,
      },
      tileType: "GD",
      interactions: {
        DragRotateAndZoom: true,
        doubleClickZoom: false,
      },
      controls: {
        zoom: true,
        zoomOptions: {
          className: "ol-zoom-custom",
        },
      },
      stationId: "",
      mapToolList: ["fence", "tile"],
      tableData: [],
      originData: [],
      station: {},
      info: {},
      returnWin: {},
      layers: {
        // 驻勤点
        stationLayer: {
          features: [],
          overlay: {
            position: undefined,
            offset: [0, -36],
          },
        },
        pointLayer: {
          features: [],
          style: {
            image: {
              src: require("@/assets/images/mapToolbar/框选.png"),
              scale: 1.2,
            },
          }
        },
        // 企业
        companyLayer: {
          features: [],
          overlay: {
            position: undefined,
            offset: [0, -36],
          },
        },
        // 驻勤点人员
        stationEmployeesLayer: {
          features: [],
          overlay: {
            position: undefined,
            offset: [0, -36],
          },
        },
        // 电子围栏
        railLayer: {
          features: [],
          cluster: {
            distance: 110,
            style: {
              circle: {
                radius: 50,
                fill: {
                  color: "#0E71FF",
                },
              },
              text: {
                font: "22px Source Han Sans CN-Medium, Source Han Sans CN",
                fill: {
                  color: "#FFFFFF",
                },
              },
            },
          },
          style: {
            fill: {
              color: "rgba(230,162,60,0.2)",
            },
            stroke: {
              color: "#E6A23C",
              width: 2,
            },
          },
          overlay: {
            position: undefined,
            offset: [0, -36],
          },
        },
      },
      isElectronicFenceEditDialog: false,
      isElectronicFenceStationDialog: false,
      isElectronicFenceDialog: false,
      isElectronicFencePeople: false,
      electronicFenceData: [],
      electronicFenceInfo: {},
      drawType: "",
      electronicFencePeopleList: [],
      peopleStationName: "",
      showFenceEdit: true,
    };
  },
  methods: {
    clickRail(evt, feature) {
      if (feature) {
        console.log(feature);
        const rails = feature.get("features");
        if (rails && rails.length === 1) {
          this.showRailInfoFromList = false;
          const rail = rails[0];
          const info = rail.get("props");
          console.log("clickRailInfo", info);
          this.showRailInfo({ info });
        } else {
          if (feature.get("props")) {
            this.showRailInfoFromList = false;
            const info = feature.get("props");
            console.log("clickRailInfo", info);
            this.showRailInfo({ info });
          } else {
            // 如果是聚合点就下钻一级
            const zoom = this.$refs.map.map.getView().getZoom() + 1;
            const center = evt.coordinate;
            this.$refs.map.panTo({ zoom, center });
          }
        }
      }
    },
    
    onRailLayerChange(features) {
      console.log(features);
      if (features && features.length === 1) {
        const feature = features[0];
        const type = feature.get("type");
        if (type && !this.showRailInfoFromList) {
          console.log(type);
          if (type === "polygon" || type === "Polygon") {
            const geometry = feature.get("geometry");
            // const view = this.$refs.map.map.getView();
            // view.fit(geometry, {
            //   duration: 1000,
            // });
            const result = this.$refs.map.calculateCenter(geometry);
            const { center } = result;
            // console.log(coordinates)
            /**
             * @弹框位置转高德转84
             */
            this.layers.railLayer.overlay.position = center;
          } else if (type === "circle" || type === "Circle") {
            const geometry = feature.get("geometry");
            // const view = this.$refs.map.map.getView();
            // view.fit(geometry, {
            //   duration: 1000,
            // });
            this.layers.railLayer.overlay.position = geometry.getCenter();
          }
        }
      }
    },
    /**
     * @电子围栏列表
     */
    setFence() {
      this.isElectronicFenceDialog = true;
    },
    /**
     * @清空地图
     */
    clearMap(exclude = ["stationLayer"]) {
      for (let layersKey in this.layers) {
        if (!exclude.includes(layersKey)) {
          this.layers[layersKey].features = [];
        }
      }
      this.$refs.map.closeOverlays();
    },
    onChangeLayer(type) {
      // console.log("onChangeLayer", type);
      if (type.indexOf("default") > -1) {
        this.tileType = "GD";
      } else {
        this.tileType = "GD_IMG";
      }
    },
    hideFenceTable() {
      this.isElectronicFenceEditDialog = false;
      this.isElectronicFenceStationDialog = false;
      this.isElectronicFenceDialog = false;
    },
    electronicFenceCancel() {
      this.isElectronicFenceDialog = false;
    },
    /**
     * @新增电子围栏
     */
    addElectronic() {
      this.isElectronicFenceEditDialog = true;
      this.isElectronicFenceDialog = false;
      this.electronicFenceInfo = JSON.parse(JSON.stringify(this.info));
      this.electronicFenceInfo = {};
      console.log(this.station);
      this.$nextTick(() => {
        this.$refs.electronicFenceEdit.updateStation({
          stationName: this.station.name,
          peopleNum: this.station.countOfSecurityMan,
          countOfSecurityMan: this.station.countOfSecurityMan,
          stationId: this.station.id,
        });
      });
    },
    /**
     * @编辑某条电子围栏
     * @param data
     */
    async electronicFenceEditFn({ data }) {
      console.log("编辑某条电子围栏", data);
      this.showRailInfoFromList = true;
      // this.map.clearMap();
      this.isElectronicFenceDialog = false;
      this.electronicFenceInfo = JSON.parse(JSON.stringify(data));
      this.electronicFenceInfo.time = [this.electronicFenceInfo.beginTime, this.electronicFenceInfo.endTime];
      const rail = await getRailDetailAccess(data.id);
      this.info = { ...rail, ...this.electronicFenceInfo }; // 弹框信息
      console.log(this.info);
      this.isElectronicFenceEditDialog = true;
      // 显示可编辑围栏区域
      this.showMapEditor(data);
    },
    delElectronic(data) {
      console.log(data);
      let params = {
        id: data.data.id,
      };
      deleteRailAccess(params)
        .then((res) => {
          console.log("deleteRailAccess", res);
          this.$refs["electronicFence"].getRails();
          this.$message({
            message: "删除成功",
            type: "success",
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
 
    electronicFenceEditCancel() {
      this.layers.railLayer.features = [];
      this.isElectronicFenceEditDialog = false;
      this.cleanDrawFigure();
      searchRailAccess({
        pageIndex: 1,
        pageSize: 10,
        searchModel: "Station",
        stationId: this.stationId,
      })
        .then((res) => {
          console.log("searchRail", res);
          if (res) {
            this.electronicFenceData = res;
          } else {
            Message({
              type: "error",
              message: "查询电子围栏信息失败",
              onClose: () => {
                // window.location = "https://www.baidu.com";
              },
            });
          }
        })
        .catch(() => {
          Message({
            type: "error",
            message: "查询电子围栏信息失败",
            onClose: () => {
              // window.location = "https://www.baidu.com";
            },
          });
        });
    },
    cleanDrawFigure() {
      this.drawType = "";
    },

    showMapEditor({ shapeType, shapedLocation }) {
      console.log('showMapEditor', shapeType, shapedLocation);
      switch (shapeType) {
        case "Circle": // 圆
          this.showCircleEditor(shapedLocation);
          break;
        case "Polygon":
          this.showPolygonEditor(shapedLocation);
          break;
        case "Crib":
          this.showCribEditor(shapedLocation);
          break;
      }
    },
    showPolygonEditor({ geos }) {
      let list = geos.map((item) => [item.lon, item.lat]);
      console.log(list);
      this.layers.railLayer.features = [
        {
          type: "polygon",
          coordinates: list,
          style: this.layers.railLayer.style,
          convert: "gd-84",
        },
      ];
      this.$refs.map.flyTo({
        zoom: 13,
        flyZoom: 8,
        center: list[0],
      });
      console.log(this.layers.railLayer.features);
    },
    showCribEditor({ geos }) {
      let list = geos.map((item) => [item.lon, item.lat]);
      console.log(list);
      this.layers.railLayer.features = [
        {
          type: "polygon",
          coordinates: list,
          style: this.layers.railLayer.style,
          convert: "gd-84",
        },
      ];
      this.$refs.map.flyTo({
        zoom: 13,
        flyZoom: 8,
        center: list[0],
      });
      console.log(this.layers.railLayer.features);
    },
    showCircleEditor({ geos, radius }) {
      const [center] = geos.map((item) => [item.lon, item.lat]);
      console.log(center);
      this.layers.railLayer.features = [
        {
          type: "Circle",
          center,
          radius,
          style: this.layers.railLayer.style,
          convert: "gd-84",
        },
      ];
      this.$refs.map.flyTo({
        zoom: 13,
        // flyZoom: 8,
        center,
      });
    },
    drawRail(type) {
      console.log("drawRail", type);
      // this.layers.railLayer.features = []
      this.drawType = type;
    },
    drawend(evt, map) {
      const { feature } = evt;
      console.log(this.drawType);
      this.layers.railLayer.features = []; // 清空上一个电子围栏
      const geometry = feature.getGeometry();
      if (this.drawType === "Rectangle" || this.drawType === "Polygon") {
        const [coordinates] = geometry.getCoordinates();
        const convertCoordinates = coordinates.map((coordinate) => {
          return utils.convertCoordinate(coordinate, "84-gd");
        });
        console.log(coordinates);
        console.log(convertCoordinates);
        const params = {
          geos: convertCoordinates.map((item) => {
            return {
              lon: item[0],
              lat: item[1],
            };
          }),
        };
        console.log(params);
        this.$refs.electronicFenceEdit.updateGeometry(params);
      } else if (this.drawType === "Circle") {
        const center = geometry.getCenter();
        console.log(center);
        const geoRadius = geometry.getRadius(); // 半径
        const metersPerUnit = map.getView().getProjection().getMetersPerUnit(); // 半径以米为单位
        const radius = (geoRadius * metersPerUnit).toFixed(2);
        console.log(radius);
        const convertCoordinates = utils.convertCoordinate(center, "84-gd");
        const params = {
          geos: [
            {
              lon: convertCoordinates[0],
              lat: convertCoordinates[1],
            },
          ],
          radius,
        };
        console.log(params);
        this.$refs.electronicFenceEdit.updateGeometry(params);
      }
    },
    initPosition(pathId) {
      this.$api.getPointListApi({ 
        pathId: pathId,
        pageIndex: 1,
        pageSize: 999999
       },{
      onSucess: (res) => {
        let list = res.data.data.map(item => [item.longitude, item.latitude]);
       console.log('list',list)
        this.layers.stationLayer.features = [
          {
            type: "polyline",
            coordinates: list,
            convert: "gd-84",
          },
        ];
        this.layers.pointLayer.features = list.map(coord => ({
          type: "point",
          coordinates: coord,
          convert: "gd-84",
          properties: {
            name: `站点-${coord.join(',')}`
          },
          // style: this.layers.pointLayer.style,
        }));
        this.$refs.map.flyTo({
          zoom: 16,
          flyZoom: 8,
          center: list[0],
        });
        },
      });  
    },
    initRail(id, radius, isCenter) {
      this.$api.getRailListApi({ 
        id: id,
        radius: radius,
        pageIndex: 1,
        pageSize: 999999
       },{
      onSucess: (res) => {
        // let list = res.data.data.map(item => [item.longitude, item.latitude]);
         const [center] = res.data.data.map((item) => [item.longitude, item.latitude]);
       console.log('list',list)
        // this.layers.stationLayer.features = [
        //   {
        //     type: "polyline",
        //     coordinates: list,
        //     convert: "gd-84",
        //   },
        // ];
        this.layers.pointLayer.features = [
            {
              type: "Circle",
              center,
              radius,
              // style: this.layers.railLayer.style,
              convert: "gd-84",
            },
          ];
          this.$refs.map.flyTo({
            zoom: 13,
            // flyZoom: 8,
            center,
          });
        },
      });  
    }
  },
  
  mounted() {
    let query = this.$route.query;
    console.log('query',query)
    if (query && query.pathId) {
      this.showFenceEdit = false
      this.initPosition(query.pathId)
    } else if (query && query.id) {
      this.showFenceEdit = false
      this.initRail(query.id, query.radius)
    } else if (query && query.shapeType!==null && query.shapedLocation!==null) {
      this.showMapEditor({ shapeType: query.shapeType, shapedLocation: JSON.parse(decodeURIComponent(query.shapedLocation))})
    }
  },
};
</script>

<style scoped lang="scss">
.page {
  width: 100%;
  height: 100%;
  position: relative;
  .map {
    z-index: 1;
  }
}
</style>
