<template>
  <transition
    appear
    name="animate__animated animate__move"
    enter-active-class="animate__zoomIn"
    leave-active-class="animate__zoomOut"
  >
    <div class="widget-ProjectPipeSpeedInfoCheck" v-Gpdrag>
      <div class="header">
        <span class="close">
          <i class="el-icon-close" @click="close()" />
        </span>
        <div class="leftBar">
          <span>进度专题图</span>
          <CommonTreeList
            style="width: 0.833333rem; /* 160/192 */"
            :placeholder="'工程选择'"
            :prjId="prjId"
            isSelectDefault
            @changeProjectName="prjChange($event)"
          />
        </div>
        <div class="rightBar">
          <el-date-picker
            style="width: 220px"
            :picker-options="pickerOptions"
            v-model="dateValue"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            :default-time="['00:00:00', '23:59:59']"
            size="mini"
            @change="dateChange"
          >
          </el-date-picker>
          <!-- <span>{{ timeLag[0] }}</span
          >{{ timeLag[0] ? '至' : '' }}<span>{{ timeLag[1] }}</span> -->
        </div>
      </div>
      <div class="content">
        <template v-if="resultData.length > 0">
          <div class="left">
            <img class="operationBtn" :src="buttonImg" @click="play()" />
            <el-select v-model="timeInterval" placeholder="请选择">
              <el-option v-for="item in intervalOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div class="right">
            <!-- <el-steps :active="active" finish-status="success">
              <el-step :title="item[0].split(' ')[0]" v-for="(item, index) in timeSteps" :key="index"></el-step>
            </el-steps> -->
            <el-slider
              v-model="active"
              show-tooltip
              :marks="marks"
              :format-tooltip="sliderFormat"
              :min="0"
              :max="timeSteps.length - 1"
              @change="sliderChange"
            ></el-slider>
          </div>
        </template>
        <el-empty v-else description="暂无数据" :image-size="40" style="flex: 1"></el-empty>
      </div>
    </div>
  </transition>
</template>

<script lang="ts">
import _ from 'lodash'
import moment from 'moment'
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import { GetProgress, PipeAndNodeProcess } from '@/api/APIs'
import { queryMapByAttribute, CircleWaveMaterialProperty } from '@/views/groupPage/util'
import config from '@/views/groupPage/districtPageModules/customTools/config.json'
import pipeInfo from '@/views/groupPage/districtPageModules/customTools/infoComponents/pipeInfo.vue'
import CommonTreeList from '@/views/groupPage/components/ComTreeList.vue'
import { watch } from 'vue-demi'
const gPipe = config.gPipe
const SuperMap = (window as any).SuperMap
const Cesium = (window as any).Cesium
let gCustomDataSource = null
let gPrimitiveCollection = null
let gHandler = null
let pointDataSource = null //聚合源
//进度查看模块
@Component({ name: 'ProjectPipeSpeedInfoCheck', components: { CommonTreeList } })
export default class ProjectPipeSpeedInfoCheck extends Vue {
  viewer
  apiurls = {
    sjfw: '',
    smiddtfw: ''
  }
  pipeInfo = null
  selectPrj: string = ''
  resultData = [] //进度结果数据保存
  //时间戳值
  active: number = 0
  //播放变量
  buttonImg = ''
  playButtonImg = require('@/views/groupPage/images/工具栏/play.png')
  pauseButtonImg = require('@/views/groupPage/images/工具栏/stop.png')
  isPlaying = false
  isShowCompletion = false
  //日期控件
  dateValue = []
  pickerOptions = {}
  //防抖
  timeout = null
  //聚合参数
  pointArrCluster = [] //聚合点数组
  //
  get marks() {
    let t = {}
    t[this.active] = {
      style: { color: '#1989FA', fontWeight: 'bold' },
      label: this.settings()
    }
    // t[0] = {
    //   style: { color: '#1989FA', fontWeight: 'bold' },
    //   label: `${moment(this.timeSteps[0][0]).format('YYYY-MM-DD')}`
    // }
    // t[this.timeSteps.length - 1] = {
    //   style: { color: '#1989FA', fontWeight: 'bold' },
    //   label: `${moment(this.timeSteps[this.timeSteps.length - 1][1]).format('YYYY-MM-DD')}`
    // }
    return t
  }
  get prjId() {
    return this.$store.state.bigScreen.currentPrjId
  }
  settings() {
    let label = ''
    switch (this.timeInterval) {
      case 1:
        label = `${moment(
          this.active !== this.timeSteps.length - 1 ? this.timeSteps[this.active][0] : this.timeSteps[this.active][1]
        ).format('YYYY/MM/DD')}`
        break
      default:
        label =
          `${moment(this.timeSteps[this.active][0]).format('YYYY/MM/DD')}` +
          `至` +
          `\n${moment(this.timeSteps[this.active][1]).format('YYYY/MM/DD')}`
        break
    }

    return label
  }
  //
  isLoadFirst = true
  timeLag = []
  splitTimeArr = []
  timeSteps: Array<Array<string>> = []
  timeInterval = 30
  intervalOptions = [
    { value: 1, label: '按天' },
    { value: 7, label: '按周' },
    { value: 30, label: '按月' }
  ]
  //监听间隔变化
  @Watch('timeInterval')
  timeIntervalChangeMethod() {
    this.active = 0
    this.splitTime()
  }
  //播放监听
  @Watch('isPlaying', { immediate: true })
  activeChangeMethod(val) {
    this.buttonImg = val ? this.pauseButtonImg : this.playButtonImg
  }
  get mapConfig() {
    return this.$store.state.bigScreen.mapConfig
  }
  mounted() {
    this.viewer = (window as any).viewer
    this.init()
    // this.initScanTimes()
  }
  //初始化数据服务地址
  init() {
    this.apiurls.sjfw = this.mapConfig.gisResource.tiplayers.config['sjfw'].url
    this.apiurls.smiddtfw = this.mapConfig.gisResource.tiplayers.config['bjsmidfw'].url
    gCustomDataSource = new Cesium.CustomDataSource('displaycontrol')
    this.viewer.dataSources.add(gCustomDataSource)
  }
  //进度滑块提示信息
  sliderFormat(e) {
    return this.timeSteps.length > 0 && this.timeSteps[e]
      ? e !== this.timeSteps.length - 1
        ? this.timeSteps[e][0]
        : this.timeSteps[e][1]
      : e
  }
  //进度滑块改变
  sliderChange() {
    this.isPlaying = false
  }
  //开始播放
  play() {
    this.isPlaying = !this.isPlaying
    if (this.isPlaying) {
      this.loopPlayback()
    } else {
    }
  }
  @Watch('isShowCompletion')
  onchangeMethod(n, o) {
    if (n && this.isPlaying) {
      this.loopPlayback()
    }
  }
  @Watch('dateValue')
  onchangeDateValueMethod(date, o) {
    if (!date) {
      this.splitTimeArr = this.timeLag
      this.dateValue = [new Date(this.timeLag[0]), new Date()]
      this.splitTime()
      this.initScanTimes()
      return
    }
    const time = [moment(date[0]).format('YYYY-MM-DD'), moment(date[1]).format('YYYY-MM-DD')]
    this.splitTimeArr = time
    this.splitTime()
  }
  @Watch('active')
  onChangeActiveMethod(n) {
    const data2 = {
      beginDate: this.timeSteps[this.active][0].replaceAll('-', ''),
      endDate: this.timeSteps[this.active][1].replaceAll('-', '')
    }
    this.clearSpeedInfos()
    this.debounce(() => {
      this.initScanTimes(data2)
    }, 1000)
  }
  //去抖延迟
  debounce(fn, wait) {
    if (this.timeout !== null) clearTimeout(this.timeout)
    this.timeout = setTimeout(fn, wait)
  }
  loopPlayback() {
    //长度减一是因为timeSteps存储的是时间间隔
    if (this.active >= this.timeSteps.length - 1) {
      this.active = 0
    }
    this.isShowCompletion = false
    setTimeout(() => {
      this.active += 1
    }, 5000)
  }
  prjChange(data) {
    this.active = 0
    this.clearSpeedInfos()
    if (data != '') {
      const { name } = data
      this.selectPrj = name
      this.initScanTimes()
    } else {
      this.selectPrj = ''
      this.timeSteps = []
      this.resultData = []
      if (this.dateValue) this.initScanTimes()
    }
  }
  //时间改变
  dateChange() {
    this.active = 0
    this.clearSpeedInfos()
    if (!this.dateValue) {
      this.isPlaying = false
      this.timeSteps = []
      this.resultData = []
      if (this.selectPrj) this.initScanTimes()
      return
    } else {
      this.initScanTimes()
    }
  }
  //时间分割函数
  splitTime() {
    let start = this.splitTimeArr[0]
    let end = this.splitTimeArr[1]
    let intD = this.timeInterval
    this.timeSteps = []
    const startTime = start
    const endTime = end
    const intervalDay = (getDate(endTime).getTime() - getDate(startTime).getTime()) / (1000 * 60 * 60 * 24)
    if (intervalDay >= 1) {
      let timeArr = formatEveryDay(startTime, endTime)
      this.timeSteps = group(timeArr, 2)
    } else {
      let timeArr: Array<string> = []
      timeArr.push(start)
      timeArr.push(end)
      this.timeSteps.push(timeArr)
    }
    function formatEveryDay(s, e) {
      let dateList = []
      let startTimeC = getDate(s)
      let endTimeC = getDate(e)

      while (endTimeC.getTime() - startTimeC.getTime() >= 0) {
        let year = startTimeC.getFullYear()
        let month = startTimeC.getMonth() + 1 < 10 ? '0' + (startTimeC.getMonth() + 1) : startTimeC.getMonth() + 1
        let day = startTimeC.getDate().toString().length == 1 ? '0' + startTimeC.getDate() : startTimeC.getDate()
        // dateList.push(year + '-' + month + '-' + day + ' ' + start.split(' ')[1])
        dateList.push(year + '-' + month + '-' + day)
        startTimeC.setDate(startTimeC.getDate() + intD)
      }
      dateList[dateList.length - 1] = endTime
      return dateList
    }
    function getDate(datestr) {
      let temp = datestr.split('-')
      let date = new Date(temp[0], temp[1] - 1, temp[2])
      return date
    }
    function group(array, subGroupLength) {
      let index = 0
      let newArray = []
      while (index < array.length - 1) {
        newArray.push(array.slice(index, index + subGroupLength))
        index += 1
      }
      return newArray
    }
  }
  timeDataAssembly(result) {
    let mini = [],
      max = []
    result.map((item) => {
      if (item.minScanTime) mini.push(new Date(item.minScanTime))
      if (item.maxScanTime) max.push(new Date(item.maxScanTime))
    })
    var minDate = new Date(Math.min.apply(null, mini))
    var maxDate = new Date(Math.max.apply(null, max))
    this.timeLag = [moment(minDate).format('YYYY-MM-DD'), moment(new Date()).format('YYYY-MM-DD')]
    this.splitTimeArr = this.timeLag
    this.dateValue = [minDate, new Date()]
    this.setDisabledDate(minDate, new Date())
    this.splitTime()
  }
  setDisabledDate(min, max) {
    this.pickerOptions = Object.assign({}, this.pickerOptions, {
      disabledDate(time) {
        // return !(moment(time).isSameOrAfter(moment(min)) && moment(time).isSameOrBefore(moment(max)))
        return !(time.getTime() >= min - 8.64e7 && time.getTime() <= max)
      }
    })
  }
  //进度信息查询
  async initScanTimes(date?) {
    const pipe = gPipe
    const that = this
    const fieldName = 'CODE'
    const geourl = this.apiurls.smiddtfw
    let dateRange = {
      queryText: this.selectPrj,
      beginDate: date
        ? date.beginDate
        : this.dateValue && this.dateValue[0]
        ? moment(this.dateValue[0]).format('YYYY-MM-DD').replaceAll('-', '')
        : '',
      endDate: date
        ? date.endDate
        : this.dateValue && this.dateValue[1]
        ? moment(this.dateValue[1]).format('YYYY-MM-DD').replaceAll('-', '')
        : ''
    }
    let s_dt = date
      ? date.beginDate
      : this.dateValue && this.dateValue[0]
      ? moment(this.dateValue[0]).format('YYYY-MM-DD')
      : ''
    let e_dt = date
      ? date.endDate
      : this.dateValue && this.dateValue[1]
      ? moment(this.dateValue[1]).format('YYYY-MM-DD')
      : ''
    await this.showSpeedInfos(s_dt, e_dt)
    PipeAndNodeProcess(dateRange)
      .then((result) => {
        if (result.code !== 1 || result.result.length === 0) {
          this.isShowCompletion = true
          return
        }
        if (!this.isPlaying && this.active == 0) {
          this.resultData = result.result
          if (this.isLoadFirst || this.selectPrj == '') {
            this.timeDataAssembly(result.result)
            this.isLoadFirst = false
          }
        }
        const filters = []
        const cwpInfos = []
        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 = _.find(pipe, function (pipeItem) {
            return pipeItem.origindataset === pipename
          })
          if (!layer) {
            continue
          }
          //组装
          let cwpInfo = {
            name: '',
            roadName: '',
            code: '',
            dateRange: '',
            design: {
              name: '',
              total: 0,
              pipe: 0,
              node: 0
            },
            spv: {
              name: '',
              pipeLen: 0,
              times: 0,
              part: 0,
              pictures: 0
            },
            con: {
              name: '',
              pipeLen: 0,
              times: 0,
              part: 0,
              pictures: 0,
              totalLen: 0
            }
          }
          cwpInfo.dateRange = dateRange.beginDate + '~' + dateRange.endDate
          cwpInfo.code = item.firstPbs
          cwpInfo.name = item.zdwName
          cwpInfo.roadName = item.roadName
          //设计
          const design = _.find(item.tjData, (djData) => {
            return djData.dataType === 'DESIGN'
          })
          if (design) {
            cwpInfo.design.name = design.designUnit
            cwpInfo.design.total = design.tfPipeLength
            cwpInfo.design.pipe = design.tfPipeCount
            cwpInfo.design.node = design.tfNodeCount
          }
          //施工
          const con = _.find(item.tjData, (djData) => {
            return djData.dataType === 'CON'
          })
          if (con) {
            cwpInfo.con.name = con.buildUnit
            cwpInfo.con.pipeLen = con.smLength
            cwpInfo.con.times = con.scanTimes
            cwpInfo.con.part = con.partsTotal
            cwpInfo.con.pictures = con.pictures
            cwpInfo.con.totalLen = con.builtLength
          }
          //监理
          const spv = _.find(item.tjData, (djData) => {
            return djData.dataType === 'SPV'
          })
          if (spv) {
            cwpInfo.spv.name = spv.supervisionUnit
            cwpInfo.spv.pipeLen = spv.smLength
            cwpInfo.spv.times = spv.scanTimes
            cwpInfo.spv.part = spv.partsTotal
            cwpInfo.spv.pictures = spv.pictures
          }
          //合并相同数据
          let same = cwpInfos.find((e) => e.code == item.firstPbs)
          if (same) {
            Object.assign(same, cwpInfo)
          } else {
            cwpInfos.push(cwpInfo)
          }
          //多图层搜索
          const queryname = layer.smidmapnameNT ? layer.smidmapnameNT : layer.smidmapname
          const JGFilter = new SuperMap.REST.FilterParameter({
            name: queryname,
            attributeFilter: fieldName + " = '" + item['firstPbs'] + "'",
            fields: [fieldName]
          })
          filters.push(JGFilter)
        }
        const onComplete = function (geoResult) {
          console.log('地图查询结果', geoResult)
          //交互事件
          that.getCurrentInfo()
          let promiseArr = []
          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 = _.find(cwpInfos, function (scanItem) {
              return scanItem.code === features[0]['fieldValues'][0]
            })
            let position = features[0].geometry.points[0]
            promiseArr.push(
              new Promise((resolve, reject) => {
                let isLoaded = this.addEntity({
                  id: scanProj.code,
                  name: scanProj.code,
                  position: Cesium.Cartesian3.fromDegrees(position.x, position.y, position.z),
                  scanProj: scanProj
                })
                if (isLoaded) {
                  resolve(true)
                } else {
                  reject(false)
                }
              })
            )
          })
          Promise.all(promiseArr).then(
            () => isCompleted(),
            () => isCompleted()
          )
          function isCompleted() {
            setTimeout(() => {
              that.isShowCompletion = true
            }, 500)
          }
        }
        queryMapByAttribute({
          url: geourl,
          filterParameters: filters,
          completed: onComplete.bind(this),
          failed: function (err) {
            console.log(err)
          }
        })
      })
      .catch((err) => {
        console.log(err)
      })
  }
  //添加工程图标
  addEntity(options) {
    let imgSrc = require('@/views/groupPage/images/地图/进度施工.png')
    let ellipse = {}
    if (options.scanProj.con.pipeLen && options.scanProj.con.pipeLen != 0) {
      ellipse = {
        semiMinorAxis: new Cesium.CallbackProperty(() => {
          var d = Cesium.Cartesian3.distance(options.position, this.viewer.camera.position) //实体与相机的距离
          return d / 16
        }, false), //长半轴
        semiMajorAxis: new Cesium.CallbackProperty(() => {
          var d = Cesium.Cartesian3.distance(options.position, this.viewer.camera.position)
          return d / 16
        }, false), //短半轴
        //圆形扩散波纹效果
        material: new CircleWaveMaterialProperty({
          duration: 5000, //速度
          gradient: 0.5, //渐变
          color: Cesium.Color.fromCssColorString('#00B4FF').withAlpha(1),
          count: 2 //数量
        })
      }
    }
    let entity = new Cesium.Entity({
      id: options.id,
      position: options.position,
      billboard: {
        image: imgSrc,
        width: 24,
        height: 24,
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        eyeOffset: Cesium.Cartesian3.ZERO,
        disableDepthTestDistance: 9999999
      },
      ellipse
    })
    entity.displayData = options.scanProj
    if (!gCustomDataSource.entities.getById(options.id)) {
      gCustomDataSource.entities.add(entity)
      return true
    } else {
      return false
    }
  }
  /**
   * 获取当前情况
   */
  getCurrentInfo() {
    if (!this.pipeInfo) {
      const pipeInfoConstructor = Vue.extend(pipeInfo)
      this.pipeInfo = new pipeInfoConstructor({
        store: this.$store
      }).$mount()
    }
    this.removeLabels()
    gHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.canvas)
    gHandler.setInputAction(
      function (movement) {
        var pickedObject = this.viewer.scene.pick(movement.endPosition)
        // 使用时，最好利用pickPositionSupported判断一下浏览器是否支持模型高度拾取
        if (this.viewer.scene.pickPositionSupported && Cesium.defined(pickedObject)) {
          let info = pickedObject.id
          if (info && info.displayData) {
            this.pipeInfo.$set(this.pipeInfo, 'displayData', info.displayData)
            this.pipeInfo.$set(this.pipeInfo, 'isShow', true)
            this.pipeInfo.$refs['widget-pipeInfo'].style.setProperty('--left', `${movement.endPosition.x}px`)
            this.pipeInfo.$refs['widget-pipeInfo'].style.setProperty('--top', `${movement.endPosition.y}px`)
          }
        } else {
          this.pipeInfo.$set(this.pipeInfo, 'isShow', false)
        }
      }.bind(this),
      Cesium.ScreenSpaceEventType.MOUSE_MOVE
    )
  }
  /**
   * 显示进度信息
   * @param {string} s_dt 起始日期
   * @param {string} e_dt 终止日期
   */
  showSpeedInfos(s_dt, e_dt) {
    const that = this
    const data = {
      SDate: s_dt,
      EDate: e_dt
    }
    this.clearPrimitives()
    if (!gPrimitiveCollection) {
      gPrimitiveCollection = new Cesium.PrimitiveCollection()
      this.viewer.scene.primitives.add(gPrimitiveCollection)
    } else {
      return
    }
    GetProgress(data)
      .then((result) => {
        if (result.code === 1) {
          if (Object.keys(result.result).length === 0) {
            // this.$message.success('无进度信息')
            return
          }
          that.pbsInfo(result.result)
        } else {
          this.$message.error('查询失败')
        }
      })
      .catch((error) => {
        console.log(error)
      })
  }
  /**
   * 该方法用于生成查询smid条件
   * @param pbscodes
   */
  pbsInfo(pbscodes) {
    const layers = []
    for (let layername in pbscodes) {
      const pbsLayer = layername.split(',')[0]
      const codes = pbscodes[layername]
      layers.push({ name: pbsLayer, codes: codes })
    }
    const fieldname = 'CODE'
    if (layers.length == 0) {
      this.$message.success('无施工进度信息')
      return
    }
    const url = this.apiurls.smiddtfw
    const filterPars = layers.map((item) => {
      const pipeConfig = _.find(gPipe, function (pipe) {
        return pipe.origindataset === item.name
      })
      let str = ''
      item.codes.forEach((item, index) => {
        if (index == 0) {
          str += "'" + item + "'"
        } else {
          str += ",'" + item + "'"
        }
      })
      return new SuperMap.REST.FilterParameter({
        name: pipeConfig.smidmapname,
        attributeFilter: fieldname + ' in (' + str + ')',
        fields: [fieldname]
      })
    })
    const options = {
      url: url,
      filterParameters: filterPars,
      queryOption: SuperMap.REST.QueryOption.ATTRIBUTEANDGEOMETRY,
      completed: this.queryComplete.bind(this),
      failed: function (error) {
        console.error(error)
      }
    }
    queryMapByAttribute(options)
  }
  /**
   * 查询成功
   * @param result
   */
  queryComplete(result) {
    this.flashMapService(result.originResult.recordsets)
  }
  /**
   * 该方法用于添加二维管线高亮
   * @param records
   */
  flashMapService(records) {
    if (!records || records.length === 0) return
    if (!gPrimitiveCollection) return
    const primtCol = gPrimitiveCollection
    this.pointArrCluster = []
    records.forEach((record) => {
      if (record.features.length == 0) return false
      record.features.forEach((feature) => {
        const geometry = feature.geometry.points
        const geotype = feature.geometry.type.toLowerCase().indexOf('line') > -1 ? 'LINE' : 'POINT'
        if (geotype === 'LINE') {
          const pointA = Cesium.Cartesian3.fromDegrees(geometry[0].x, geometry[0].y)
          const pointB = Cesium.Cartesian3.fromDegrees(geometry[1].x, geometry[1].y)
          const pointL = [geometry[0].x, geometry[0].y, geometry[0].z]
          this.pointArrCluster.push(pointL)
          primtCol.add(this.generaGroundPolyline([pointA, pointB]))
        } else {
          const pointA = Cesium.Cartesian3.fromDegrees(geometry[0].x, geometry[0].y, 1000)
          const pointR = [geometry[0].x, geometry[0].y, geometry[0].z]
          this.pointArrCluster.push(pointR)
          primtCol.add(this.generaGroundCircle(pointA, 10))
        }
      })
    })
    this.clustering() //聚合显示
  }
  /**
   * 该方法用于生成贴地线图元
   * @returns groundPolylinePrimitive
   */
  generaGroundPolyline(positions) {
    const instance = new Cesium.GeometryInstance({
      geometry: new Cesium.GroundPolylineGeometry({
        positions: positions,
        width: 20.0
      })
    })
    const polyline = new Cesium.GroundPolylinePrimitive({
      geometryInstances: instance,
      appearance: new Cesium.MaterialAppearance({
        material: Cesium.Material.fromType('Color', {
          color: Cesium.Color.AQUA
        }),
        faceForward: true,
        flat: true
      }),
      classificationType: Cesium.ClassificationType.TERRAIN
    })
    return polyline
  }
  /**
   * 该方法用于生成贴地圆图元
   * @returns groundPolylinePrimitive
   */
  generaGroundCircle(center, radius) {
    const instance = new Cesium.GeometryInstance({
      geometry: new Cesium.EllipseGeometry({
        center: center,
        semiMajorAxis: 10,
        semiMinorAxis: 10,
        height: 100.0
      })
    })
    const circle = new Cesium.GroundPrimitive({
      geometryInstances: instance,
      appearance: new Cesium.MaterialAppearance({
        material: Cesium.Material.fromType('Color', {
          color: Cesium.Color.AQUA
        }),
        faceForward: true,
        flat: true
      }),
      classificationType: Cesium.ClassificationType.TERRAIN
    })
    return circle
  }
  //聚合显示
  clustering() {
    var that = this
    // this.viewer.dataSources.removeAll()
    //聚合参数
    pointDataSource = new Cesium.CustomDataSource('pointData')
    this.pointArrCluster.forEach((item) => {
      var entity = pointDataSource.entities.add({
        position: Cesium.Cartesian3.fromDegrees(item[0], item[1], item[2] + 100),
        billboard: {
          image: that.getDrawCanvas(1, 5),
          width: 50,
          height: 50,
          heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
        }
      })
    })
    var dataSourcePromise = this.viewer.dataSources.add(pointDataSource)
    dataSourcePromise.then(function (dataSource) {
      var pixelRange = 100 //聚合距离，以像素为单位，小于这个距离就会被聚合
      var minimumClusterSize = 2 //每个聚合点的最小聚合个数
      var enabled = true

      dataSource.clustering.enabled = enabled
      dataSource.clustering.pixelRange = pixelRange
      dataSource.clustering.minimumClusterSize = minimumClusterSize

      var removeListener
      function customStyle() {
        if (Cesium.defined(removeListener)) {
          removeListener()
          removeListener = undefined
        } else {
          removeListener = dataSource.clustering.clusterEvent.addEventListener(function (clusteredEntities, cluster) {
            if (!cluster) return
            cluster.label.show = false
            cluster.billboard.show = true
            cluster.billboard.id = cluster.label.id
            cluster.billboard.verticalOrigin = Cesium.VerticalOrigin.BOTTOM

            if (clusteredEntities.length >= 100) {
              cluster.billboard.image = that.getDrawCanvas(clusteredEntities.length, 1)
            } else if (clusteredEntities.length >= 50) {
              cluster.billboard.image = that.getDrawCanvas(clusteredEntities.length, 2)
            } else if (clusteredEntities.length >= 10) {
              cluster.billboard.image = that.getDrawCanvas(clusteredEntities.length, 3)
            } else {
              var singleDigit = new Array(8)
              for (var i = 0; i < singleDigit.length; ++i) {
                singleDigit[i] = that.getDrawCanvas(i + 2, 4)
              }
              cluster.billboard.image = singleDigit[clusteredEntities.length - 2]
            }
          })
        }
        // force a re-cluster with the new styling
        var pixelRange = dataSource.clustering.pixelRange
        dataSource.clustering.pixelRange = 0
        dataSource.clustering.pixelRange = pixelRange
      }
      // start with custom style
      customStyle()
      var handler = new Cesium.ScreenSpaceEventHandler(this.viewer.scene.canvas)
      handler.setInputAction(function (movement) {
        var pickedLabel = that.viewer.scene.pick(movement.position)
        if (Cesium.defined(pickedLabel)) {
          var ids = pickedLabel.id
          if (Array.isArray(ids)) {
            for (var i = 0; i < ids.length; ++i) {
              ids[i].billboard.color = Cesium.Color.RED
            }
          }
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK)
    })
  }
  getDrawCanvas(text, level) {
    var canvas = document.createElement('canvas')
    var ctx = canvas.getContext('2d')
    canvas.height = 100
    canvas.width = 100
    switch (level) {
      case 1:
        ctx.beginPath()
        var grad = ctx.createRadialGradient(50, 50, 0, 50, 50, 50)
        grad.addColorStop(0.8, 'rgba(159,33,200,0.8)')
        grad.addColorStop(1, 'rgba(159,33,200,0.4)')
        ctx.fillStyle = grad
        ctx.arc(50, 50, 50, 0, 2 * Math.PI, true)
        ctx.fill()
        //加入字体
        ctx.font = '30px bold 楷体'
        ctx.fillStyle = 'white'
        ctx.fillText(text, (canvas.width - ctx.measureText(text).width) / 2, canvas.height - 40)
        break
      case 2:
        ctx.beginPath()
        var grad = ctx.createRadialGradient(45, 45, 0, 45, 45, 45)
        grad.addColorStop(0.8, 'rgba(44,72,240,0.8)')
        grad.addColorStop(1, 'rgba(44,72,240,0.4)')
        ctx.fillStyle = grad
        ctx.arc(45, 45, 45, 0, 2 * Math.PI, true)
        ctx.fill()
        //
        ctx.font = '30px bold 楷体'
        ctx.fillStyle = 'white'
        ctx.fillText(text, (canvas.width - ctx.measureText(text).width) / 2.5, canvas.height - 40)
        break
      case 3:
        ctx.beginPath()
        var grad = ctx.createRadialGradient(40, 40, 0, 40, 40, 40)
        grad.addColorStop(0.8, 'rgba(214,116,10,0.8)')
        grad.addColorStop(1, 'rgba(214,116,10,0.4)')
        ctx.fillStyle = grad
        ctx.arc(40, 40, 40, 0, 2 * Math.PI, true)
        ctx.fill()
        //
        ctx.font = '30px bold 楷体'
        ctx.fillStyle = 'white'
        ctx.fillText(text, (canvas.width - ctx.measureText(text).width) / 3, canvas.height - 50)
        break
      case 4:
        ctx.beginPath()
        var grad = ctx.createRadialGradient(30, 30, 0, 30, 30, 30)
        grad.addColorStop(0.8, 'rgba(2,138,63,0.8)')
        grad.addColorStop(1, 'rgba(2,138,63,0.4)')
        ctx.fillStyle = grad
        ctx.arc(30, 30, 30, 0, 2 * Math.PI, true)
        ctx.fill()
        //
        ctx.font = '30px bold 楷体'
        ctx.fillStyle = 'white'
        ctx.fillText(text, (canvas.width - ctx.measureText(text).width) / 4, canvas.height - 60)
        break
      case 5:
        ctx.beginPath()
        var grad = ctx.createRadialGradient(50, 50, 0, 50, 50, 50)
        grad.addColorStop(0.8, 'rgba(2,138,63,0.8)')
        grad.addColorStop(1, 'rgba(2,138,63,0.4)')
        ctx.fillStyle = grad
        ctx.arc(50, 50, 50, 0, 2 * Math.PI, true)
        ctx.fill()
        //
        ctx.font = '50px bold 楷体'
        ctx.fillStyle = 'white'
        ctx.fillText(text, (canvas.width - ctx.measureText(text).width) / 2, canvas.height - 30)
        break
    }
    return canvas
  }
  //清除进度信息
  clearSpeedInfos() {
    this.viewer.scene.layers.releaseSelection()
    this.removeLabels()
    this.clearPrimitives()
    this.clearClusterDataSource()
  }
  removeCurrentInfo() {
    if (this.pipeInfo) {
      this.pipeInfo.remove()
    }
  }
  //该方法用于清除entity label
  removeLabels() {
    if (Cesium.defined(gCustomDataSource)) {
      gCustomDataSource.entities.removeAll()
    }
    if (gHandler != null && !gHandler.isDestroyed()) {
      gHandler.destroy()
    }
  }
  //该方法用于清除primitivecollection
  clearPrimitives() {
    if (gPrimitiveCollection) {
      gPrimitiveCollection.removeAll()
      const isDel = this.viewer.scene.primitives.remove(gPrimitiveCollection)
      if (isDel) gPrimitiveCollection = null
    }
  }
  //清除聚合数据源
  clearClusterDataSource() {
    if (pointDataSource) {
      this.viewer.dataSources.remove(pointDataSource)
      pointDataSource = null
    }
  }
  close() {
    this.$store.state.bigScreen.isShowPipeSpeedInfoCheck = false
    this.clearSpeedInfos()
    this.removeCurrentInfo()
  }
  beforeDestroy() {
    this.close()
  }
}
</script>

<style lang='scss' scoped>
.animate__zoomIn,
.animate__zoomOut {
  animation-duration: 1s; //动画持续时间
  animation-delay: 0s; //动画延迟时间
}
.widget-ProjectPipeSpeedInfoCheck {
  bottom: 0.520833rem /* 100/192 */;
  left: calc(50% - 1.5625rem);
  //   margin-left: -1.5625rem /* 300/192 */;
  width: 3.125rem /* 600/192 */;
  height: 0.833333rem /* 160/192 */;
  position: absolute;
  font-family: Source Han Sans CN;
  z-index: 999;
  //
  background: rgba(0, 60, 98, 0.7);
  border-radius: 4px;
  .header {
    width: 100%;
    height: 0.208333rem /* 40/192 */;
    border-bottom: 1px solid rgba(41, 177, 255, 0.3);
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding-right: 0.15625rem /* 30/192 */;
    .leftBar {
      font-size: 0.072917rem /* 14/192 */;
      font-family: Source Han Sans CN;
      font-weight: 500;
      color: #0ea7ff;
      padding: 0 0.052083rem /* 10/192 */;
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    .rightBar {
      display: flex;
      align-items: center;
      font-size: 0.072917rem /* 14/192 */;
      color: #eee;
    }
    .close {
      position: absolute;
      right: 0.052083rem /* 10/192 */;
      color: #a3d3ff;
      font-size: 0.083333rem /* 16/192 */;
      z-index: 10;
      cursor: pointer;
    }
    .title {
      white-space: nowrap;
      font-family: Source Han Sans CN;
      font-size: 0.072917rem /* 14/192 */;
      color: #2ba7ff;
    }
  }
  /deep/ .el-select {
    // width: 0.520833rem /* 100/192 */;
    width: inherit;
    .el-input__inner {
      background-color: transparent;
      border: none;
      font-size: 0.072917rem /* 14/192 */;
      font-family: Source Han Sans CN;
      font-weight: 500;
      color: #2ba7ff;
      position: relative;
    }
    .el-input .el-select__caret {
      display: flex;
      align-items: center;
    }
    .el-icon-arrow-up:before {
      content: '';
      display: block;
      // 定义元素宽高
      width: 0.130208rem /* 25/192 */;
      height: 0.078125rem /* 15/192 */;
      background: url('~@/views/groupPage/images/三角下.png') no-repeat center center;
      background-size: 100% 100%;
      transform: rotate(180deg);
    }
    .el-select-dropdown {
      min-width: 0.625rem /* 120/192 */ !important /* 90/192 */;
    }
    .el-tree {
      background: #023c5d;
      color: #ffffff;
      .el-tree-node__content {
        background: #023c5d;
      }
      .el-tree-node.is-current > .el-tree-node__content,
      .el-tree-node__content:hover {
        background-color: rgba(43, 167, 255, 0.2) !important;
      }
    }
  }
  /deep/ .el-date-editor {
    background: rgb(9, 48, 84);
    border-color: transparent;
    .el-range-input {
      background-color: transparent !important;
      color: #ffffff;
    }
    .el-range-separator {
      color: #ffffff;
    }
  }
  .content {
    width: 100%;
    height: calc(100% - 0.208333rem /* 40/192 */);
    display: flex;
    .left {
      width: 0.729167rem /* 140/192 */;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      .operationBtn {
        cursor: pointer;
        margin-left: 0.052083rem /* 10/192 */;
        width: 0.255208rem /* 49/192 */;
        height: 0.255208rem /* 49/192 */;
      }
    }
    .right {
      width: calc(100% - 0.729167rem /* 140/192 */);
      height: 100%;
      // padding: 0.052083rem /* 10/192 */;
      margin: 0 0.260417rem /* 50/192 */;
      display: flex;
      align-items: center;
      justify-content: center;
      /deep/ .el-steps {
        width: 100%;
        .el-step__icon-inner {
          color: transparent;
        }
        .el-step__line {
          top: 0.03125rem /* 6/192 */;
          height: 0.020833rem /* 4/192 */;
          background: #0ea7ff;
        }
        .el-step__head.is-success {
          .el-step__icon.is-text {
            width: 0.083333rem /* 16/192 */;
            height: 0.083333rem /* 16/192 */;
            border: 3px solid #04eaff;
            box-shadow: 0 0 5px #04eaff;
          }
        }
        .el-step__title.is-success {
          font-family: Source Han Sans CN;
          font-size: 0.0625rem /* 12/192 */;
          font-weight: 500;
          color: #04eaff;
          padding: 0 0.026042rem /* 5/192 */;
          white-space: nowrap;
        }
        .el-step__head.is-wait .el-step__icon.is-text,
        .el-step__head.is-process .el-step__icon.is-text {
          width: 0.083333rem /* 16/192 */;
          height: 0.083333rem /* 16/192 */;
          border: 3px solid #0ea7ff;
        }
        .el-step__title.is-process,
        .el-step__title.is-wait {
          font-size: 0.0625rem /* 12/192 */;
          font-family: Source Han Sans CN;
          font-weight: 500;
          color: #ffffff;
          padding: 0 0.026042rem /* 5/192 */;
          white-space: nowrap;
        }
      }
      /deep/ .el-slider {
        width: 100%;
        .el-slider__marks-text {
          // white-space: pre-wrap;
          white-space: nowrap;
        }
        .el-slider__button {
          border: 2px solid #04eaff;
          box-shadow: 0 0 2px 2px #04eaff;
        }
        .el-slider__runway {
          background-color: #5e7383;
        }
        .el-slider__stop {
          display: none;
        }
      }
    }
  }
}
</style>