<template>
  <div>
    <div class="module-title">专题图</div>
    <div class="module-item"><label>工区统计</label><el-switch v-model="gqtj"></el-switch></div>
    <div class="module-item"><label>扫码地图(次数)</label><el-switch v-model="smdtcs"></el-switch></div>
    <div class="module-item"><label>扫码地图(人数)</label><el-switch v-model="smdtrs"></el-switch></div>
    <div class="module-item"><label>补录数据</label><el-switch v-model="blsj"></el-switch></div>
    <div class="module-item"><label>管道流向</label><el-switch v-model="pipeFlow"></el-switch></div>
    <PipeDirectionSwitch ref="PipeDirectionSwitch" />
  </div>
</template>

<script>
import Vue from 'vue'
import $ from 'jquery'
import {
  getScanPersonStatistics_api,
  getScanTimesStatisticsFilter_api,
  GetBuildAreaStatistic_api,
  pbsTreeSearch_api,
  getPidByPbs_api
} from '@/api/APIs'
import Config from './config.json'
import PipeUnitInfo from '@/views/widgets/PipeUnitInfo/index.vue'
import PipeDirectionSwitch from './PipeDirectionSwitch.vue'
export default {
  name: 'ThematicMap', //编码显示
  components: {
    PipeDirectionSwitch
  },
  props: {
    apiurl: {}
  },
  data() {
    return {
      gqtj: false,
      smdtcs: false,
      smdtrs: false,
      blsj: false,
      pipeFlow: false,
      currentEntiy: null,
      display: null,
      pickSend: null, //已拾取的对象
      scaleHeight: null //比例尺高度
    }
  },
  computed: {
    _apiurl: function () {
      return this.apiurl
    },
    config: function () {
      return Config
    }
  },
  watch: {
    gqtj(n, o) {
      if (n) {
        this.scanRegionStatistics()
      } else {
        this.clearSelection()
        this.removeLabels()
      }
    },
    smdtcs(n, o) {
      if (n) {
        this.smcsStatistics('cs')
      } else {
        this.removeLabels()
      }
    },
    smdtrs(n, o) {
      if (n) {
        this.smcsStatistics('rs')
      } else {
        this.removeLabels()
      }
    },
    blsj(n, o) {
      if (n) {
        this.smcsStatistics('bl')
      } else {
        this.removeLabels()
      }
    },
    pipeFlow(n, o) {
      if (n) {
        this.$refs.PipeDirectionSwitch.psPipeDirectionFlow(n)
      } else {
        this.$refs.PipeDirectionSwitch.psPipeDirectionFlow(false)
      }
    }
  },
  mounted() {
    this._customDataSource = new Cesium.CustomDataSource('displayControlThematicMap')
    window.viewer.dataSources.add(this._customDataSource)
    this.customDataSourcePercent = new Cesium.CustomDataSource('displayControlThematicMapPercent')
    window.viewer.dataSources.add(this.customDataSourcePercent)
    this.customDataSourcePercentRoad = new Cesium.CustomDataSource('displayControlThematicMapPercentAndRoad')
    window.viewer.dataSources.add(this.customDataSourcePercentRoad)
  },
  methods: {
    handlerInit() {
      let that = this
      const clickhandler = new Cesium.ScreenSpaceEventHandler(window.viewer.canvas)
      this.display = 0
      clickhandler.setInputAction(function (movement) {
        var pick = window.viewer.scene.pick(movement.position)
        if (pick) {
          that.showSelect(pick)
        } else {
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
      clickhandler.setInputAction(function (movement) {
        if (that.display === 1) {
          that.removeHightLight(that.pickSend)
        } else {
          that.clearSelection()
        }
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
      clickhandler.setInputAction(function () {
        that.reDisplay()
      }, Cesium.ScreenSpaceEventType.WHEEL)
    },
    /**
     * 计算地图比例尺
     */
    calculateScale() {
      var geodesic = new Cesium.EllipsoidGeodesic()
      let scene = window.viewer.scene
      let width = scene.canvas.clientWidth
      let height = scene.canvas.clientHeight
      let left = scene.camera.getPickRay(new Cesium.Cartesian2((width / 2) | 0, height - 1))
      let right = scene.camera.getPickRay(new Cesium.Cartesian2((1 + width / 2) | 0, height - 1))
      let globe = scene.globe
      let leftPosition = globe.pick(left, scene)
      let rightPosition = globe.pick(right, scene)
      let barWidth
      let distanceLabel
      if (!Cesium.defined(leftPosition) || !Cesium.defined(rightPosition)) {
        barWidth = undefined
        distanceLabel = undefined
        return
      }
      let leftCartographic = globe.ellipsoid.cartesianToCartographic(leftPosition)
      let rightCartographic = globe.ellipsoid.cartesianToCartographic(rightPosition)
      geodesic.setEndPoints(leftCartographic, rightCartographic)
      let pixelDistance = geodesic.surfaceDistance
      // Find the first distance that makes the scale bar less than 100 pixels.
      let BarWidth = 100
      let distance = pixelDistance * BarWidth
      this.scaleHeight = distance
    },
    reDisplay() {
      this.calculateScale() //计算比例尺
      if (this.scaleHeight < 2000) {
        this.customDataSourcePercent.show = false
        this.customDataSourcePercentRoad.show = true
      } else if (this.scaleHeight >= 2000) {
        this.customDataSourcePercent.show = true
        this.customDataSourcePercentRoad.show = false
      }
    },
    /**
     * 扫码次数统计
     * @param id 键值
     */
    smcsStatistics(id) {
      let data = {}
      switch (id) {
        case 'rs':
          getScanPersonStatistics_api(data)
            .then((res) => {
              const result = res
              this.getInfo(result, 'personCount', id)
            })
            .catch((err) => {
              console.log(err)
            })
          break
        case 'cs':
          getScanTimesStatisticsFilter_api(data)
            .then((res) => {
              const result = res
              this.getInfo(result, 'scanCount', id)
            })
            .catch((err) => {
              console.log(err)
            })
          break
        case 'bl':
          data = { isSupplement: 1 }
          getScanTimesStatisticsFilter_api(data)
            .then((res) => {
              const result = res
              this.getInfo(result, 'scanCount', id)
            })
            .catch((err) => {
              console.log(err)
            })
          break
      }
    },
    getInfo(result, totalField, id) {
      const pipe = this.config.pipe
      const that = this
      const minRadius = 1
      const maxRadius = 10
      const fieldName = 'CODE'
      const geourl = this._apiurl.smiddtfw
      if (result.code !== 1) return

      const numList = []
      let min = Number.POSITIVE_INFINITY
      let max = 0
      const filters = []
      const len = result.result.length
      for (let i = 0; i < len; i++) {
        const item = result.result[i]
        const pipename = item.firstLayerName.split(',')[0]
        const layer = this.$_.find(pipe, function (pipeItem) {
          return pipeItem.origindataset === pipename
        })
        numList.push({ dwgc: item['dwgc'], num: item[totalField], radius: 50 })
        min = item[totalField] < min ? item[totalField] : min
        max = item[totalField] > max ? item[totalField] : max
        const queryname = layer.smidmapnameNT ? layer.smidmapnameNT : layer.smidmapname
        const JGFilter = new SuperMap.REST.FilterParameter({
          name: queryname,
          attributeFilter: fieldName + " = '" + item['fristPbs'] + "'",
          fields: [fieldName]
        })
        filters.push(JGFilter)
      }
      for (let i = 0; i < numList.length; i++) {
        let subProj = numList[i]
        const radius = ((subProj['num'] - min) / (max - min)) * (maxRadius - minRadius) + 50
        subProj.radius = radius
      }
      const onComplete = function (geoResult) {
        this.getCurrentInfo()
        geoResult.originResult.recordsets.forEach((record) => {
          const features = record.features
          if (features.length > 1) {
            console.log('pbs重复')
            return true
          }
          if (features.length == 0) {
            return true
          }
          const scanProj = this.$_.find(result.result, function (scanItem) {
            return scanItem.fristPbs === features[0]['fieldValues'][0]
          })
          const dwcgNum = this.$_.find(numList, function (numItem) {
            return numItem['dwgc'] === scanProj['dwgc']
          })
          let cyRadius = dwcgNum['radius']
          let labelText = scanProj[totalField] + ''
          scanProj.displayType = id
          let isDelay
          switch (id) {
            case 'cs':
              if (scanProj.scanTodayConCount > 0) {
                isDelay = 0
                scanProj.title_Info = '今日施工'
              } else {
                isDelay = 1
                scanProj.title_Info = '今日未施工'
              }
              break
            case 'rs':
              if (parseInt(scanProj.personTodayCONCount) > 0) {
                isDelay = 0
                scanProj.title_Info = '今日有办公'
              } else {
                isDelay = 1
                scanProj.title_Info = '今日未办公'
              }
              break
            case 'bl':
              if (scanProj.scanTodayConCount > 0 || scanProj.scanTodaySpvCount > 0) {
                isDelay = 0
                scanProj.title_Info = '今日有补录'
              } else {
                isDelay = 1
                scanProj.title_Info = '今日无补录'
              }
              break
          }
          let position = features[0].geometry.points[0]
          position = Cesium.Cartesian3.fromDegrees(position.x, position.y, position.z)
          that.addUnitBillboard({
            id: scanProj.fristPbs,
            name: scanProj.fristPbs,
            text: labelText,
            position: position,
            cyRadius: cyRadius,
            scanProj: scanProj,
            isDelay: isDelay
          })
        })
      }
      let option = {
        url: geourl,
        filterParameters: filters,
        completed: onComplete.bind(this),
        failed: function (err) {
          console.log(err)
        }
      }
      this.$emit('queryMapByAttribute', option)
    },
    /**
     * 该方法用于生成部件定位指示牌
     * @param options entity信息
     * @param options.id entity ID
     * @param options.text 站点信息
     * @param options.name 站点信息
     * @param options.position 位置
     */
    addUnitBillboard(options) {
      var that = this
      var bottomPosition = Cesium.Cartographic.fromCartesian(options.position)
      var topPosition = Cesium.Cartographic.fromRadians(
        bottomPosition.longitude,
        bottomPosition.latitude,
        bottomPosition.height + 40
      )
      var bPosition = Cesium.Cartographic.toCartesian(bottomPosition)
      var tPosition = Cesium.Cartographic.toCartesian(topPosition)
      var color = 'rgb(56, 136, 205)'
      var canvas = document.createElement('canvas')
      canvas.width = 30
      canvas.height = 30
      var ctx = canvas.getContext('2d')
      let radialRadius = 15
      //添加渐变圆
      switch (options.isDelay) {
        case 0:
          ctx.beginPath()
          var grad = ctx.createRadialGradient(radialRadius, radialRadius, 0, radialRadius, radialRadius, radialRadius)
          grad.addColorStop(0.8, 'rgba(159,33,200,0.9)')
          grad.addColorStop(1, 'rgba(159,33,200,0.7)')
          ctx.fillStyle = grad
          ctx.arc(radialRadius, radialRadius, radialRadius, 0, 2 * Math.PI, true)
          ctx.fill()
          break
        case 1:
          ctx.beginPath()
          var grad = ctx.createRadialGradient(radialRadius, radialRadius, 0, radialRadius, radialRadius, radialRadius)
          grad.addColorStop(0.8, 'rgba(30,144,255,0.9)')
          grad.addColorStop(1, 'rgba(30,144,255,0.7)')
          ctx.fillStyle = grad
          ctx.arc(radialRadius, radialRadius, radialRadius, 0, 2 * Math.PI, true)
          ctx.fill()
          break
      }
      //添加文本
      ctx.lineWidth = 10
      ctx.strokeStyle = color
      ctx.font = '13px Arial'
      var width = ctx.measureText(options.text).width
      ctx.fillStyle = 'rgb(255,255,255)'
      ctx.fillText(options.text, (canvas.width - width) / 2, (canvas.height + 10) / 2)
      //添加柱体对象
      var entity = new Cesium.Entity({
        id: options.id,
        name: options.name,
        show: true,
        position: Cesium.Cartographic.toCartesian(topPosition),
        polyline: {
          positions: [bPosition, tPosition],
          material: Cesium.Color.fromBytes(56, 136, 205, 255),
          width: 3
        },
        billboard: {
          sizeInMeters: false,
          image: canvas,
          width: canvas.width,
          height: canvas.height,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER
        }
      })
      entity.displayType = options.scanProj.displayType
      entity.displayData = options.scanProj
      that._customDataSource.entities.add(entity)
    },
    /**
     * 工区统计
     */
    scanRegionStatistics() {
      //防止地图交互冲突
      this.$store.dispatch('map/changeCurrentTool', null)
      const that = this
      const geourl = this._apiurl.smiddtfw
      const pipe = this.config.pipe
      const fieldName = 'CODE'
      GetBuildAreaStatistic_api()
        .then((res) => {
          const result = res
          if (result.code !== 1) return
          const filters = []
          const len = result.result.length
          for (let i = 0; i < len; i++) {
            const item = result.result[i]
            if (item.firstLayerName) {
              var pipename = item.firstLayerName.split(',')[0]
            }
            const layer = this.$_.find(pipe, function (pipeItem) {
              return pipeItem.origindataset === pipename
            })
            const queryname = layer.smidmapnameNT ? layer.smidmapnameNT : layer.smidmapname
            const JGFilter = new SuperMap.REST.FilterParameter({
              name: queryname,
              attributeFilter: fieldName + " = '" + item['code'] + "'",
              fields: [fieldName]
            })
            filters.push(JGFilter)
          }
          const onComplete = function (geoResult) {
            geoResult.originResult.recordsets.forEach((record) => {
              const features = record.features
              if (features.length > 1) {
                console.log('pbs重复')
                return true
              }
              if (features.length === 0) return true
              const scanProj = this.$_.find(result.result, function (scanItem) {
                return scanItem.code === features[0]['fieldValues'][0]
              })
              let position = features[0].geometry.points[0]
              position = Cesium.Cartesian3.fromDegrees(position.x, position.y, position.z)
              let isDelay
              switch (scanProj.builtStatus) {
                case null:
                  isDelay = 1
                  break
                case 1:
                  isDelay = 1 //待建
                  break
                case 2:
                  isDelay = 2 //在建
                  break
                case 3:
                  isDelay = 3 //完工
                  break
                case 4:
                  isDelay = 4 //停工
                  break
              }
              scanProj.displayType = 'gqtj'
              that.addUnitBillboardWorkArea({
                id: scanProj.code,
                name: scanProj.code,
                position: position,
                scanProj: scanProj,
                isDelay: isDelay
              })
            })
            this.getCurrentInfo()
            this.handlerInit()
            this.clickHightLight()
            this.reDisplay()
          }
          let option = {
            url: geourl,
            filterParameters: filters,
            completed: onComplete.bind(this),
            failed: function (err) {
              console.log(err)
            }
          }
          this.$emit('queryMapByAttribute', option)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    /**
     * 该方法用于生成部件定位指示牌
     * @param options entity信息
     * @param options.id entity ID
     * @param options.text 站点信息
     * @param options.name 站点信息
     * @param options.position 位置
     */
    addUnitBillboardWorkArea(options) {
      var that = this
      var bottomPosition = Cesium.Cartographic.fromCartesian(options.position)
      var topPosition = Cesium.Cartographic.fromRadians(
        bottomPosition.longitude,
        bottomPosition.latitude,
        bottomPosition.height + 40
      )
      var bPosition = Cesium.Cartographic.toCartesian(bottomPosition)
      var tPosition = Cesium.Cartographic.toCartesian(topPosition)
      let percent = options.scanProj['progressRealRate'] ? options.scanProj['progressRealRate'] + '%' : '0%'
      let labelText = options.scanProj['roadName'].substring(0, 4)
      var color = 'rgb(56, 136, 205)'
      var canvas = document.createElement('canvas')
      canvas.width = 30
      canvas.height = 30
      var ctx = canvas.getContext('2d')
      let radialRadius = 15
      //添加渐变圆
      switch (options.isDelay) {
        case 1:
          ctx.beginPath()
          var grad = ctx.createRadialGradient(radialRadius, radialRadius, 0, radialRadius, radialRadius, radialRadius)
          grad.addColorStop(0.8, 'rgba(141,141,141,0.9)')
          grad.addColorStop(1, 'rgba(141,141,141,0.7)')
          ctx.fillStyle = grad
          ctx.arc(radialRadius, radialRadius, radialRadius, 0, 2 * Math.PI, true)
          ctx.fill()
          break
        case 2:
          ctx.beginPath()
          var grad = ctx.createRadialGradient(radialRadius, radialRadius, 0, radialRadius, radialRadius, radialRadius)
          grad.addColorStop(0.8, 'rgba(20,116,196,0.9)')
          grad.addColorStop(1, 'rgba(20,116,196,0.7)')
          ctx.fillStyle = grad
          ctx.arc(radialRadius, radialRadius, radialRadius, 0, 2 * Math.PI, true)
          ctx.fill()
          break
        case 3:
          ctx.beginPath()
          var grad = ctx.createRadialGradient(radialRadius, radialRadius, 0, radialRadius, radialRadius, radialRadius)
          grad.addColorStop(0.8, 'rgba(11,166,91,0.9)')
          grad.addColorStop(1, 'rgba(11,166,91,0.7)')
          ctx.fillStyle = grad
          ctx.arc(radialRadius, radialRadius, radialRadius, 0, 2 * Math.PI, true)
          ctx.fill()
          break
        case 4:
          ctx.beginPath()
          var grad = ctx.createRadialGradient(radialRadius, radialRadius, 0, radialRadius, radialRadius, radialRadius)
          grad.addColorStop(0.8, 'rgba(231,53,53,0.9)')
          grad.addColorStop(1, 'rgba(231,53,53,0.7)')
          ctx.fillStyle = grad
          ctx.arc(radialRadius, radialRadius, radialRadius, 0, 2 * Math.PI, true)
          ctx.fill()
          break
      }
      //添加文本
      ctx.lineWidth = 10
      ctx.strokeStyle = color
      ctx.font = '13px Arial'
      var width = ctx.measureText(percent).width
      ctx.font = '13px Arial'
      ctx.fillStyle = 'rgb(255,255,255)'
      ctx.fillText(percent, (canvas.width - width) / 2, (canvas.height + 10) / 2)
      //添加百分比柱体对象
      var entityPercent = new Cesium.Entity({
        id: options.id,
        name: options.name,
        show: true,
        position: Cesium.Cartographic.toCartesian(topPosition),
        polyline: {
          positions: [bPosition, tPosition],
          material: Cesium.Color.fromBytes(56, 136, 205, 255),
          width: 3
        },
        billboard: {
          sizeInMeters: false,
          image: canvas,
          width: canvas.width,
          height: canvas.height,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER
        }
      })
      entityPercent.displayType = options.scanProj.displayType
      entityPercent.displayData = options.scanProj
      that.customDataSourcePercent.entities.add(entityPercent)
      //添加百分比和道路名称对象
      var canvas2 = document.createElement('canvas')
      canvas2.width = 60
      canvas2.height = 60
      var ctx2 = canvas2.getContext('2d')
      let radialRadius2 = 30
      //添加渐变圆
      switch (options.isDelay) {
        case 1:
          ctx2.beginPath()
          var grad = ctx2.createRadialGradient(
            radialRadius2,
            radialRadius2,
            0,
            radialRadius2,
            radialRadius2,
            radialRadius2
          )
          grad.addColorStop(0.8, 'rgba(141,141,141,0.9)')
          grad.addColorStop(1, 'rgba(141,141,141,0.7)')
          ctx2.fillStyle = grad
          ctx2.arc(radialRadius2, radialRadius2, radialRadius2, 0, 2 * Math.PI, true)
          ctx2.fill()
          break
        case 2:
          ctx2.beginPath()
          var grad = ctx2.createRadialGradient(
            radialRadius2,
            radialRadius2,
            0,
            radialRadius2,
            radialRadius2,
            radialRadius2
          )
          grad.addColorStop(0.8, 'rgba(20,116,196,0.9)')
          grad.addColorStop(1, 'rgba(20,116,196,0.7)')
          ctx2.fillStyle = grad
          ctx2.arc(radialRadius2, radialRadius2, radialRadius2, 0, 2 * Math.PI, true)
          ctx2.fill()
          break
        case 3:
          ctx2.beginPath()
          var grad = ctx.createRadialGradient(
            radialRadius2,
            radialRadius2,
            0,
            radialRadius2,
            radialRadius2,
            radialRadius2
          )
          grad.addColorStop(0.8, 'rgba(11,166,91,0.9)')
          grad.addColorStop(1, 'rgba(11,166,91,0.7)')
          ctx2.fillStyle = grad
          ctx2.arc(radialRadius2, radialRadius2, radialRadius2, 0, 2 * Math.PI, true)
          ctx2.fill()
          break
        case 4:
          ctx2.beginPath()
          var grad = ctx2.createRadialGradient(
            radialRadius2,
            radialRadius2,
            0,
            radialRadius2,
            radialRadius2,
            radialRadius2
          )
          grad.addColorStop(0.8, 'rgba(231,53,53,0.9)')
          grad.addColorStop(1, 'rgba(231,53,53,0.7)')
          ctx2.fillStyle = grad
          ctx2.arc(radialRadius2, radialRadius2, radialRadius2, 0, 2 * Math.PI, true)
          ctx2.fill()
          break
      }
      //添加文本
      ctx2.lineWidth = 10
      ctx2.strokeStyle = color
      ctx2.font = '13px Arial'
      var width = ctx2.measureText(percent).width
      var width2 = ctx2.measureText(labelText).width
      ctx2.font = '13px Arial'
      ctx2.fillStyle = 'rgb(255,255,255)'
      ctx2.fillText(percent, (canvas2.width - width) / 2.5, (canvas2.height - 10) / 2)
      ctx2.fillText(labelText, (canvas2.width - width2) / 2.5, (canvas2.height + 25) / 2)
      //添加柱体对象
      var entityPercentRoad = new Cesium.Entity({
        id: options.id,
        name: options.name,
        show: true,
        position: Cesium.Cartographic.toCartesian(topPosition),
        polyline: {
          positions: [bPosition, tPosition],
          material: Cesium.Color.fromBytes(56, 136, 205, 255),
          width: 3
        },
        billboard: {
          sizeInMeters: false,
          image: canvas2,
          width: canvas2.width,
          height: canvas2.height,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER
        }
      })
      entityPercentRoad.displayType = options.scanProj.displayType
      entityPercentRoad.displayData = options.scanProj
      that.customDataSourcePercentRoad.entities.add(entityPercentRoad)
      that.customDataSourcePercentRoad.entities.show = false
    },
    /**
     * 获取当前统计数据情况
     */
    getCurrentInfo() {
      let parentDom = $('#mainMapContainer .widget-displaycontrol-mapInfoLook')
      if (parentDom.length == 0) {
        $('#mainMapContainer').append("<div class='widget-displaycontrol-mapInfoLook'></div>")
        parentDom = $('#mainMapContainer .widget-displaycontrol-mapInfoLook')
      }
      this.otherDestroy()
      this.handler = new Cesium.ScreenSpaceEventHandler(window.viewer.canvas)
      this.handler.setInputAction(
        function (movement) {
          var pickedObject = window.viewer.scene.pick(movement.endPosition)
          // 使用时，最好利用pickPositionSupported判断一下浏览器是否支持模型高度拾取
          if (window.viewer.scene.pickPositionSupported && Cesium.defined(pickedObject)) {
            let info = pickedObject.id
            if (!info) return
            if (info.displayData) {
              let data = info.displayData
              parentDom.attr('style', 'left:' + movement.endPosition.x + 'px;top:' + movement.endPosition.y + 'px;')
              parentDom.addClass('show')
              switch (info.displayType) {
                case 'gqtj':
                  this.currentEntiy = data
                  let title = data['zdwName']
                  let isYQ = data['predictTime'] > data['planEndTime'] ? '延期风险' : '进度正常'
                  //计划时间
                  let jhsj = this.setNullAndUndefinedEnpty(data['planEndTime'])
                  //延期时间
                  let yqsj = this.setNullAndUndefinedEnpty(data['predictTime'])
                  //管点信息
                  let gdpercent
                  if (((data['nodeScanCount'] / data['tfNodeCount']) * 100).toFixed(2)) {
                    gdpercent = ((data['nodeScanCount'] / data['tfNodeCount']) * 100).toFixed(2)
                  } else {
                    gdpercent = 0
                  }
                  if (gdpercent === '0.00') {
                    gdpercent = 0
                  }
                  let smgd = this.setNullAndUndefinedEnpty(data['nodeScanCount'])
                  let gdNum = gdpercent + '%，' + smgd + '个'
                  let gdTotal = this.setNullAndUndefinedEnpty(data['tfNodeCount'])
                  //管道信息
                  let gxpercent = this.setNullAndUndefinedEnpty(data['lengthPercentNew'])
                  let gxsm = this.setNullAndUndefinedEnpty(data['tfPipeLengthNew'])
                  let gxNum = gxpercent + '%，' + gxsm + 'm'
                  let gxbj = this.setNullAndUndefinedEnpty(data['tfPipeCount'])
                  let gxcd = this.setNullAndUndefinedEnpty(data['tfPipeLength'])
                  let gxTotal = gxbj + '个，' + gxcd + 'm'
                  let html = this.addContainer('gqtj')
                  parentDom.empty().append(html)
                  let gqtj = parentDom.find('.gqtj')
                  gqtj.find('.gqtj-title').text(title)
                  gqtj.find('.gqtj-isYQ').text(isYQ)
                  gqtj.find('.jhsjdata').text(jhsj)
                  gqtj.find('.yqsjdata').text(yqsj)
                  gqtj.find('.gqtj-gdNum').text(gdNum)
                  gqtj.find('.gqtj-gdTotal').text(gdTotal + '个')
                  gqtj.find('.gqtj-gxNum').text(gxNum)
                  gqtj.find('.gqtj-gxTotal').text(gxTotal)
                  if (data['predictTime'] <= data['planEndTime']) {
                    gqtj.find('.gqtj-isYQ').addClass('gqtj-isZC')
                  }
                  //百分比;
                  let gdCssPercent = gdpercent > 100 ? 100 : gdpercent
                  let gxCssPercent = gxpercent > 100 ? 100 : gxpercent
                  gqtj.find('.gqtj-gdys2').attr('style', 'width:' + gdCssPercent + '%')
                  gqtj.find('.gqtj-gxys2').attr('style', 'width:' + gxCssPercent + '%')
                  break
                case 'cs':
                  let csTitle = data['dwgc']
                  let isSG = data['title_Info']
                  //施工扫码
                  let sgsm = data['scanConCount']
                  //监理扫码
                  let jlsm = data['scanSpvCount']
                  //今日施工扫码
                  let jrsgsm = data['scanTodayConCount']
                  //今日监理扫码
                  let jrjlsm = data['scanTodaySpvCount']
                  let csHtml = this.addContainer('cs')
                  parentDom.empty().append(csHtml)
                  let smtjDom = parentDom.find('.smsj')
                  smtjDom.find('.smsj-title').text(csTitle)
                  smtjDom.find('.smsj-issg').text(isSG)
                  if (jrsgsm !== 0) {
                    smtjDom.find('.smsj-issg').css('background', 'yellow')
                  }
                  smtjDom.find('.smsj-sgsmNum').text(sgsm)
                  smtjDom.find('.smsj-jlsmNum').text(jlsm)
                  smtjDom.find('.smsj-jrsgsmNum').text(jrsgsm)
                  smtjDom.find('.smsj-jrjlsmNum').text(jrjlsm)
                  break
                case 'rs':
                  let rsTitle = data['dwgc']
                  let issg = data['title_Info']
                  //施工扫码
                  let zrs = data['personCount']
                  //今日总人数
                  let jrzrs = data['personTodayCount']
                  //今日施工人数
                  let sgsmrs = data['personTodayCONCount']
                  //今日监理人数
                  let jlsmrs = data['personTodaySPVCount']
                  let rsHtml = this.addContainer('rs')
                  parentDom.empty().append(rsHtml)
                  let smrstjDom = parentDom.find('.smsj')
                  smrstjDom.find('.smsj-title').text(rsTitle)
                  smrstjDom.find('.smsj-issg').text(issg)
                  if (sgsmrs !== 0) {
                    smrstjDom.find('.smsj-issg').css('background', 'yellow')
                  }
                  smrstjDom.find('.zrsNum').text(zrs)
                  smrstjDom.find('.jrsmrsNum').text(jrzrs)
                  smrstjDom.find('.jrsgsmrsNum').text(sgsmrs)
                  smrstjDom.find('.jrjlsmrsNum').text(jlsmrs)
                  break
                case 'bl':
                  let blTitle = data['dwgc']
                  let isBL = data['title_Info']
                  //施工补录
                  let sgbl = data['scanConCount']
                  //监理补录
                  let jlbl = data['scanSpvCount']
                  //今日施工补录
                  let jrsgbl = data['scanTodayConCount']
                  //今日监理补录
                  let jrjlbl = data['scanTodaySpvCount']
                  let blHtml = this.addContainer('bl')
                  parentDom.empty().append(blHtml)
                  let blsjDom = parentDom.find('.smsj')
                  blsjDom.find('.smsj-title').text(blTitle)
                  blsjDom.find('.smsj-issg').text(isBL)
                  if (jrsgbl !== 0 || jrjlbl !== 0) {
                    blsjDom.find('.smsj-issg').css('background', 'yellow')
                  }
                  blsjDom.find('.sgblNum').text(sgbl)
                  blsjDom.find('.jlblNum').text(jlbl)
                  blsjDom.find('.jrsgblNum').text(jrsgbl)
                  blsjDom.find('.jrjlblNum').text(jrjlbl)
                  break
              }
            } else {
              if (parentDom.hasClass('show')) {
                parentDom.removeClass('show')
                this.currentEntiy = null
              }
            }
          } else {
            if (parentDom.hasClass('show')) {
              parentDom.removeClass('show')
              this.currentEntiy = null
            }
          }
        }.bind(this),
        Cesium.ScreenSpaceEventType.MOUSE_MOVE
      )
    },
    //浮动框内容添加
    addContainer(type) {
      let html = []
      html.push("<div class='smsj'>")
      html.push("<div class='smsj-headerTitle'>")
      html.push("<span class='smsj-title'></span>")
      html.push("<span class='smsj-issg'></span></div>")
      html.push("<div class='smsj-infoDisplay'>")
      html.push("<div class='smsj-total'>")
      if (type == 'cs') {
        html.push("<span class='smsj-sgsm'>施工扫码：<span class='smsj-sgsmNum'></span>次</span>")
        html.push("<span class='smsj-jlsm'>监理扫码：<span class='smsj-jlsmNum'></span>次</span></div>")
        html.push("<div class='smsj-today'>")
        html.push("<span class='smsj-jrsgsm'>今日施工：<span class='smsj-jrsgsmNum'></span>次</span>")
        html.push("<span class='smsj-jrjlsm'>今日监理：<span class='smsj-jrjlsmNum'></span>次</span></div></div></div>")
        return html.join('')
      }
      if (type == 'rs') {
        html.push("<span class='smsj-sgsm'>累计办公：<span class='zrsNum'></span>人</span>")
        html.push("<span class='smsj-jlsm'>今日办公：<span class='jrsmrsNum'></span>人</span></div>")
        html.push("<div class='smsj-today'>")
        html.push("<span class='smsj-jrsgsm'>今日施工：<span class='jrsgsmrsNum'></span>人</span>")
        html.push("<span class='smsj-jrjlsm'>今日监理：<span class='jrjlsmrsNum'></span>人</span></div></div></div>")
        return html.join('')
      }
      if (type == 'bl') {
        html.push("<span class='smsj-sgsm'>施工补录：<span class='sgblNum'></span>次</span>")
        html.push("<span class='smsj-jlsm'>监理补录：<span class='jlblNum'></span>次</span></div>")
        html.push("<div class='smsj-today'>")
        html.push("<span class='smsj-jrsgsm'>今日施工补录：<span class='jrsgblNum'></span>次</span>")
        html.push("<span class='smsj-jrjlsm'>今日监理补录：<span class='jrjlblNum'></span>次</span></div></div></div>")
        return html.join('')
      }
      if (type == 'gqtj') {
        html = []
        html.push("<div class='gqtj'>")
        html.push("<div class='gqtj-headerTitle'><span class='gqtj-title'></span><span class='gqtj-isYQ'></span></div>")
        html.push("<div class='gqtj-dataInfo'>")
        html.push("<span class='gqtj-jhsj'>计划完成时间：<span class='jhsjdata'></span></span>")
        html.push("<span class='gqtj-yqsj'>预计完成时间：<span class='yqsjdata'></span></span></div>")
        html.push("<div class='gqtj-infoDisplay'>")
        html.push("<div class='gqtj-gd'>")
        html.push(
          "<span class='gqtj-gdTitle'>管点：</span><div class='gqtj-ys'><span class='gqtj-gdys'></span><span class='gqtj-gdys2'></span></div><span class='gqtj-gdNum'></span><span class='gqtj-gdTotal'></span></div>"
        )
        html.push("<div class='gqtj-gx'>")
        html.push(
          "<span class='gqtj-gxTitle'>管线：</span><div class='gqtj-ys'><span class='gqtj-gxys'></span><span class='gqtj-gxys2'></span></div><span class='gqtj-gxNum'></span><span class='gqtj-gxTotal'></span></div>"
        )
        html.push('</div></div>')
        return html.join('')
      }
    },
    //单击高亮显示部件
    clickHightLight() {
      this.handler = new Cesium.ScreenSpaceEventHandler(window.viewer.canvas)
      //点击高亮工程下所有部件
      this.handler.setInputAction(
        function (movement) {
          var that = this
          if (that.display === 0) {
            that.clearSelection()
          }
          var pickedObject = window.viewer.scene.pick(movement.position)
          // 使用时，最好利用pickPositionSupported判断一下浏览器是否支持模型高度拾取
          if (window.viewer.scene.pickPositionSupported && Cesium.defined(pickedObject)) {
            if (!pickedObject) return
            if (pickedObject && pickedObject.id && pickedObject.id.displayType === 'gqtj') {
              that.pickResult(pickedObject)
            }
          } else {
            return
          }
        }.bind(this),
        Cesium.ScreenSpaceEventType.LEFT_CLICK
      )
    },
    pickResult(pickedObject) {
      let that = this
      let info = pickedObject.id
      const pbsname = info.displayData.code.split('.')[0] + '.' + info.displayData.code.split('.')[1]
      pbsTreeSearch_api({ pbs: pbsname, pageSize: 9999 })
        .then((res) => {
          const result = res
          if (result.code !== 1) return
          that.pbspart(result.result)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    pbspart(result) {
      let that = this
      const filters = []
      const pipe = that.config.pipe
      const fieldName = 'CODE'
      const geourl = that._apiurl.smiddtfw
      result.forEach((item) => {
        const pipename = item.layerName.split(',')[0]
        const layer = that.$_.find(pipe, function (pipeItem) {
          return pipeItem.origindataset === pipename
        })
        //多图层搜索
        const queryname = layer.smidmapnameNT ? layer.smidmapnameNT : layer.smidmapname
        const JGFilter = new SuperMap.REST.FilterParameter({
          name: queryname,
          attributeFilter: fieldName + " = '" + item.code + "'",
          fields: [fieldName]
        })
        filters.push(JGFilter)
      }) //循环结束
      //成功回调函数
      const queryComplete = function (geoResult) {
        if (geoResult.originResult.recordsets[0].features.length < 1) return
        geoResult.originResult.recordsets.forEach((item) => {
          const pbsid = item.features[0].fieldValues[0]
          const geometry = item.features[0].geometry
          that.hightLight(geometry, pbsid) //高亮
        })
      }
      //属性查找
      let option = {
        url: geourl,
        filterParameters: filters,
        completed: queryComplete.bind(this),
        failed: function (err) {
          console.log(err)
        }
      }
      that.$emit('queryMapByAttribute', option)
    },
    /**
     * 结果二维高亮
     * @param result
     * @returns
     */
    hightLight(result, pbsid) {
      if (!this._pointPrimitiveCollection) {
        this._pointPrimitiveCollection = new Cesium.PointPrimitiveCollection()
        window.viewer.scene.primitives.add(this._pointPrimitiveCollection) //添加点容器
      }
      if (!this._polylineprimitiveCollection) {
        this._polylineprimitiveCollection = new Cesium.PrimitiveCollection()
        window.viewer.scene.primitives.add(this._polylineprimitiveCollection) //添加线容器
      }
      if (!result) return
      if (!this._pointPrimitiveCollection) return
      if (!this._polylineprimitiveCollection) return
      const type = result.type //获取要素类型
      let position = result.points //获取坐标信息
      if (type === 'POINT3D') {
        const pointS = Cesium.Cartesian3.fromDegrees(position[0].x, position[0].y, position[0].z)
        this._polylineprimitiveCollection.add(generaGroundCircle(pointS, 2, pbsid))
      } else {
        const pointA = Cesium.Cartesian3.fromDegrees(position[0].x, position[0].y)
        const pointB = Cesium.Cartesian3.fromDegrees(position[1].x, position[1].y)
        this._polylineprimitiveCollection.add(GroundPolyline([pointA, pointB], pbsid))
      }
      //管点高亮
      function generaGroundCircle(center, axis, pbsid) {
        //圆
        const instance = new Cesium.GeometryInstance({
          geometry: new Cesium.EllipseGeometry({
            center: center,
            semiMajorAxis: axis,
            semiMinorAxis: axis,
            height: 100.0
          }),
          attributes: {
            color: new Cesium.ColorGeometryInstanceAttribute(0.0, 1.0, 1.0, 0.5)
          },
          id: pbsid
        })
        const circle = new Cesium.GroundPrimitive({
          geometryInstances: instance,
          appearance: new Cesium.PerInstanceColorAppearance({
            flat: true,
            translucent: false
          }),
          classificationType: Cesium.ClassificationType.TERRAIN
        })
        circle.custom = { name: 'pickcircle' }
        return circle
      }
      //管线高亮
      function GroundPolyline(positions, pbsid) {
        const instance = new Cesium.GeometryInstance({
          geometry: new Cesium.GroundPolylineGeometry({
            positions: positions,
            width: 15.0
          }),
          attributes: {
            color: new Cesium.ColorGeometryInstanceAttribute(0.0, 1.0, 1.0, 0.5)
          },
          id: pbsid
        })
        const polyline = new Cesium.GroundPolylinePrimitive({
          geometryInstances: instance,
          appearance: new Cesium.PolylineColorAppearance(),
          classificationType: Cesium.ClassificationType.TERRAIN
        })
        polyline.custom = { name: 'pickpolyline' }
        return polyline
      }
    },
    /**
     *
     * @param pick 屏幕点击获取到的对象
     */
    showSelect(pick) {
      this.pickSend = pick
      this.pickHightLight(pick)
    },
    /**
     * 该方法用于根据pbs编码定位部件位置
     * @param pbs
     */
    locateUnit(pbs) {
      getPidByPbs_api({ pbs: pbs }).then((res) => {
        const result = res
        if (result.code !== 1) return
        let lyName = result.result.layerName
        const code = pbs
        if (lyName.indexOf(',') > -1) {
          lyName = lyName.split(',')[1]
        } else {
          lyName = lyName
        }
        const pipeInfoConstructor = Vue.extend(PipeUnitInfo)
        const pipeInfo = new pipeInfoConstructor({
          data: {
            pickType: 'point',
            isInteractive: false,
            locateUnit: {
              name: lyName,
              id: code
            }
          },
          store: this.$store
        }).$mount()
      })
    },
    /**
     * 对象高亮
     * @param pick 拾取对象
     * @param index 对象索引值
     */
    pickHightLight(pick) {
      if (!pick.id) return
      if (pick.id.displayType === 'gqtj') {
        return
      } else if (pick.primitive.custom) {
        var attributes = pick.primitive.getGeometryInstanceAttributes(pick.id) //获取某个实例的属性集
        attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromBytes(255, 125, 0)) //设置其高亮
        this.display = 1
        this.locateUnit(pick.id)
      }
    },
    /**
     * 清除对象高亮
     * @param pick
     * @param index
     */
    removeHightLight(pick) {
      if (pick.id.displayType === 'gqtj') {
        return
      } else {
        var attributes = pick.primitive.getGeometryInstanceAttributes(pick.id) //获取某个实例的属性集
        attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromBytes(0, 255, 255, 50)) //设置其初始颜色
        this.display = 0
      }
    },
    /**
     * 清除高亮显示
     */
    clearSelection() {
      window.viewer.scene.layers.releaseSelection()
      this.clearAllPrimitives()
    },
    /**
     * 该方法用于清除二维点和线的primitivecollection
     */
    clearAllPrimitives() {
      if (this._pointPrimitiveCollection) {
        this._pointPrimitiveCollection.removeAll()
        const isPointDel = window.viewer.scene.primitives.remove(this._pointPrimitiveCollection)
        if (isPointDel) this._pointPrimitiveCollection = null
      }
      if (this._polylineprimitiveCollection) {
        this._polylineprimitiveCollection.removeAll()
        const isPolylineDel = window.viewer.scene.primitives.remove(this._polylineprimitiveCollection)
        if (isPolylineDel) this._polylineprimitiveCollection = null
      }
    },
    /**
     * 本方法用于对列表输出的空值的统一设置为空（传入值为null、undefined、""的统一设置），目前统一设置为--
     * @param input 判断的输入
     * */
    setNullAndUndefinedEnpty(input) {
      if (
        input === 'Null' ||
        input === 'null' ||
        input === 'NULL' ||
        input === null ||
        input === undefined ||
        input === ''
      ) {
        return 0
      } else {
        return input
      }
    },
    removeLabels() {
      if (Cesium.defined(this._customDataSource)) {
        this._customDataSource.entities.removeAll()
      }
      if (Cesium.defined(this.customDataSourcePercent)) {
        this.customDataSourcePercent.entities.removeAll()
      }
      if (Cesium.defined(this.customDataSourcePercentRoad)) {
        this.customDataSourcePercentRoad.entities.removeAll()
      }
      let parentDom = $('#mainMapContainer .widget-displaycontrol-mapInfoLook')
      if (parentDom.length != 0) {
        parentDom.remove()
      }
    },
    otherDestroy() {
      if (this.handler != null && !this.handler.isDestroyed()) {
        this.handler.removeInputAction(Cesium.ScreenSpaceEventType.MOUSE_MOVE) //移除事件
        this.handler.destroy()
      }
    },
    removeSource() {
      this.clearSelection()
      this.removeLabels()
      this.otherDestroy()
      window.viewer.dataSources.remove(this._customDataSource)
      window.viewer.dataSources.remove(this.customDataSourcePercent)
      window.viewer.dataSources.remove(this.customDataSourcePercentRoad)
    }
  }
}
</script>

<style lang="scss" scoped>
.module-title {
  padding: 8px 20px;
  text-align: center;
  font-size: 1rem;
  background: #99c3e8;
}
.module-item {
  padding: 8px 20px;
  display: flex;
  justify-content: space-between;
  label {
    vertical-align: middle;
  }
}
</style>