<template>
  <div class="page">
    <!-- 工具 -->
    <map-toolbar :show-list="mapToolList" @fence="setFence" @clearMap="clearMap"></map-toolbar>
    <!-- 地图 -->
    <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"
        @singleclick="clickStation"
      ></v-vector>
      <!-- 企业 -->
      <v-vector
        ref="companyLayer"
        layer-id="companyLayer"
        :features="layers.companyLayer.features"
        :cluster="layers.companyLayer.cluster"
        :z-index="2"
        @singleclick="clickCompany"
      ></v-vector>
      <!-- 驻勤点人员 -->
      <v-vector
        ref="stationEmployeesLayer"
        layer-id="stationEmployeesLayer"
        :features="layers.stationEmployeesLayer.features"
        :z-index="2"
        @singleclick="clickStationEmployees"
      ></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-overlay
        :position="layers.stationLayer.overlay.position"
        :class-name="['info-window', 'info-window-common', 'info-window-station']"
        positioning="bottom-center"
        :offset="layers.stationLayer.overlay.offset"
      >
        <a class="close" @click.stop="closeStationInfo">×</a>
        <overlay-station :info="info" readonly></overlay-station>
      </v-overlay>
      <!-- 企业详情弹框 -->
      <v-overlay
        :position="layers.companyLayer.overlay.position"
        :class-name="['info-window', 'info-window-common', 'info-window-company']"
        positioning="bottom-center"
        :offset="layers.companyLayer.overlay.offset"
      >
        <a class="close" @click.stop="closeCompanyInfo">×</a>
        <overlay-company :info="info" :return-win="returnWin"></overlay-company>
      </v-overlay>
      <!-- 驻勤点人员弹框 -->
      <v-overlay
        :position="layers.stationEmployeesLayer.overlay.position"
        :class-name="['info-window', 'info-window-common', 'info-window-stationEmployees']"
        positioning="bottom-center"
        :offset="layers.stationEmployeesLayer.overlay.offset"
      >
        <a class="close" @click.stop="closeStationEmployeesInfo">×</a>
        <overlay-stationEmployees :info="info" :return-win="returnWin"></overlay-stationEmployees>
      </v-overlay>
    </v-map>
    <!-- 电子围栏列表弹框 -->
    <electronic-fence-dialog
      ref="electronicFence"
      v-if="isElectronicFenceDialog"
      @cancel="electronicFenceCancel"
      @addElectronic="addElectronic"
      @electronicFenceEdit="electronicFenceEditFn"
      :info="info"
      :data.sync="electronicFenceData"
      @del="delElectronic"
    ></electronic-fence-dialog>
    <!-- 电子围栏增加修改弹框 -->
    <electronic-fence-edit-dialog
      ref="electronicFenceEdit"
      v-show="isElectronicFenceEditDialog"
      :info="info"
      :electronic-fence-info="electronicFenceInfo"
      :station-id="station.id"
      @openPeopleNum="openPeopleNumFn"
      @relationStation="relationStationFn"
      @cancel="electronicFenceEditCancel"
      @cleanFigure="cleanDrawFigure"
      @draw="drawRail"
    >
    </electronic-fence-edit-dialog>
    <!-- 电子围栏驻勤点人员弹框 -->
    <electronic-fence-people
      v-if="isElectronicFencePeople"
      :list="electronicFencePeopleList"
      :station-name="peopleStationName"
      @cancel="electronicFencePeopleCancel"
    >
    </electronic-fence-people>
    <!-- 电子围栏关联驻勤点弹框 -->
    <electronic-fence-station-dialog
      ref="electronicFenceStation"
      v-show="isElectronicFenceStationDialog"
      :info="info"
      :electronic-fence-info="station"
      @relation="setRelatedStation"
      @cancel="electronicFenceStationCancel"
    >
    </electronic-fence-station-dialog>
  </div>
</template>

<script>
import { utils, VMap, VTile, VVector, VOverlay, VDraw } from "v-ol-map";
import "v-ol-map/lib/v-ol-map.css";
import mapToolbar from "@/components/mapToolbar/index.vue";
import { Message } from "element-ui";
import { deleteRail, getRailDetail, searchRail } from "@/api/security-station-rails-controller";
import { getStationDetail } from "@/api/security-station-controller";
import { textSlice } from "@/api/common";
import OverlayStation from "@/components/mapOverlay/station";
import OverlayCompany from "@/components/mapOverlay/company";
import { getCompanyDetail } from "@/api/company-controller";
import { getEmployees } from "@/api/employee-controller";
import OverlayStationEmployees from "@/components/mapOverlay/stationEmployees";
import electronicFenceDialog from "@/views/rail/components/electronicFence.vue";
import electronicFenceEditDialog from "@/views/resources/components/electronicFenceEdit.vue";
import electronicFencePeople from "@/views/resources/components/electronicFencePeople.vue";
import electronicFenceStationDialog from "@/views/resources/components/electronicFenceStation.vue";

export default {
  name: "rail",
  components: {
    VMap,
    VTile,
    VVector,
    VOverlay,
    VDraw,
    mapToolbar,
    OverlayStation,
    OverlayCompany,
    OverlayStationEmployees,
    electronicFenceDialog,
    electronicFenceEditDialog,
    electronicFenceStationDialog,
    electronicFencePeople,
  },
  data() {
    return {
      platform: localStorage.getItem("platform") || "1",
      deskTypes: localStorage.getItem("platform") === "1" ? ["Normal"] : ["Proprietor"],
      view: {
        city: "厦门",
        zoom: 12,
      },
      tileType: "GD",
      interactions: {
        DragRotateAndZoom: true,
        doubleClickZoom: false,
      },
      controls: {
        zoom: true,
        zoomOptions: {
          className: "ol-zoom-custom",
        },
      },
      mapToolList: ["fence"],
      tableData: [],
      originData: [],
      station: {},
      info: {},
      returnWin: {},
      layers: {
        // 驻勤点
        stationLayer: {
          features: [],
          overlay: {
            position: undefined,
            offset: [0, -36],
          },
        },
        // 企业
        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: "",
    };
  },
  methods: {
    /**
     * @驻勤点图层点击事件
     * 1、先判断点击位置是否有驻勤点
     * 2、获取点属性id
     * 3、通过id查找驻勤点详情
     * 4、把详情放到info变量用来展现详情（showStationInfo）
     * 5、把经纬度赋值给position属性展示弹框
     * @param evt
     * @param feature
     */
    clickStation(evt, feature) {
      if (feature) {
        this.showStationInfo();
      }
    },
    /**
     * @企业图层点击事件
     * @param evt
     * @param feature
     */
    clickCompany(evt, feature) {
      if (feature) {
        console.log(feature);
        const features = feature.get("features");
        if (features && features.length === 1) {
          const company = features[0];
          const info = company.get("props");
          console.log(info);
          this.showCompanyInfo({ info });
        } else {
          // 如果是聚合点就下钻一级
          const zoom = this.$refs.map.map.getView().getZoom() + 1;
          const center = evt.coordinate;
          this.$refs.map.panTo({ zoom, center });
        }
      }
    },
    /**
     * @驻勤点详情
     */
    showStationInfo() {
      this.clearMap();
      const { superviseDepartName, address, longitude, latitude, stationTypes } = this.station;
      const [{ mapIcon }] = stationTypes;
      if (this.layers.stationLayer.features.length <= 0) {
        this.layers.stationLayer.features = [
          {
            coordinates: [Number(longitude), Number(latitude)],
            convert: "gd-84",
            style: {
              icon: {
                src: mapIcon,
                scale: 0.5,
              },
            },
            props: this.station,
          },
        ];
      }
      this.info = {
        ...this.station,
        superviseDepartNameSlice: textSlice(superviseDepartName),
        addressSlice: textSlice(address),
      };
      /**
       * @弹框位置转高德转84
       */
      this.layers.stationLayer.overlay.position = utils.convertCoordinate([Number(longitude), Number(latitude)], "gd-84");
      this.$refs.map.panTo({
        center: this.layers.stationLayer.overlay.position,
      });
    },
    /**
     * @驻勤点弹框点击关闭
     */
    closeStationInfo() {
      this.layers.stationLayer.overlay.position = undefined;
    },
    /**
     * @企业详情
     * @param info
     * @param infoType
     */
    showCompanyInfo({ info, infoType }) {
      console.log("company", info);
      let { organizationId } = info;
      getCompanyDetail(organizationId)
        .then((company) => {
          const { registerAddress, longitude, latitude } = company;
          console.log("company", company);
          this.info = {
            ...company,
            registerAddressSlice: textSlice(registerAddress),
          };
          if (infoType) {
            this.clearMap();
            this.hideFenceTable();
            this.returnWin = { info, infoType };
            this.layers.companyLayer.features = [
              {
                coordinates: [Number(longitude), Number(latitude)],
                convert: "gd-84",
                style: {
                  icon: {
                    src: require("@/assets/images/mapSearch/公司.png"),
                  },
                },
                props: company,
              },
            ];
          }
          /**
           * @弹框位置转高德转84
           */
          this.layers.companyLayer.overlay.position = utils.convertCoordinate([Number(longitude), Number(latitude)], "gd-84");
          this.$refs.map.panTo({
            center: this.layers.companyLayer.overlay.position,
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    /**
     * @企业弹框点击关闭
     */
    closeCompanyInfo() {
      this.returnWin = {};
      this.layers.companyLayer.overlay.position = undefined;
    },
    /**
     * @驻勤点人员详情
     * @param info
     * @param infoType
     */
    showStationEmployeesInfo({ info, infoType }) {
      console.log("showStationEmployeesInfo-" + infoType, info);
      let { id } = info;
      getEmployees({
        pageIndex: 1,
        pageSize: 5000,
        securityStationIds: [id + ""],
        searchModel: "SecurityStation",
        deskTypes: this.deskTypes,
      })
        .then((res) => {
          console.log("stationEmployees", res);
          console.log("station", info);
          info["stationEmployees"] = [...res].map((x) => {
            return {
              ...x,
              isPhone: false,
            };
          });
          this.info = { ...{}, ...info };
          console.log("info", this.info);
          if (infoType) {
            this.clearMap();
            this.hideFenceTable();

            this.returnWin = { info, infoType };
            this.layers.stationEmployeesLayer.features = [
              {
                coordinates: [Number(info.longitude), Number(info.latitude)],
                convert: "gd-84",
                style: {
                  icon: {
                    src: require("@/assets/images/mapSearch/在岗_保安员.png"),
                  },
                },
                props: info,
              },
            ];
            if (infoType === "rail") {
              info["name"] = info.stationName;
            }
          }
          /**
           * @弹框位置转高德转84
           */
          this.layers.stationEmployeesLayer.overlay.position = utils.convertCoordinate(
            [Number(info.longitude), Number(info.latitude)],
            "gd-84"
          );
          this.$refs.map.panTo({
            // zoom: 13,
            // flyZoom: 8,
            center: this.layers.stationEmployeesLayer.overlay.position,
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    /**
     * @驻勤点人员图层点击事件
     * @param evt
     * @param feature
     */
    clickStationEmployees(evt, feature) {
      if (feature) {
        console.log("clickStationEmployees-feature", feature);
        const stations = feature.get("features");
        if (stations && stations.length === 1) {
          const station = stations[0];
          const info = station.get("props");
          this.showStationEmployeesInfo({ info });
        } else {
          if (feature.get("props")) {
            const info = feature.get("props");
            this.showStationEmployeesInfo({ info });
          } else {
            // 如果是聚合点就下钻一级
            const zoom = this.$refs.map.map.getView().getZoom() + 1;
            const center = evt.coordinate;
            this.$refs.map.panTo({ zoom, center });
          }
        }
      }
    },
    /**
     * @驻勤点人数弹框点击关闭
     */
    closeStationEmployeesInfo() {
      this.returnWin = {};
      this.layers.stationEmployeesLayer.overlay.position = undefined;
    },
    /**
     * @电子围栏图层点击事件
     * @param evt
     * @param feature
     */
    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 });
          }
        }
      }
    },
    /**
     * @电子围栏详情
     * @param info
     * @param infoType
     */
    showRailInfo({ info, infoType }) {
      // this.layers.railLayer.features = [];
      getRailDetail(info.id)
        .then((res) => {
          console.log("railres", res);
          console.log("railinfo", info);
          res["id"] = info.id; //后端传值有问题
          // res["name"] = info.name; //后端传值有问题
          res["shapedLocation"] = info.shapedLocation; //后端传值有问题
          res["companyNameSlice"] = textSlice(res.companyName); //多出部分省略号显示
          this.info = { ...{}, ...res };
          if (infoType) {
            this.clearMap();
            this.hideFenceTable();
            this.returnWin = { info, infoType };
          }
          if (res.railShapeType === "Circle") {
            console.log("Circle", res.shapedLocation);
            const feature = {
              type: "circle",
              // center: [118.051876, 24.607453],
              // radius: 272,
              convert: "gd-84",
              center: [res.shapedLocation.geos[0].lon, res.shapedLocation.geos[0].lat],
              radius: res.shapedLocation.radius,
              props: info,
            };
            console.log(feature);
            this.layers.railLayer.cluster = false;
            this.layers.railLayer.features = [feature];
          } else if (res.railShapeType === "Crib" || res.railShapeType === "Polygon") {
            const coordinates = res.shapedLocation.geos.map((x) => {
              return [x.lon, x.lat];
            });
            this.layers.railLayer.cluster = false;
            this.layers.railLayer.features = [
              {
                type: "polygon",
                convert: "gd-84",
                coordinates,
                props: info,
              },
            ];
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    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;
    },
    /**
     * @注册显示弹框类事件
     */
    eventBusBinding() {
      this.$bus.$on("click-station", this.showStationInfo); // 显示驻勤点弹框
      this.$bus.$on("click-company", this.showCompanyInfo); // 显示公司弹框
      this.$bus.$on("click-stationEmployees", this.showStationEmployeesInfo); // 显示驻勤点人员
    },
    /**
     * @清空地图
     */
    clearMap(exclude = ["stationLayer"]) {
      for (let layersKey in this.layers) {
        if (!exclude.includes(layersKey)) {
          this.layers[layersKey].features = [];
        }
      }
      this.$refs.map.closeOverlays();
    },
    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;
      // 显示关联的驻勤点
      const situation = await getStationDetail(data.stationId);
      console.log(situation);
      this.layers.stationLayer.features = [situation].map((feature) => {
        return {
          coordinates: [Number(feature.longitude), Number(feature.latitude)],
          convert: "gd-84",
          style: {
            icon: {
              src: feature.stationTypes[0].mapIcon,
              scale: 0.5,
            },
          },
          props: feature,
        };
      });
      // this.map.clearMap();
      this.isElectronicFenceDialog = false;
      this.electronicFenceInfo = JSON.parse(JSON.stringify(data));
      this.electronicFenceInfo.time = [this.electronicFenceInfo.beginTime, this.electronicFenceInfo.endTime];
      this.electronicFenceInfo.countOfSecurityMan = situation.countOfSecurityMan;
      const rail = await getRailDetail(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,
      };
      deleteRail(params)
        .then((res) => {
          console.log("deleteRail", res);
          this.$refs["electronicFence"].getRails();
          this.$message({
            message: "删除成功",
            type: "success",
          });
        })
        .catch((err) => {
          console.log(err);
        });
    },
    openPeopleNumFn(id, stationName) {
      this.electronicFencePeopleList = [];
      this.isElectronicFencePeople = true;
      this.peopleStationName = stationName;
      getEmployees({
        pageIndex: 1,
        pageSize: 1000,
        securityStationIds: [id + ""],
        searchModel: "SecurityStation",
        deskTypes: this.deskTypes,
      }).then((res) => {
        this.electronicFencePeopleList = res;
      });
    },
    /**
     * @关联驻勤点
     */
    relationStationFn(info) {
      this.isElectronicFenceStationDialog = true;
      this.info = { ...this.info, ...info };
    },
    electronicFenceEditCancel() {
      this.layers.railLayer.features = [];
      this.isElectronicFenceEditDialog = false;
      this.cleanDrawFigure();
      searchRail({
        pageIndex: 0,
        pageSize: 0,
        searchModel: "Station",
        stationId: this.station.id,
      })
        .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 = "";
    },
    /**
     * @关闭驻勤点人员
     */
    electronicFencePeopleCancel() {
      this.isElectronicFencePeople = false;
    },
    async setRelatedStation(val) {
      this.isElectronicFenceStationDialog = false;
      console.log(val);
      this.$refs.electronicFenceEdit.updateStation(val);
      // 显示关联的驻勤点
      const situation = await getStationDetail(val.stationId);
      console.log("situation", situation);
      this.layers.stationLayer.features = [situation].map((feature) => {
        return {
          coordinates: [Number(feature.longitude), Number(feature.latitude)],
          convert: "gd-84",
          style: {
            icon: {
              src: feature.stationTypes[0].mapIcon,
              scale: 0.5,
            },
          },
          props: feature,
        };
      });
      this.$refs.map.panTo({
        // zoom: 13,
        // flyZoom: 8,
        center: [Number(situation.longitude), Number(situation.latitude)],
      });
    },
    electronicFenceStationCancel() {
      this.layers.railLayer.features = [];
      this.isElectronicFenceStationDialog = false;
      this.cleanDrawFigure();
    },
    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);
      }
    },
  },
  beforeRouteEnter(to, from, next) {
    // http://localhost:8080/#/rail?stationId=rtAZi63Xc5MgyiV5lYv--__W052b1XNoLmPckF6ch1
    const stationId = to.query.stationId;
    if (stationId) {
      // 获取驻勤点信息
      getStationDetail(stationId)
        .then((station) => {
          if (station) {
            const { longitude, latitude, stationTypes } = station;
            const [{ mapIcon }] = stationTypes;
            // 获取电子围栏信息
            searchRail({
              pageIndex: 0,
              pageSize: 0,
              searchModel: "Station",
              stationId,
            })
              .then((res) => {
                console.log("searchRail", res);
                if (res) {
                  next((vm) => {
                    vm.layers.stationLayer.features = [
                      {
                        coordinates: [Number(longitude), Number(latitude)],
                        convert: "gd-84",
                        style: {
                          icon: {
                            src: mapIcon,
                            scale: 0.5,
                          },
                        },
                        props: station,
                      },
                    ];
                    vm.station = { ...station };
                    vm.electronicFenceData = res;
                    vm.isElectronicFenceDialog = true;
                  });
                } else {
                  Message({
                    type: "error",
                    message: "查询电子围栏信息失败",
                    onClose: () => {
                      // window.location = "https://www.baidu.com";
                    },
                  });
                }
              })
              .catch(() => {
                Message({
                  type: "error",
                  message: "查询电子围栏信息失败",
                  onClose: () => {
                    // window.location = "https://www.baidu.com";
                  },
                });
              });
          } else {
            Message({
              type: "error",
              message: "查询驻勤点信息失败",
              onClose: () => {
                // window.location = "https://www.baidu.com";
              },
            });
          }
        })
        .catch((err) => {
          console.log(err);
          Message({
            type: "error",
            message: "查询驻勤点信息失败",
            onClose: () => {
              // window.location = "https://www.baidu.com";
            },
          });
        });
    } else {
      Message({
        type: "error",
        message: "未识别驻勤点ID",
        onClose: () => {
          // window.location = "https://www.baidu.com";
        },
      });
    }
  },
  mounted() {
    this.eventBusBinding();
  },
};
</script>

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