<script lang="jsx">
import { defineComponent } from "vue";
import { mapState } from "vuex";
import { bbox, point, points, featureCollection } from "@turf/turf";
import GisMap from "@/components/GisMap/index.vue";
import Popup from "@/components/GisMap/Popup/index.vue";
import HoverPopup from "@/components/GisMap/HoverPopup/index.vue";
import StaticLayers from "./layer/StaticLayers/index.vue";
import StaticLayerPopupContent from "./popup/StaticLayerPopupContent/index.vue";
import CameraPlayer from "./popup/StaticLayerPopupContent/CameraPlayer.vue";
import EventLayer from "@/components/GisMap/Layer/EventLayer.vue";
import { layerCode } from "./config";
const interactiveStaticLayerCodeSet = new Set([
  layerCode.TOLL_STATION, // 收费站
  layerCode.SERVICE_AREA, // 服务区
  layerCode.BRIDGE, // 桥梁
  layerCode.TUNNEL, // 隧道
  layerCode.CULVERT, // 涵洞
  layerCode.CAMERA, // 摄像头
  layerCode.GANTRY, // 龙门架
  layerCode.BOARD, // 情报板
]);
export default defineComponent({
  data() {
    return {
      cameraData: null,
      cameraPopPosition: null,
      events: [
        {
          lng: 105.8239515869493,
          lat: 29.262943891582296,
        },
      ],
      zoom: 5,
    };
  },
  computed: {
    ...mapState({
      config: (state) => state.map.config,
      map: (state) => state.map.map,
      boundaryLineFace: state => state.map.boundaryLineFace,
      staticLayers: (state) => state.map.layers || [],
      visibleStaticLayerCodes: (state) => state.map.selectedLayers || [],
      allRoads: (state) => state.road.allRoads || [],
      selectRoadId: (state) => state.road.selectRoadId[2],
      selectRoadId2: (state) => state.road.selectRoadId,
    }),
    selectRoad() {
      const { allRoads, selectRoadId } = this;
      if (!allRoads || allRoads.length < 1 || !selectRoadId) {
        return null;
      }
      return allRoads.find(({ id }) => id === selectRoadId);
    },
    interactiveStaticLayerIds() {
      const { staticLayers } = this;
      const arr = [];
      staticLayers &&
        staticLayers.forEach((item) => {
          interactiveStaticLayerCodeSet.has(item.code) &&
            arr.push(item.layerId);
        });
      return arr;
    },
    // 摄像头图层单独处理
    cameraLayer() {
      const { staticLayers } = this;
      return (
        staticLayers &&
        staticLayers.find(({ code }) => code === layerCode.CAMERA)
      );
    },
    roadBounds() {
      const { allRoads, selectRoad } = this;
      if (!allRoads || allRoads.length < 1) {
        return null;
      }
      const pointArr = [];
      if (selectRoad && selectRoad.begLng) {
        pointArr.push(point([selectRoad.begLng, selectRoad.begLat]));
        pointArr.push(point([selectRoad.endLng, selectRoad.endLat]));
      } else {
        allRoads.forEach((item) => {
          if (item.begLng) {
            pointArr.push(point([item.begLng, item.begLat]));
            pointArr.push(point([item.endLng, item.endLat]));
          }
        });
      }
      return bbox(featureCollection(pointArr));
    },
  },
  watch: {
    map(val) { //先高亮所有的省份
      this.hightLinghtProve()
      this.getChangeRoads(['CQ']) //默认选中重庆的，所以地图加载好之后再操作一下
    },
    selectRoadId2(nval) {
      this.getChangeRoads(nval)
    }
  },
  mounted() {
    this.$store.dispatch("map/getMapConfig");
  },
  methods: {
    // 路段切换
    getChangeRoads(nval) {
      const qmz = JSON.parse(localStorage.getItem('mapCLkmz'))
      if(this.map) {
        this.map.setLayoutProperty(qmz.ROUTE, "visibility", "none");//所有路段  （为全国时显示所有路段）
        if(nval[0]) {
          this.provinceClick(nval[0])
          // this.map.setLayoutProperty('466cb84ab4cacabe16ba0d1c269c0606', "visibility", "none");
        } else {
          this.hightLinghtProve()
          this.map.setLayoutProperty(qmz.ROUTE, "visibility", "none"); //所有路段  （单个省份隐藏所有路段）
        }
      }
    },
    //高亮所有省份
    hightLinghtProve() {
      // this.map.setZoom(4.8);
      // this.map.setCenter([107.85585,28.465908]);
      this.map.setZoom(5.2);
      this.map.setCenter([104.07751, 28.55365]);
      this.boundaryLineFace.forEach(el => {
        this.map.setLayoutProperty(el.layerIdl, "visibility", "visible");
        this.map.setLayoutProperty(el.layerIdf, "visibility", "visible");
      })
    },
    // 单独高亮某个省份
    provinceClick(name) {
      let provinceMarker = [{
        zb: [107.969855, 30.367095],
        id: 'CQ',
        zoom: 6.8
      }, {
        zb: [102.928995, 30.52487],
        id: 'SC',
        zoom: 5.8
      }, {
        zb: [101.593103, 25.353375],
        id: 'YN',
        zoom: 6
      }, {
        zb: [106.641243, 27.10797],
        id: 'GZ',
        zoom: 6.5
      }, {
        zb: [117.229929, 31.825398],
        id: 'AH',
        zoom: 6.5
      }]
      provinceMarker.forEach(el => {
        if (name === el.id) {
          this.$nextTick(() => {
            this.map.flyTo({
              center: el.zb,
              zoom: el.zoom,
            })
          });
        }
      })
      //
      this.boundaryLineFace.forEach(el => {
        this.map.setLayoutProperty(el.layerIdl, "visibility", "none");
        this.map.setLayoutProperty(el.layerIdf, "visibility", "none");
      })
      this.boundaryLineFace.forEach(el => {
        if (name == el.code) {
          this.map.setLayoutProperty(el.layerIdl, "visibility", "visible");
          this.map.setLayoutProperty(el.layerIdf, "visibility", "visible");
        }
      })
    },
    handleLoad(data) {
      this.$store.commit("map/setMap", data.map);
    },
    onCameraLayerClick(evt) {
      const { features, layer } = evt;
      if (!features || !features[0] || !features[0].properties) {
        return;
      }
      const { properties } = features[0];
      this.cameraPopPosition = [properties.lon, properties.lat];
      this.cameraData = { ...properties };
    },
    onCameraPopClose() {
      this.$emit("closeCamera", this.cameraData);
      this.cameraPopPosition = null;
      this.cameraData = null;
    },
    getJHpoint(ponitData) {
      this.$refs.videogismap.getjhponit(ponitData)
    },
    doinitmap() {
      this.$refs.videogismap.init()
    }
  },
  render() {
    const {
      config,
      staticLayers,
      visibleStaticLayerCodes,
      interactiveStaticLayerIds,
      cameraLayer,
      roadBounds,
      cameraData,
      cameraPopPosition,
      onCameraLayerClick,
      onCameraPopClose,
      events,
      handleLoad,
      zoom
    } = this;
    // <EventLayer data={events}></EventLayer>
    return (
      <GisMap
        ref="videogismap"
        config={config}
        zoom={zoom}
        onLoad={handleLoad}
        center={[106.55, 35.57]}
      >
        <StaticLayers
          staticLayers={staticLayers}
          visibleStaticLayerCodes={visibleStaticLayerCodes}
          onCameraLayerClick={onCameraLayerClick}
        />
        <HoverPopup layerIds={interactiveStaticLayerIds}>
          {{
            default: ({ layerId, data }) => {
              if (
                layerId !== cameraLayer.layerId ||
                !cameraData ||
                cameraData.camera_ind !== data.camera_ind
              ) {
                return <StaticLayerPopupContent data={data} />;
              }
              return null;
            },
          }}
        </HoverPopup>
        <Popup
          position={cameraPopPosition}
          options={{ closeOnClick: false }}
          onClose={onCameraPopClose}
        >
          {cameraData && <CameraPlayer data={cameraData} />}
        </Popup>
      </GisMap>
    );
  },
});
</script>
