<template>
  <div>
    <el-input placeholder="输入关键字进行过滤" v-model="filterText" clearable></el-input>
    <el-row :gutter="24" style="margin-top:10px;">
      <el-col :span="12" style="text-align: center;">
        <el-switch v-model="value1" active-text="实时监测" @change="realTimeShow"></el-switch>
      </el-col>
      <el-col :span="12" style="text-align: center;">
        <el-switch v-model="value2" active-text="显示分区" @change="partitionShow"></el-switch>
      </el-col>
    </el-row>
    <el-tabs v-model="activeName" type="card" style="margin-top:10px">
      <el-tab-pane label="按设备类型" name="first">
        <el-tree
          class="filter-tree"
          :data="deviceData"
          :props="defaultProps"
          default-expand-all
          :filter-node-method="filterNode"
          @node-click="handleNodeClick"
          :expand-on-click-node="false"
          ref="tree1"
        >
          <span class="custom-tree-node" slot-scope="{node,data}">
            <span
              v-cloak
              v-if="data.siteState && data.siteState==0"
              style="color:#77787b"
            >{{ node.label }}</span>
            <span
              v-cloak
              v-else-if="data.isWarning && data.isWarning>0"
              style="color:#FF0000"
            >{{ node.label }}</span>
            <span v-cloak v-else>{{ node.label }}</span>
          </span>
        </el-tree>
      </el-tab-pane>
      <el-tab-pane label="按排水分区" name="second">
        <el-tree
          class="filter-tree"
          :data="areaData"
          :props="defaultProps"
          default-expand-all
          :filter-node-method="filterNode"
          ref="tree2"
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        >
          <span class="custom-tree-node" slot-scope="{node,data}">
            <span
              v-cloak
              v-if="data.siteState && data.siteState==0"
              style="color:#77787b"
            >{{ node.label }}</span>
            <span
              v-cloak
              v-else-if="data.isWarning && data.isWarning>0"
              style="color:#FF0000"
            >{{ node.label }}</span>
            <span v-cloak v-else>{{ node.label }}</span>
          </span>
        </el-tree>
      </el-tab-pane>
    </el-tabs>
    <!-- 历史曲线 -->
    <historyCurve ref="historyCurve"></historyCurve>
  </div>
</template>

<script>
import {
  getDisplaySitet,
  getPartitionDisplaySite,
  getPartition,
  getSiteNewData
} from '@/views/spectrum/dynamicMonitor/api/api'
import { getSiteIcon } from '@/views/spectrum/common/siteIcon/siteIcon'// 站点图标

import { MapPopup } from '@/views/spectrum/common/mapPopup/mapPopup'
import historyCurve from '@/views/spectrum/common/historyCurve/index'
import { creatTipMonitor } from '@/views/spectrum/common/mapPopup/getPopupInfo'
export default {
  components: {
    historyCurve
  },
  data() {
    return {
      activeName: 'first',
      filterText: '',
      value1: false,
      value2: false,
      deviceData: [],
      areaData: [],
      defaultProps: {
        children: 'list',
        label: 'label'
      },
      handler: null, // 地图对象
      partitionEntities: [],
      siteArray: [], // 站点
      popup:null,// 弹窗
    }
  },
  mounted() {
    this.getDisplaySitet()
    this.getPartitionDisplaySite()
  },
  destroyed() {
    this.cviewerClear()
    if (this.popup) {
      this.popup.destroy()
    }
    MapPopup.clearAll()
    if (this.handler) this.handler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK)
  },
  watch: {
    filterText(val) {
      this.$refs.tree1.filter(val)
      this.$refs.tree2.filter(val)
    }
  },
  methods: {
    /**
     * 筛选过滤
     */
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    /**
     * 按设备类型
     */
    getDisplaySitet() {
      this.siteArray = []
      getDisplaySitet({ projectId: this.$store.state.project.project.id }).then((res) => {
        const treeData = res.result.map((item1) => {
          item1['label'] = item1.deviceTypeName
            ? `${item1.deviceTypeName}(${item1.list ? item1.list.length : 0})`
            : `未绑定(${item1.list ? item1.list.length : 0})`
          item1.list = item1.list.map((item2) => {
            item2['label'] = `${item2.siteName}(${item2.checkNumber}/${item2.warningNumber})`
            // 存储站点
            this.siteArray.push(item2)
            return item2
          })
          return item1
        })
        this.deviceData = treeData
        // 显示站点要素
        this.showPointFeature()
      })
    },
    /**
     * 按排水分区
     */
    getPartitionDisplaySite() {
      getPartitionDisplaySite({ projectId: this.$store.state.project.project.id }).then((res) => {
        let treeData = res.result.map((item1) => {
          item1['label'] = item1.partitionName
            ? `${item1.partitionName}(${item1.list ? item1.list.length : 0})`
            : `未知(${item1.list ? item1.list.length : 0})`
          item1.list = item1.list.map((item2) => {
            item2['label'] = item2.groupByName
              ? `${item2.groupByName}(${item2.list ? item2.list.length : 0})`
              : `未知(${item2.list ? item2.list.length : 0})`
            item2.list = item2.list.map((item3) => {
              item3['label'] = item3.siteName
                ? `${item3.siteName}(${item3.checkNumber}/${item3.warningNumber})`
                : `未知(${item3.checkNumber}/${item3.warningNumber})`
              return item3
            })
            return item2
          })
          return item1
        })
        this.areaData = treeData
      })
    },
    /**
     * 显示点位
     */
    async showPointFeature() {
      let viewer = window.viewer
      this.siteArray.forEach((deviceItem) => {
        const icon = getSiteIcon(deviceItem)
        let lon = deviceItem.longitude || null
        let lat = deviceItem.latitude || null

        if (lon && lat) {
          const position = Cesium.Cartesian3.fromDegrees(lon, lat, 0)
          let entity = new Cesium.Entity({
            id: deviceItem.id,
            position: position,
            billboard: {
              image: icon,
              width: 40,
              height: 70,
              heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
              eyeOffset: Cesium.Cartesian3.ZERO
            }
          })
          viewer.entities.add(entity)
        }
      })
      // 初始化点击事件
      this.initClick()
    },
    /**
     * 监听站点点击事件
     */
    initClick() {
      let viewer = window.viewer
      this.handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas)
      this.handler.setInputAction((movement) => {
        var pick = viewer.scene.pick(movement.position)
        if (Cesium.defined(pick)) {
          // 本组件定义弹窗存在先移除
          if (this.popup) {
            this.popup.destroy()
          }
          let siteId = pick.id.id
          let siteData = this.siteArray.filter((item) => {
            return item.id == siteId
          })
          if (siteData.length > 0) {
            const data = siteData[0]
            // 展示实时数据
            this.getSiteNewData([data])
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    },
    /**
     * 获取站点实时数据
     */
    getSiteNewData(sites) {
      let ids = sites.map((item) => {
        return item.id
      })
      getSiteNewData({ sites: ids.join(',') }).then((res) => {
        if (res.code && res.code == 1) {
          let result = res.result
          creatTipMonitor(sites, result, (data, tipHtml) => {
            this.popup = new MapPopup({
              lon: data.longitude,
              lat: data.latitude,
              viewer: viewer,
              title: data.siteName,
              html: tipHtml,
              cureBtnClick: () => {
                // 查看历史曲线
                this.$refs.historyCurve.show(data.id)
              }
            })
          })
        }
      })
    },
    /**
     * 获取显示分区
     */
    getPartition() {
      getPartition({ projectId: this.$store.state.project.project.id, size: 1000 }).then((res) => {
        if (res.code == 1) {
          this.partitionEntities = []
          res.result.records.forEach((item) => {
            if (!item.coordinate) return false
            const position = JSON.parse(item.coordinate)
            const newPositions = position.map((item) => {
              return Cesium.Cartesian3.fromDegrees(item.x, item.y)
            })
            const linePositions = newPositions.map((item) => {
              return item
            })
            linePositions.push(linePositions[0])
            const bound = Cesium.PolygonGeometry.computeRectangle({
              polygonHierarchy: new Cesium.PolygonHierarchy(newPositions)
            })
            const center = Cesium.Rectangle.center(bound)
            center.height = 200
            const centercar3 = Cesium.Cartographic.toCartesian(center)
            //名称标识背景
            const color = 'rgb(56, 136, 205)'
            const canvas = document.createElement('canvas')
            let ratio = 2.0
            let width = 100
            let height = 200
            canvas.width = 120
            canvas.height = 80
            const ctx = canvas.getContext('2d')
            const img = new Image()
            img.src = require('@/assets/images/quantum/icon.png')
            img.onload = () => {
              ctx.lineWidth = 10
              ctx.strokeStyle = color
              ctx.font = '24px bold 宋体'
              const width = ctx.measureText(item.partitionName).width + 30
              canvas.width = width
              ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
              ctx.font = '24px bold 宋体'
              ctx.fillStyle = 'rgb(10,109,185)'
              ctx.textBaseline = 'middle'
              ctx.fillText(item.partitionName, 15, 27)

              const polygon = window.viewer.entities.add({
                position: centercar3,
                billboard: {
                  sizeInMeters: false,
                  image: canvas,
                  heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
                  verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
                  horizontalOrigin: Cesium.HorizontalOrigin.CENTER
                },
                polyline: {
                  show: true,
                  followSurface: false,
                  clampToGround: true,
                  positions: linePositions,
                  material: Cesium.Color.DODGERBLUE,
                  width: 2.0
                },
                polygon: {
                  hierarchy: new Cesium.PolygonHierarchy(newPositions),
                  material: Cesium.Color.DEEPSKYBLUE.withAlpha(0.1),
                  perPositionHeight: false,
                  outline: false,
                  outlineColor: Cesium.Color.GREEN,
                  heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                  outlineWidth: 2.0
                }
              })
              this.partitionEntities.push(polygon)
            }
          })
        }
      })
    },
    /**
     * tree节点点击事件
     */
    handleNodeClick(data, node, prop) {
      if (!data.hasOwnProperty('longitude') || !data.hasOwnProperty('latitude')) return
      // 站点定位
      this.viewerflyToLonLat(data)
    },
    /**
     * 定位站点
     * @param data (lng=>经度坐标,lat=>纬度坐标,alt=>距离中心点高度)
     */
    viewerflyToLonLat(data) {
      let viewer = window.viewer
      let lon = data.longitude || null
      let lat = data.latitude || null
      if (!lon || !lat) {
        this.$message.warning('无坐标信息，无法定位！')
        return
      }
      let entity = viewer.entities.getById(data.id)
      // 本组件定义弹窗存在先移除
      if (this.popup) {
        this.popup.destroy()
      }
      let flyPromise = viewer.flyTo(entity, {
        offset: {
          heading: Cesium.Math.toRadians(0.0),
          pitch: Cesium.Math.toRadians(-25),
          range: 3000
        }
      })

      // 飞行完后，展示实时数据。
      flyPromise
        .then((flyPromise) => {
          if (flyPromise) {
            // 展示实时数据
            this.getSiteNewData([data])
          }
        })
        .otherwise((error) => {
          console.log(error)
        })
    },
    /**
     * 显示分区开关
     */
    partitionShow(val) {
      if (val) this.getPartition()
      else {
        if (this.partitionEntities.length > 0) {
          this.partitionEntities.forEach((item) => {
            window.viewer.entities.remove(item)
          })
        }
      }
    },
    /**
     * 显示实时
     */
    realTimeShow(val) {
      // MapPopup.clearAll()
      if (val) {
        let sites = JSON.parse(JSON.stringify(this.siteArray))
        this.getSiteNewData(sites)
      } else {
        MapPopup.clearAll()
      }
    },
    /**
     * 清除地图上的实体
     */
    cviewerClear() {
      let viewer = window.viewer
      viewer.entities.removeAll()
    }
  }
}
</script>

<style lang="scss" scoped>
@import './scss.scss';
</style>