<template>
  <div class="w-1/3 dropdiv">
    <div class="dropdivin">
      <div class="container">
        <div class="iptdiv">
          <el-input
            v-model="text"
            size="small"
            placeholder="请输入监控名称"
            style="width: 200px; margin-right: 20px"
            v-on:keyup.enter="handleSerch(true)"
          ></el-input>
          <el-button type="primary" size="small" @click="handleSerch(true)">搜索</el-button>
        </div>
        <!-- <div class="movelist" v-for="(item, index) in monitorList" :key="index">
          <div
            class="item-name"
            @click="handleShowVideo(item.cameraIndexCode, item.name)"
          >
            {{ item.name }}
          </div>
        </div>-->
        <el-tree
          v-loading="loading"
          ref="tree"
          :default-expanded-keys="['101']"
          @node-click="nodeClick"
          :data="treeData"
          :props="defaultProps"
          :filter-node-method="filterNode"
          style="background: none; color: #fff"
          node-key="id"
          accordion
        ></el-tree>
      </div>
    </div>

    <el-dialog :title="videoname" v-model="videoVisible" width="770px">
      <div>
        <div class="player" v-if="url">
          <videoPlayer :url="url"></videoPlayer>
        </div>
        <div>
          <el-button
            v-for="(item, index) in bottonList"
            :key="index"
            type="primary"
            round
            size="medium"
            @click="doPushMoniter(index)"
          >{{ item }}</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getVideoUrl } from "@/api/operation";
import videoPlayer from "./newLayerContrl/components/videoPlayer.vue";
import { getVideoCameraResource, videoRegionTree } from "@/api/video";
import { mapState, mapMutations } from "vuex";
import { getSectionVideoRegion, getOrg } from "@/api/curingManage";
import { assign } from "lodash";
import videoPng from "@/assets/images/camera.png";

export default {
  components: {
    videoPlayer
  },
  computed: {
    ...mapState({
      map: state => state.map.map,
      boundaryLineFace: state => state.map.boundaryLineFace
    }),
    getVideoInfo () {
      return this.$store.state.videoInfo;
    }
  },
  data () {
    return {
      loading: false,
      allRoads: [],
      markers: [],
      url: null,
      videoname: null,
      videoVisible: false,
      treeData: [],
      defaultProps: {
        children: "children",
        label: "label"
      },
      pageNo: 1,
      pageSize: 13,
      url: "",
      text: "",
      serchInput: true, // 从输入框筛选 或者 从底部的摄像头分类(隧道、涵洞、收费站...)筛选
      monitorList: [],
      allVideo: [],
      bottonList: ["左上", "右上", "左下", "右下", "鹰眼摄像"],
      // 当前选中（播放的视频），需传给右侧监控咧白哦
      currentVideo: {
        name: "",
        url: "",
        code: ""
      },
      provinceCenter: [
        {
          zb: [107.969855, 30.067095],
          id: "CQ",
          zoom: 6.8
        },
        {
          zb: [103.143217, 30.163066],
          id: "SC",
          zoom: 5.5
        },
        {
          zb: [101.836002, 24.887257],
          id: "YN",
          zoom: 5.5
        },
        {
          zb: [106.641243, 26.60797],
          id: "GZ",
          zoom: 6
        },
        {
          zb: [117.229929, 31.825398],
          id: "AH",
          zoom: 6
        }
      ],
      videoPonit: [], //数字聚合点
      treeMarkList: [], //树节点上的视频
      pointVisible: "visible" //数字聚合点的显示和隐藏
    };
  },
  watch: {
    getVideoInfo (val) {
      this.handleShowVideo(val.kind, val.title);
    },
    map (val) {
      //先高亮所有的省份
      this.map.setZoom(4.8);
      this.map.setCenter([107.85585, 28.465908]);
      const qmz = JSON.parse(localStorage.getItem('mapCLkmz'))
      this.map.setLayoutProperty(
        qmz.ROUTE,
        "visibility",
        "none"
      );
      this.boundaryLineFace.forEach(el => {
        this.map.setLayoutProperty(el.layerIdl, "visibility", "visible");
        this.map.setLayoutProperty(el.layerIdf, "visibility", "visible");
      });
      this.addSources();
    }
  },
  async mounted () {
    this.getData();
    this.getVideoTree();
  },
  methods: {
    ...mapMutations("road", ["setSelectRoadId", "setSelectLevel"]),
    // 获取组织结构
    async getData () {
      const orgData = await getOrg();
      // this.getTreeData(orgData.msgContent)
    },
    async getVideoTree () {
      const data = await videoRegionTree();
      this.getTreeData(data.msgContent);
    },
    // 将数组重组为树结构
    getTreeData (data) {
      const _that = this;
      let level1_arr = [];
      let level2_arr = [];
      let level3_arr = [];
      let level4_arr = [];
      let level5_arr = [];
      data.forEach(item => {
        item.label = item.organizationName;
        item.id = item.organizationId;
        item.children = [];
        if (item.level === "1") {
          level1_arr.push(item);
        }
        if (item.level === "2") {
          level2_arr.push(item);
        }
        if (item.level === "3") {
          level3_arr.push(item);
        }
        if (item.level === "4") {
          level4_arr.push(item);
        }
        if (item.level === "5") {
          level5_arr.push(item);
        }
      });
      level1_arr.forEach(e1 => {
        level2_arr.forEach(e2 => {
          if (e2.pnode == e1.organizationId) e1.children.push(e2);
        });
      });
      level1_arr.forEach(e1 => {
        e1.children.forEach(e2 => {
          level3_arr.forEach(e3 => {
            if (e3.pnode == e2.organizationId) e2.children.push(e3);
          });
        });
      });
      level1_arr.forEach(e1 => {
        e1.children.forEach(e2 => {
          e2.children.forEach(e3 => {
            level4_arr.forEach(e4 => {
              if (e4.pnode == e3.organizationId) e3.children.push(e4);
            });
          });
        });
      });
      level1_arr.forEach(e1 => {
        e1.children.forEach(e2 => {
          e2.children.forEach(e3 => {
            e3.children.forEach(e4 => {
              level5_arr.forEach(e5 => {
                if (e5.pnode == e4.organizationId) e4.children.push(e5);
              });
            });
          });
        });
      });
      this.treeData = level1_arr;
      const markers = level5_arr.filter(
        item => item.longitude && item.latitude
      );
      this.addMarkers(markers);
    },
    // 树节点点击
    nodeClick (data, node) {
      if (data.level == 1 || data.level == 2 || data.level == 3) {
        this.$emit("drawRoads", data.id, data.level);
        this.treeMarkList = [];
        const st = this.nodeClickCheckVideo(data);
        if (st) {
          this.pointVisible = this.map.getLayoutProperty(
            "point-outer-cluster-0",
            "visibility"
          );
          this.map.removeSource("data-point");
          this.map.removeLayer("cluster-count");
          this.map.removeLayer("unclustered-points");
          this.map.removeLayer("point-outer-cluster-0");
          this.addMarkers(this.treeMarkList);
        }
      }
      if (data.level == 1) {
        this.shouLinghtProve(data.id);
      }
      if (data.level == 2) {
        this.shouLinghtProve(data.pnode);
      }
      // 播放视频
      if (node.level == 5) {
        this.handleShowVideo(data.id, data.name);
        if (data.longitude && data.latitude) {
          this.flyToMap(data);
        }
      }
    },
    //点击树节点后，获取改节点下的视频（然后获取经纬、打点）
    nodeClickCheckVideo (data) {
      let dataCopy = data;
      let _that = this;
      function setData (data) {
        if (data.children && data.children.length > 0) {
          data.children.forEach((ele, index) => {
            if (ele.children && ele.children.length > 0) {
              _that.nodeClickCheckVideo(ele);
            } else {
              if (ele.longitude && ele.latitude) {
                _that.treeMarkList.push(ele);
              }
            }
          });
        }
      }
      setData(dataCopy);
      return true;
    },
    //点击树结构，地图的变化
    shouLinghtProve (provinceId) {
      // 显示或隐藏高亮的省份
      // 先隐藏掉其他高亮的省份
      this.boundaryLineFace.forEach(el => {
        this.map.setLayoutProperty(el.layerIdl, "visibility", "none");
        this.map.setLayoutProperty(el.layerIdf, "visibility", "none");
      });
      this.boundaryLineFace.forEach(el => {
        if (provinceId == el.code) {
          this.map.setLayoutProperty(el.layerIdl, "visibility", "visible");
          this.map.setLayoutProperty(el.layerIdf, "visibility", "visible");
        }
      });
      this.provinceCenter.forEach(el => {
        if (provinceId == el.id) {
          this.map.flyTo({
            center: el.zb,
            zoom: el.zoom
          });
        }
      });
    },

    // 清除点
    // 在地图上打点 这是点聚合
    addMarkers (arr) {
      // 打点
      let result = {
        type: "FeatureCollection",
        features: []
      };
      arr.forEach((item, index) => {
        if (item.longitude && item.latitude) {
          result.features.push({
            geometry: {
              type: "Point",
              coordinates: [item.longitude, item.latitude]
            },
            properties: {
              title: item.label,
              kind: item.id
            },
            type: "Feature"
          });
        }
      });
      this.videoPonit = result;
      this.addSources();
    },
    // 跳转到地图点位
    flyToMap (data) {
      const lnglat = [data.longitude, data.latitude];
      this.map.flyTo({
        center: lnglat,
        zoom: 12
      });
    },
    // 视频弹框
    async handleShowVideo (deviceCode, name) {
      this.videoname = name;
      const res = await getVideoUrl(deviceCode);
      if (res && res.success && res.data) {
        this.url = res.data;
      } else {
        this.url = null;
      }
      this.currentVideo.name = name;
      this.currentVideo.url = this.url;
      this.currentVideo.code = deviceCode;
      this.videoVisible = true;
    },
    //将当前视频添加到右侧视频监控列表
    doPushMoniter (num) {
      let obj = Object.assign({}, this.currentVideo);
      this.$emit("doPushMoniter", num, obj);
    },
    // 输入框搜索
    handleSerch (blo) {
      this.serchInput = blo;
      this.$refs.tree.filter(this.text);
    },
    // 摄像头分类搜索
    layerSerch (data) {
      console.log("摄像头分类");
      console.log(data);
      this.serchInput = false;
      data.length > 0
        ? this.$refs.tree.filter(data)
        : this.$refs.tree.filter("");
    },
    filterNode (value, data) {
      if (!value) return true;
      // 从输入框筛选
      if (this.serchInput && data.label.indexOf(value) !== -1) {
        return true;
      }
      // 从底部的摄像头分类(隧道、涵洞、收费站...)筛选
      if (
        !this.serchInput &&
        data.unitType &&
        value.indexOf(data.unitType) !== -1
      ) {
        return true;
      }
    },

    // 视频监控点聚合
    addSources () {
      const _that = this;
      if (this.map && this.videoPonit) {
        this.map.addSource("data-point", {
          type: "geojson",
          data: _that.videoPonit,
          cluster: true,
          clusterMaxZoom: 10 /* 最大聚合层级 */,
          clusterRadius: 50 /* 聚合半径 */
        });
        this.addLayers();
      }
    },
    addLayers () {
      let { map } = this;
      const _that = this;
      //添加非聚合图层
      map.loadImage(videoPng, function (error, image) {
        if (error) throw error;
        // 添加自定义图标
        map.addImage("park", image);
        map.addLayer({
          id: "unclustered-points",
          type: "symbol",
          source: "data-point",
          filter: ["!has", "point_count"],
          layout: {
            "icon-image": "park",
            "icon-size": 0.5,
            visibility: _that.pointVisible
          }
        });
      });
      //添加聚合图层
      //添加聚合图层
      var outerColors = [
        [1000, "rgba(253, 156, 115, 0.6)"],
        [100, "rgba(241, 211, 87, 0.6)"],
        [0, "rgba(181, 226, 140, 0.6)"]
      ];

      outerColors.forEach(function (color, i) {
        map.addLayer({
          id: "point-outer-cluster-" + i,
          type: "circle",
          source: "data-point",
          paint: {
            "circle-color": color[1],
            "circle-radius": 20
          },
          filter:
            i === 0
              ? [">=", "point_count", color[0]]
              : [
                "all",
                [">=", "point_count", color[0]],
                ["<", "point_count", outerColors[i - 1][0]]
              ]
        });
      });
      var innerColors = [
        [1000, "rgba(241, 128, 23, 0.6)"],
        [100, "rgba(240, 194, 12, 0.6)"],
        [0, "rgba(110, 204, 57, 0.6)"]
      ];

      innerColors.forEach(function (color, i) {
        map.addLayer({
          id: "point-inner-cluster-" + i,
          type: "circle",
          source: "data-point",
          paint: {
            "circle-color": color[1],
            "circle-radius": 15
          },
          filter:
            i === 0
              ? [">=", "point_count", color[0]]
              : [
                "all",
                [">=", "point_count", color[0]],
                ["<", "point_count", innerColors[i - 1][0]]
              ]
        });
      });

      // map.addLayer({
      //   "id": "point-outer-cluster-0",
      //   "type": "circle",
      //   "source": "data-point",
      //   "paint": {
      //     "circle-color": '#06B7C1',
      //     "circle-radius": 20
      //   },
      //   "layout": {
      //     "visibility": _that.pointVisible
      //   }
      // });
      //添加数量图层
      map.addLayer({
        id: "cluster-count",
        type: "symbol",
        source: "data-point",
        layout: {
          "text-field": "{point_count}",
          "text-size": 10,
          visibility: _that.pointVisible
        },
        paint: {
          "text-color": "rgba(0,0,0,.75)"
        },
        filter: ["has", "point_count"]
      });

      map.on("click", function (e) {
        var features = map.queryRenderedFeatures(e.point, {
          layers: ["unclustered-points"]
        });
        if (features.length > 0) {
          // _that.$store.commit('changeVideo', features[0].properties)
          _that.handleShowVideo(
            features[0].properties.kind,
            features[0].properties.title
          );
        }
        var contfeatures = map.queryRenderedFeatures(e.point, {
          layers: ["cluster-count"]
        });
        if (contfeatures.length > 0) {
          map.flyTo({
            center: contfeatures[0].geometry.coordinates,
            zoom: 11
          });
        }
      });
    }
  }
};
var subSet = function (arr1, arr2) {
  var set1 = new Set(arr1);
  var set2 = new Set(arr2);

  var subset = [];

  for (let item of set1) {
    if (!set2.has(item)) {
      subset.push(item);
    }
  }

  return subset;
};
</script>
<style>
.iptdiv input {
  background-color: #0c1d3c !important;
}
.el-tree-node__content:hover {
  background-color: #0c1d3c !important;
}
.el-tree-node:focus > .el-tree-node__content {
  background-color: #0c1d3c !important;
}
</style>
<style lang="scss" scoped>
.dropdiv {
  position: absolute;
  left: 0;
  top: 0;
  width: 430px;
  height: calc(100% - 320px);
  padding: 40px 10px;
  z-index: 9999;
  margin-top: 30px;
  // margin-left: 20px;
}
.dropdivin {
  width: 100%;
  height: 100%;
  padding: 20px 0;
  background: url("/src/assets/images/videoSurveillance/dropbg.png");
  background-size: 100% 100%;
}
.container {
  width: 100%;
  height: calc(100% - 30px);
  padding: 15px;
  overflow: auto;
}
.iptdiv {
  margin-bottom: 15px;
}
.movelist {
  padding: 12px;
  font-size: 14px;
  color: #fff;
  cursor: pointer;
}
.movelist:hover {
  color: #00ccff;
}
.page {
  padding-left: 15px;
}
::v-deep(.el-input__inner) {
  color: #fff;
}
</style>
