<template>
  <div class="layer-contrl">
    <!-- <Module
        :loading="loading"
        :error="error"
        :info="bsMeta && bsMeta['utilities']"
      >
        <template #title>摄像头分类</template> -->
    <div class="group-content">
      <div
        class="group-item"
        v-for="item in layersData"
        :key="item.code"
        :class="{
          active: selectedType.includes(item.enunittype.split('&')[0]),
        }"
        @click="onItemClick(item.enunittype, item)"
      >
        <div class="item-icon">
          <img
            v-if="selectedType.includes(item.enunittype.split('&')[0])"
            :src="imagelist[item.code + 'act']"
          />
          <img v-else :src="imagelist[item.code]" />
        </div>
        <div class="inlayertext">{{ item.name }}</div>
      </div>
    </div>
    <div class="group-content">
      <div
        class="group-item"
        v-for="item in layersData"
        :key="item.code"
      >
        <div class="item-icon">
          <img
            v-if="selectedType.includes(item.enunittype.split('&')[0])"
            :src="imageTipslist[item.code]"
          />
        </div>
      </div>
    </div>
    <!-- </Module> -->
  </div>
</template>
<script lang="jsx">
import { defineComponent } from "vue";
import { mapState, mapMutations } from "vuex";

import { getVideoCameraResource } from "@/api/video";

import BRIDGE from "@/assets/images/roadVisualization/BRIDGE.png";
import BRIDGEact from "@/assets/images/roadVisualization/BRIDGE-act.png";

import TUNNEL from "@/assets/images/roadVisualization/TUNNEL.png";
import TUNNELact from "@/assets/images/roadVisualization/TUNNEL-act.png";

import SERVICE_AREA from "@/assets/images/roadVisualization/SERVICE_AREA.png";
import SERVICE_AREAact from "@/assets/images/roadVisualization/SERVICE_AREA-act.png";

import TOLL_STATION from "@/assets/images/roadVisualization/TOLL_STATION.png";
import TOLL_STATIONact from "@/assets/images/roadVisualization/TOLL_STATION-act.png";

import YHCL from "@/assets/images/baseStruct/yhcl.png";
import YHCLact from "@/assets/images/baseStruct/yhcl-active.png";

// import videoPNG from "./Map/images/摄像头.png";
import qlPNG from "./Map/images/桥梁.png";
// import qlPNG1 from "@/assets/images/jhtypeicon/桥梁1.png";
// import qlPNG2 from "@/assets/images/jhtypeicon/桥梁2.png";
// import qlPNG3 from "@/assets/images/jhtypeicon/桥梁3.png";
import qlPNG1 from "@/assets/images/jhtypeicon/桥梁4.png";

import sdPNG from "./Map/images/隧道.png";
// import sdPNG1 from "@/assets/images/jhtypeicon/隧道1.png";
// import sdPNG2 from "@/assets/images/jhtypeicon/隧道2.png";
// import sdPNG3 from "@/assets/images/jhtypeicon/隧道3.png";
import sdPNG1 from "@/assets/images/jhtypeicon/隧道3.png";
import fwqPNG from "./Map/images/服务区.png";
// import fwqPNG1 from "@/assets/images/jhtypeicon/服务区1.png";
// import fwqPNG2 from "@/assets/images/jhtypeicon/服务区2.png";
// import fwqPNG3 from "@/assets/images/jhtypeicon/服务区3.png";
import fwqPNG1 from "@/assets/images/jhtypeicon/服务区2.png";
import sfzPNG from "./Map/images/收费站.png";
// import sfzPNG1 from "@/assets/images/jhtypeicon/收费站1.png";
// import sfzPNG2 from "@/assets/images/jhtypeicon/收费站2.png";
// import sfzPNG3 from "@/assets/images/jhtypeicon/收费站3.png";
import sfzPNG1 from "@/assets/images/jhtypeicon/收费站1.png";
import clskPNG from "./Map/images/摄像头.png";

const layerPngs = {
  QL: qlPNG,
  QL1: qlPNG1,
  SD: sdPNG,
  SD1: sdPNG1,
  FWQ: fwqPNG,
  FWQ1: fwqPNG1,
  SFZ: sfzPNG,
  SFZ1: sfzPNG1,
  CLSK: clskPNG,
};

export default defineComponent({
  data() {
    return {
      imagelist: {
        BRIDGE: BRIDGE,
        BRIDGEact: BRIDGEact,

        TUNNEL: TUNNEL,
        TUNNELact: TUNNELact,

        SERVICE_AREA: SERVICE_AREA,
        SERVICE_AREAact: SERVICE_AREAact,

        TOLL_STATION: TOLL_STATION,
        TOLL_STATIONact: TOLL_STATIONact,

        YHCL: YHCL,
        YHCLact: YHCLact,
      },
      imageTipslist: {
        BRIDGE: qlPNG1,
        TUNNEL: sdPNG1,
        SERVICE_AREA: fwqPNG1,
        TOLL_STATION: sfzPNG1,
      },
      layersData: [
        {
          name: "桥梁",
          code: "BRIDGE",
          enunittype: "QL",
          layerid: "videoLayerQL", //在地图上的图层id
        },
        {
          name: "隧道",
          code: "TUNNEL",
          enunittype: "SD",
          layerid: "videoLayerSD",
        },
        {
          name: "服务区",
          code: "SERVICE_AREA",
          enunittype: "FWQ",
          layerid: "videoLayerFWQ",
        },
        {
          name: "收费站",
          code: "TOLL_STATION",
          enunittype: "SFZ",
          layerid: "videoLayerSFZ",
        },
        // {
        //   name: "车辆实况",
        //   code: "YHCL",
        //   enunittype: "CLSK",
        //   layerid: "videoLayerCLSK",
        // },
      ],
      selectedType: [],
      qlpng: BRIDGE,
      roadsId: '',
      level: 0,
      selectedTypeNames: []
    };
  },
  computed: {
    ...mapState({
      map: (state) => state.map.map,
    }),
  },
  watch: {
    map(val) {
      // this.getPoint('SD');
    },
  },
  mounted() {},
  methods: {
    // dropdown页面传过来的路段id
    getRoadsId(id, level) {
      this.roadsId = id
      this.level = level
      // 如果有已选中的类别，再继续执行（显示该路段下的累呗）
      if(this.selectedType.length > 0) {
        // 先删除已有的类别图层
        this.selectedType.forEach(type => {
          this.map.removeSource('pointSource' + type)
          this.map.removeLayer('videoLayer' + type)
          this.map.removeLayer("videoLayer"+ type + "1")
          this.map.removeImage("videoSurveillance"+type)
          this.map.removeImage("videoSurveillance"+type + '1')
          this.getPoint(type)
        });
      }
    },
    //点击类别
    onItemClick(enunittype, item) {
      const idx = this.selectedType.indexOf(enunittype);
      if (idx > -1) {
        //  已有此类别，则删除图层
        this.selectedType.splice(idx, 1);
        // this.map.setLayoutProperty(item.layerid, "visibility", "none");
        this.map.removeSource('pointSource' + enunittype)
        this.map.removeLayer('videoLayer' + enunittype)
        this.map.removeLayer("videoLayer"+ enunittype + "1")
        this.map.removeImage("videoSurveillance"+enunittype)
        this.map.removeImage("videoSurveillance"+enunittype + "1")
      } else {
        //  没有此类别，则添加图层
        this.selectedType.push(enunittype);
        this.getPoint(enunittype)
      }
      //
      this.selectedType.length > 0
        ? this.showHideJH("none")
        : this.showHideJH("visible");

      //  获取已选类别的中文名字(需要在dropdown页面做筛选)
      this.selectedTypeNames = [];
      const sl = this.layersData.filter((item) =>
        this.selectedType.includes(item.enunittype)
      );
      sl.forEach((val) => {
        this.selectedTypeNames.push(val.name);
      });
      this.$emit("layerSelect", this.selectedTypeNames);
    },
    // 隐藏或显示数字聚合图层
    showHideJH(sty) {
      this.map.setLayoutProperty("cluster-count", "visibility", sty);
      this.map.setLayoutProperty("unclustered-points", "visibility", sty);
      let curLayerList = ['point-outer-cluster-0', 'point-outer-cluster-1', 'point-outer-cluster-2', 'point-inner-cluster-0', 'point-inner-cluster-1', 'point-inner-cluster-2']
          curLayerList.forEach(i => {
            this.map.setLayoutProperty(i, "visibility", sty);
          })
    },

    async getPoint(type) {
      // 先把所有的分类下面的摄像头的点获取到
      let result = {
          type: "FeatureCollection",
          features: [],
        };
        // this.$emit("layerSelect", this.selectedTypeNames);
        const res = await getVideoCameraResource('', type, this.roadsId, this.level);
        let arr = res.msgContent || [];
        arr.forEach((item, index) => {
          if (item.longitude && item.latitude) {
            result.features.push({
              geometry: {
                type: "Point",
                coordinates: [item.longitude, item.latitude],
              },
              properties: {
                title: item.name,
                kind: item.id,
              },
              type: "Feature",
            });
          }
        });
        this.addSource(result, type);
        const _that = this
    },
    // 再把获取到的点打在地图上(并隐藏点)，一个类别对应一个图层(Layer), 每个图层都有唯一的图层id
    addSource(arr, type) {
      let { map } = this;
      this.map.addSource("pointSource" + type, {
        type: "geojson",
        data: arr,
        cluster: true,
        clusterMaxZoom: 10, /* 最大聚合层级 */
        clusterRadius: 30 /* 聚合半径 */
      });
      map.loadImage(layerPngs[type], function (error, image) {
        if (error) throw error;
        // 添加自定义图标
        map.addImage("videoSurveillance" + type, image);
        map.addLayer({
          id: "videoLayer" + type,
          type: "symbol",
          source: "pointSource" + type,
          filter: ["!has", "point_count"],
          layout: {
            "icon-image": "videoSurveillance" + type,
            "icon-size": 1,
          },
        });
        //数量图层
          // map.addLayer({
          //   "id": "videoLayer"+ type + "num",
          //   "type": "symbol",
          //   "source": "pointSource" + type,
          //   "layout": {
          //     "icon-image": "videoSurveillance" + type,
          //     "icon-size": 1.2,
          //     "text-field": "{point_count}",
          //     "text-size": 13,
          //   },
          //   "paint": {
          //     "text-color": "#000",
          //     "text-halo-color": "#ffffff",
          //     "text-halo-width": 2,
          //   },
          //   "filter": ["has", "point_count"]
          // });
      });
      // var jhicons = [[1000, type + '3'], [100, type + '2'], [0, type + '1']];
      // jhicons.forEach(function (item, i) {

      //   map.loadImage(layerPngs[item[1]], function (error, image) {
      //     if (error) throw error;
      //     // 添加自定义图标
      //     map.addImage("videoSurveillance" + item[1], image);
      //     map.addLayer({
      //       "id": "videoLayer"+ item[1],
      //       "type": "symbol",
      //       "source": "pointSource" + type,
      //       "layout": {
      //         "icon-image": "videoSurveillance" + item[1],
      //         "icon-size": 0.6,
      //         "text-field": "{point_count}",
      //         "text-size": 12,
      //         "text-offset": [0, 0.6],
      //       },
      //       "paint": {
      //         "text-color": "#ffffff",
      //         "text-halo-color": "#ffffff",
      //         "text-halo-width": 0.1,
      //       },
      //       "filter": i === 0 ?
      //       [">=", "point_count", item[0]] :
      //       ["all", [">=", "point_count", item[0]], ["<", "point_count", jhicons[i - 1][0]]]
      //     });
      //   });
      // });
      map.loadImage(layerPngs[type+'1'], function (error, image) {
        if (error) throw error;
        map.addImage("videoSurveillance" + type + '1', image);
        map.addLayer({
            "id": "videoLayer"+ type + "1",
            "type": "symbol",
            "source": "pointSource" + type,
            "layout": {
              "icon-image": "videoSurveillance" + type + '1',
              "icon-size": 0.6,
              "text-field": "{point_count}",
              "text-size": 12,
              "text-offset": [0, 0.6],
              "symbol-avoid-edges": true,
              "icon-allow-overlap": true,
              "icon-ignore-placement": true,
              "symbol-spacing": 20
            },
            "paint": {
              "text-color": "#ffffff",
              "text-halo-color": "#ffffff",
              "text-halo-width": 0.1,
            },
            "filter": ["has", "point_count"]
          });

        // map.addLayer({
        //     "id": "videoLayer" + type + '1',
        //     "type": "symbol",
        //     "source": "pointSource" + type,
        //     "layout": {
        //       "icon-image": "videoSurveillance" + + type + '1',
        //       "icon-size": 0.6,
        //       "text-field": "{point_count}",
        //       "text-size": 12,
        //       "text-offset": [0, 0.6],
        //     },
        //     "paint": {
        //       "text-color": "#ffffff",
        //       "text-halo-color": "#ffffff",
        //       "text-halo-width": 0.1,
        //     },
        //     "filter": ["has", "point_count"]
        // });
      })

      const _that = this;
      map.on("click", function (e) {
        var features = map.queryRenderedFeatures(e.point, {
          layers: ["videoLayer" + type],
        });
        console.log(features);
        if (features.length > 0) {
          _that.$store.commit("changeVideo", features[0].properties);
        }

        var contfeatures1 = map.queryRenderedFeatures(e.point, { layers: ["videoLayer"+ type + "1"] });
        if (contfeatures1.length > 0) {
          map.flyTo({
            center: contfeatures1[0].geometry.coordinates,
            zoom: 11,
          })
        }
      });
    },
  },
});
</script>
<style lang="postcss" scoped>
.layer-contrl {
  width: 100%;
  height: 100%;
  /* position: absolute;
  bottom: 100px;
  left: 0; */

  /* left: 20px; */
  border-radius: 8px;
  /* padding: 20px; */
  /* overflow: auto; */
}
.group-title {
  position: relative;
  color: #d5fbff;
  font-weight: 400;
  font-size: 14px;
  line-height: 18px;
  padding-left: 15px;
  &::before {
    position: absolute;
    left: 0;
    content: " ";
    width: 5px;
    height: 18px;
    background: linear-gradient(180deg, #f7ffff, #00d3ff);
    border-radius: 2px;
  }
}
.group-content {
  width: 100%;
  display: flex;
  flex-wrap: wrap;
  margin: 10px 0 10px;
}
.group-item {
  width: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 5px;
  font-size: 12px;
  cursor: pointer;
  text-align: center;
  line-height: 18px;
  color: #fff;
  box-sizing: border-box;
  &.active {
    color: #07ffed;
  }
}
.layerIcon {
  margin: auto;
  width: 10px;
  height: 10px;
  color: #fff;
}
.icon {
  width: 20px;
  height: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #ede9e9;
  border-radius: 50%;
  margin-bottom: 5px;
  &.active {
    border-color: #3ebfb5;
    background: #3ebfb5;
  }
}
.active .inlayertext {
  background: linear-gradient(
    to right,
    transparent,
    rgba(255, 192, 0, 0.45),
    transparent
  );
  color: rgba(255, 206, 90, 1);
}
.inlayertext {
  font-weight: bold;
  letter-spacing: 1px;
  width: 100%;
  height: 15px;
  line-height: 15px;
  margin: auto;
  margin-top: 0;
  margin-bottom: 0.1rem;
  text-align: center;
  color: #badeff;
  font-size: 13px;
  background: linear-gradient(
    to right,
    transparent,
    rgba(0, 72, 137, 1),
    transparent
  );
}
.item-icon {
  width: 55px;
  height: 46px;
  margin: auto;
  /* background: red; */
}
</style>
