<template>
  <div class="widget-pipespeedinfocheck">
    <!-- <el-input suffix-icon="el-icon-date">
      <template slot="prepend">进度查看:</template>
      <el-button slot="append" icon="el-icon-close" style="color: #47d9d9;font-weight:bold;"></el-button>
    </el-input> -->
    <span style="margin-left: 5px">进度查看:</span>
    <el-date-picker
      :picker-options="pickerOptions"
      @change="dateChange"
      :title="dateValue"
      v-model="dateValue"
      type="datetimerange"
      align="left"
      prefix-icon="none"
      range-separator="-"
      start-placeholder=""
      end-placeholder=""
      value-format="yyyy-MM-dd HH:mm:ss"
      :default-time="['00:00:00', '23:59:59']"
    >
    </el-date-picker>
  </div>
</template>
<script>
import { GetProgress, PipeAndNodeProcess } from '@/api/APIs'
import _ from 'lodash'
import $ from 'jquery'
import billboardimg from './images/back.png'
const currentids = []
let gCustomDataSource = null
let gPrimitiveCollection = null
let excavatename = 'PipeSpeedInfoCheck'
let gPpostUpdate = undefined
let gHandler = null
const gPipe = [
  {
    title: '雨污合流管线',
    name: 'NETWORK_SJ_PSHS@sxgk#1',
    mapname: 'TF_SJ_PSHS_PIPE_B@sxgk',
    datasource: 'sxgk',
    dataset: 'NETWORK_SJ_PSHS',
    smidmapname: 'NETWORK_SJ_PSHS@sxgk',
    geometryType: 'line',
    pipeType: 'PS',
    lineColor: [76, 57, 38],
    origindataset: 'TF_SJ_PSHS_PIPE_B'
  },
  {
    title: '雨污合流管点',
    name: 'NETWORK_SJ_PSHS_Node@sxgk#1',
    mapname: 'TF_SJ_PSHS_NODE_B@sxgk',
    datasource: 'sxgk',
    dataset: 'TF_SJ_PSHS_NODE_B_3D',
    smidmapname: 'TF_SJ_PSHS_JG_B_3D@sxgk',
    smidmapnameNT: 'TF_SJ_PSHS_NODE_B_3D@sxgk',
    tubewelldataset: 'TF_SJ_PSHS_JG_B_3D',
    geometryType: 'point',
    pipeType: 'PS',
    origindataset: 'TF_SJ_PSHS_NODE_B',
    ADJUNCT: [],
    WELL: ['TF_SJ_PSHS_JG_B_3D@sxgk#1', 'TF_SJ_PSHS_JG_B_3D@sxgk#2']
  },
  {
    title: '雨水管线',
    name: 'NETWORK_SJ_PSYS@sxgk#1',
    mapname: 'TF_SJ_PSYS_PIPE_B@sxgk',
    datasource: 'sxgk',
    dataset: 'NETWORK_SJ_PSYS',
    smidmapname: 'NETWORK_SJ_PSYS@sxgk',
    geometryType: 'line',
    pipeType: 'PS',
    lineColor: [76, 57, 38],
    origindataset: 'TF_SJ_PSYS_PIPE_B'
  },
  {
    title: '雨水管点',
    name: 'NETWORK_SJ_PSYS_Node@sxgk#1',
    mapname: 'TF_SJ_PSYS_NODE_B@sxgk',
    datasource: 'sxgk',
    dataset: 'TF_SJ_PSYS_NODE_B_3D',
    smidmapname: 'TF_SJ_PSYS_JG_B_3D@sxgk',
    smidmapnameNT: 'TF_SJ_PSYS_NODE_B_3D@sxgk',
    tubewelldataset: 'TF_SJ_PSYS_JG_B_3D',
    geometryType: 'point',
    pipeType: 'PS',
    origindataset: 'TF_SJ_PSYS_NODE_B',
    ADJUNCT: [],
    WELL: ['TF_SJ_PSYS_JG_B_3D@sxgk#1', 'TF_SJ_PSYS_JG_B_3D@sxgk#2']
  },
  {
    title: '污水管线',
    name: 'NETWORK_SJ_PSWS@sxgk#1',
    mapname: 'TF_SJ_PSWS_PIPE_B@sxgk',
    datasource: 'sxgk',
    dataset: 'NETWORK_SJ_PSWS',
    smidmapname: 'NETWORK_SJ_PSWS@sxgk',
    geometryType: 'line',
    pipeType: 'PS',
    lineColor: [76, 57, 38],
    origindataset: 'TF_SJ_PSWS_PIPE_B'
  },
  {
    title: '污水管点',
    name: 'NETWORK_SJ_PSWS_Node@sxgk#1',
    mapname: 'TF_SJ_PSWS_NODE_B@sxgk',
    datasource: 'sxgk',
    dataset: 'TF_SJ_PSWS_NODE_B_3D',
    tubewelldataset: 'TF_SJ_PSWS_JG_B_3D',
    smidmapname: 'TF_SJ_PSWS_JG_B_3D@sxgk',
    smidmapnameNT: 'TF_SJ_PSWS_NODE_B_3D@sxgk',
    geometryType: 'point',
    pipeType: 'PS',
    origindataset: 'TF_SJ_PSWS_NODE_B',
    ADJUNCT: [],
    WELL: ['TF_SJ_PSWS_JG_B_3D@sxgk#1', 'TF_SJ_PSWS_JG_B_3D@sxgk#2']
  }
]
export default {
  name: 'PipeSpeedInfoCheck',
  props: {
    isInit: false //三维场景是否初始化
  },
  data() {
    return {
      apiurls: {
        sjfw: '',
        smiddtfw: ''
      },
      dateValue: '',
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      }
    }
  },
  watch: {
    isInit() {
      this.viewer = window.viewer
      this.init()
    }
  },
  computed: {
    AppX() {
      return this.$store.getters.AppX
    }
  },
  mounted() {
    this.$store.dispatch('cesiumMap/changeCurrentTool', this.clearSpeedInfos.bind(this))
  },
  methods: {
    init() {
      this.apiurls.sjfw = this.AppX.appConfig.gisResource.tiplayers.config['sjfw'].url
      gCustomDataSource = new Cesium.CustomDataSource('displaycontrol')
      this.viewer.dataSources.add(gCustomDataSource)
      this.apiurls.smiddtfw = this.AppX.appConfig.gisResource.tiplayers.config['bjsmidfw'].url
    },
    dateChange() {
      const dateFormat = 'YYYY-MM-DD HH:mm:ss'
      const dateFormat2 = 'YYYYMMDD HH:mm:ss'
      if (!this.dateValue) {
        this.clearSpeedInfos()
      } else {
        const start = this.dateValue[0]
        const end = this.dateValue[1]
        const data2 = {
          beginDate: start.replaceAll('-', ''),
          endDate: end.replaceAll('-', '')
        }
        this.clearSpeedInfos()
        this.initScanTimes(data2)
        this.showSpeedInfos(start, end)
      }
    },
    /**
     * 显示进度信息
     * @param {string} s_dt 起始日期
     * @param {string} e_dt 终止日期
     */
    showSpeedInfos(s_dt, e_dt) {
      const url = this.apiurls.getProgress
      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) => {
          result = result.data
          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)
        }
      }
      this.queryMapByAttribute(options)
    },
    /**
     * 属性查询（查询地图服务）根据PBS编码查询部件SMID
     * @param options
     */
    queryMapByAttribute(options) {
      let filterParams = options.filterParameters
      const sqlParams = new SuperMap.REST.QueryBySQLParameters({
        queryParams: filterParams,
        queryOption: !options.queryOption ? SuperMap.REST.QueryOption.ATTRIBUTEANDGEOMETRY : options.queryOption
      })
      const sqlService = new SuperMap.REST.QueryBySQLService(options.url, {
        eventListeners: {
          processCompleted: options.completed,
          processFailed: options.failed
        }
      })
      sqlService.processAsync(sqlParams)
    },
    initScanTimes(dateRange) {
      const pipe = gPipe
      const that = this
      const minRadius = 50
      const maxRadius = 200
      const fieldName = 'CODE'
      const url = this.apiurls.pipeAndNodeProcess
      const geourl = this.apiurls.smiddtfw
      const totalField = 'scanCount'
      const id = 'cs'
      const fields = {
        cs: [
          { title: '扫码次数', field: 'scanCount' },
          { title: '施工扫码', field: 'scanCONCount' },
          { title: '监理扫码', field: 'scanSPVCount' },
          { title: '今日扫码', field: 'scanTodayCount' }
        ]
      }
      PipeAndNodeProcess(dateRange)
        .then((result) => {
          result = result.data
          if (result.code !== 1 || result.result.length === 0) return
          console.log(result)
          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
            }
            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) {
            //交互事件
            that.getCurrentInfo()
            geoResult.originResult.recordsets.forEach((record) => {
              const pipeItem = _.find(pipe, function (item) {
                return item.smidmapname === record.datasetName || item.smidmapnameNT === record.datasetName
              })
              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 labelText = dateRange.beginDate + '~' + dateRange.endDate
              let imgSrc = './images/back.png'

              let position = features[0].geometry.points[0]
              position = Cesium.Cartesian3.fromDegrees(position.x, position.y, position.z)
              that.addUnitBillboard({
                id: scanProj.code,
                name: scanProj.code,
                text: labelText,
                position: position,
                scanProj: scanProj,
                imgSrc: imgSrc
              })
            })
          }
          that.queryMapByAttribute({
            url: geourl,
            filterParameters: filters,
            completed: onComplete.bind(this),
            failed: function (err) {
              console.log(err)
            }
          })
        })
        .catch((err) => {
          console.log(err)
        })
    },
    /**
     * 该方法用于生成部件定位指示牌
     * @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)
      options.text =
        options.scanProj.roadName + '（' + options.scanProj.con.pipeLen + 'm,' + options.scanProj.con.part + '个）'
      var color = 'rgb(56, 136, 205)'
      var canvas = document.createElement('canvas')
      const ratio = 2.0
      let height = 50
      const realHeight = 48
      //临时数值
      let width = 100
      canvas.width = width * ratio
      canvas.height = height * ratio
      const fonttxt = '50px Arial'
      var ctx = canvas.getContext('2d')
      //ctx.scale(ratio, ratio)
      var img = new Image()
      img.src = billboardimg
      img.onload = function () {
        ctx.lineWidth = 10
        ctx.strokeStyle = color
        ctx.font = '24px Arial'
        const realWidth = ctx.measureText(options.text).width
        ctx.font = fonttxt
        width = ctx.measureText(options.text).width + 100
        canvas.width = width
        ctx.drawImage(img, 0, 0, canvas.width, canvas.height)
        ctx.font = fonttxt
        ctx.fillStyle = 'rgb(255,255,255)'
        ctx.textBaseline = 'middle'
        ctx.fillText(options.text, 50, height)
        //ctx.fillText(options.text, (canvas.width - width) / 2, (canvas.height + 15) / 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,
            //scale:0.2,
            width: realWidth,
            height: realHeight,
            scaleByDistance: new Cesium.NearFarScalar(10000, 1.0, 10100, 0.5),
            verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
            horizontalOrigin: Cesium.HorizontalOrigin.CENTER
          }
        })
        entity.displayData = options.scanProj
        gCustomDataSource.entities.add(entity)
      }
    },
    /**
     * 获取当前情况
     */
    getCurrentInfo() {
      const smsjhtml =
        "<div class='smtj'>" +
        "<div class='headerTitle'><span class='title'>冷水铺路雨污分流改造工程</span><span class='issg'>(2021.5.21~2021.5.31)</span></div>" +
        "<div class='infoDisplay'>" +
        "<div class='sj infoPar'><p><span class='dwmc'>(设计)</span><span class='sgsmNum'>中国市政华北有线责任公司</span></p><p><span class='tjinfo'>设计长度1223.1KM，管道部件12123个，管点部件12233个</span></p></div>" +
        "<div class='sg infoPar'><p><span class='dwmc'>(施工)</span><span class='sgsmNum'>中国市政华北有线责任公司</span></p><p><span class='tjinfo'>施工50米，扫码2个部件，扫码10次，上传20张图片</span></p></div>" +
        "<div class='jl infoPar'><p><span class='dwmc'>(监理)</span><span class='sgsmNum'>中国市政华北有线责任公司</span></p><p><span class='tjinfo'>监理50米，扫码2个部件，扫码10次，上传20张图片</span></p></div>" +
        '</div>' +
        '</div>'
      let parentDom = $('#mainMapContainer .widget-pipespeedinfocheck-mapInfoLook')
      if (parentDom.length == 0) {
        $('#mainMapContainer').append("<div class='widget-pipespeedinfocheck-mapInfoLook'></div>")
        parentDom = $('#mainMapContainer .widget-pipespeedinfocheck-mapInfoLook')
      }
      // if (this.AppX.runtimeConfig.autoRunAdaptor) {
      //   this.AppX.runtimeConfig.autoRunAdaptor.addOperateEvents(this.excavatename, this.otherDestroy.bind(this), this);
      // }
      this.removeLabels()
      gHandler = new Cesium.ScreenSpaceEventHandler(this.viewer.canvas)
      gHandler.setInputAction(
        function (movement) {
          if (this.infoWindow) {
            this.infoWindow.hide()
          }
          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) {
              let data = info.displayData
              parentDom.attr('style', 'left:' + movement.endPosition.x + 'px;top:' + movement.endPosition.y + 'px;')
              parentDom.addClass('show')
              if (parentDom.hasClass('show') && this.currentEntiy && this.currentEntiy.fristPbs == data.code) {
                return
              }

              let csTitle = data['name']
              let isSG = data['dateRange']
              //施工扫码
              let sgsm = data['con']
              //监理扫码
              let jlsm = data['spv']
              //设计
              let sjinfo = data['design']
              let csHtml = smsjhtml
              parentDom.empty().append(csHtml)
              let smtjDom = parentDom.find('.smtj')
              smtjDom.find('.title').text(csTitle)
              smtjDom.find('.issg').text(isSG)
              //设计
              smtjDom.find('.sj.infoPar .sgsmNum').text(sjinfo.name)
              smtjDom
                .find('.sj.infoPar .tjinfo')
                .text('设计长度' + sjinfo.total + '米，管道部件' + sjinfo.pipe + '个，管点部件' + sjinfo.node + '个')
              //施工
              smtjDom.find('.sg.infoPar .sgsmNum').text(sgsm.name)
              const conPercent = ((parseFloat(sgsm.pipeLen) / parseFloat(sgsm.totalLen)) * 100).toFixed(2)
              const conDesignPercent = ((parseFloat(sgsm.pipeLen) / parseFloat(sjinfo.total)) * 100).toFixed(2)
              smtjDom
                .find('.sg.infoPar .tjinfo')
                .text(
                  '施工' +
                    sgsm.pipeLen +
                    '米，占施工总长度(' +
                    sgsm.totalLen +
                    '米)' +
                    conPercent +
                    '%，占设计总长度' +
                    conDesignPercent +
                    '%，扫码' +
                    sgsm.part +
                    '个部件，扫码' +
                    sgsm.times +
                    '次，上传' +
                    sgsm.pictures +
                    '张图片'
                )
              smtjDom.find('.jl.infoPar .sgsmNum').text(jlsm.name)
              smtjDom
                .find('.jl.infoPar .tjinfo')
                .text(
                  '监理' +
                    jlsm.pipeLen +
                    '米，扫码' +
                    jlsm.part +
                    '个部件，扫码' +
                    jlsm.times +
                    '次，上传' +
                    jlsm.pictures +
                    '张图片'
                )
            } 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
      )
    },
    /**
     * 该方法用于清除entity label
     */
    removeLabels() {
      if (Cesium.defined(gCustomDataSource)) {
        gCustomDataSource.entities.removeAll()
      }
      this.otherDestroy()
    },
    otherDestroy() {
      if (gHandler != null && !gHandler.isDestroyed()) {
        gHandler.destroy()
      }
    },
    /**
     * 查询成功
     * @param result
     */
    queryComplete(result) {
      console.log(result)
      const that = this
      if (result.currentCount === 0) {
        return
      }
      result.originResult.recordsets.forEach((record) => {
        if (record.features.length == 0) return false
        const pipe = _.find(gPipe, function (item) {
          return item.smidmapname === record.datasetName
        })
        const ids = record.features.map((item) => {
          return item.ID
        })
        const s3mNames = pipe.geometryType === 'line' ? [pipe.name] : pipe.WELL
        s3mNames.forEach((item) => {
          const ly = that.viewer.scene.layers.find(item)
          ly.selectedColor = Cesium.Color.YELLOW
          ly.selectEnabled = true
          ly.multiChoose = true
          ly.selectColorType =
            pipe.geometryType === 'line' ? Cesium.SelectColorType.REPLACE : Cesium.SelectColorType.MIX
          ly.setSelection(ids)
          ly.selectEnabled = false
        })
      })
      this.flashMapService(result.originResult.recordsets)
    },
    /**
     * 该方法用于添加二维管线高亮
     * @param records
     */
    flashMapService(records) {
      const that = this
      if (!records || records.length === 0) return
      if (!gPrimitiveCollection) return
      const primtCol = gPrimitiveCollection
      //fade材质
      let t = 0.0
      const linefadeMaterial = Cesium.Material.fromType(Cesium.Material.FadeType, {
        repeat: true,
        fadeInColor: Cesium.Color.ORANGE,
        fadeOutColor: Cesium.Color.ORANGE.withAlpha(0.0),
        time: new Cesium.Cartesian2(0.0, 0.0),
        fadeDirection: {
          x: true,
          y: false
        }
      })
      //圆
      const EllipsoidFadeSource =
        'czm_material czm_getMaterial(czm_materialInput materialInput)\n' +
        '{\n' +
        '  czm_material material = czm_getDefaultMaterial(materialInput);\n' +
        '  material.diffuse = 1.5 * color.rgb;\n' +
        '  vec2 st = materialInput.st;\n' +
        '  float dis = distance(st, vec2(0.5, 0.5));\n' +
        '  float per = fract(time);\n' +
        '  if(dis > per * 0.5) {\n' +
        '    material.alpha = 0.0;\n' +
        '    discard;\n' +
        '  }else{\n' +
        '    material.alpha = color.a * dis / per / 1.0;\n' +
        '  }\n' +
        '  return material;\n' +
        '}'
      const circlefadeMaterial = new Cesium.Material({
        fabric: {
          type: 'fadeCircle',
          uniforms: {
            color: Cesium.Color.ORANGE,
            time: 0.0
          },
          source: EllipsoidFadeSource
        }
      })

      //let polylines = this.viewer.scene.groundPrimitives.add(primtCol);
      //let pointPrim = primtCol.add(new Cesium.PointPrimitiveCollection());
      records.forEach((record) => {
        if (record.features.length == 0) return false
        const pipe = _.find(gPipe, function (item) {
          return item.smidmapname === record.datasetName
        })
        const ids = record.features.map((item) => {
          return item.ID
        })
        const s3mNames = pipe.geometryType === 'line' ? [pipe.name] : pipe.WELL

        record.features.forEach((feature) => {
          const geometry = feature.geometry.points
          const geotype = feature.geometry.type.toLowerCase().indexOf('line') > -1 ? 'LINE' : 'POINT'
          let entity
          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)
            primtCol.add(that.generaGroundPolyline([pointA, pointB], linefadeMaterial))
          } else {
            const pointA = Cesium.Cartesian3.fromDegrees(geometry[0].x, geometry[0].y, 1000)
            primtCol.add(this.generaGroundCircle(pointA, 10, circlefadeMaterial))
            // pointPrim.add({
            //     position: pointA,
            //     pixelSize: 5,
            //     color: Cesium.Color.PINK
            // })
          }
        })
      })
      // var render = function () {
      //     t += 0.01;
      //     if (t >= 1.0) {
      //         t = 0.0;
      //     }
      //     linefadeMaterial.uniforms.time.x = t;
      //     circlefadeMaterial.uniforms.time=t;
      //     requestAnimationFrame(render);
      // }
      // requestAnimationFrame(render);
      if (gPpostUpdate) {
        gPpostUpdate()
        gPpostUpdate = undefined
      }
      gPpostUpdate = this.viewer.scene.postUpdate.addEventListener((e) => {
        t += 0.02
        if (t >= 1.0) {
          t = 0.0
        }
        linefadeMaterial.uniforms.time.x = t
        circlefadeMaterial.uniforms.time = t
      })
    },
    /**
     * 该方法用于生成贴地线图元
     * @returns groundPolylinePrimitive
     */
    generaGroundPolyline(positions, material) {
      const instance = new Cesium.GeometryInstance({
        geometry: new Cesium.GroundPolylineGeometry({
          positions: positions,
          width: 20.0
        }),
        attributes: {
          color: Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.BLUE)
        }
      })
      const polyline = new Cesium.GroundPolylinePrimitive({
        geometryInstances: instance,
        appearance: new Cesium.MaterialAppearance({
          material: material,
          faceForward: true,
          flat: true
        }),
        classificationType: Cesium.ClassificationType.TERRAIN
      })
      return polyline
    },
    /**
     * 该方法用于生成贴地圆图元
     * @returns groundPolylinePrimitive
     */
    generaGroundCircle(center, radius, material) {
      const instance = new Cesium.GeometryInstance({
        geometry: new Cesium.EllipseGeometry({
          center: center,
          semiMajorAxis: 10,
          semiMinorAxis: 10,
          height: 100.0
        }),
        attributes: {
          color: new Cesium.ColorGeometryInstanceAttribute(0.0, 1.0, 1.0, 1.0)
        }
      })
      const circle = new Cesium.GroundPrimitive({
        geometryInstances: instance,
        appearance: new Cesium.MaterialAppearance({
          material: material,
          faceForward: true,
          flat: true
        }),
        classificationType: Cesium.ClassificationType.TERRAIN
      })
      return circle
    },
    /**
     * 该方法用于清除primitivecollection
     */
    clearPrimitives() {
      if (gPrimitiveCollection) {
        gPrimitiveCollection.removeAll()
        const isDel = this.viewer.scene.primitives.remove(gPrimitiveCollection)
        if (isDel) gPrimitiveCollection = null
      }
    },
    /**
     * 清除进度信息
     */
    clearSpeedInfos() {
      this.viewer.scene.layers.releaseSelection()
      this.removeLabels()
      this.clearPrimitives()
      if (gPpostUpdate) {
        gPpostUpdate()
        gPpostUpdate = undefined
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.widget-pipespeedinfocheck {
  position: absolute;
  top: 13px;
  // left: 30.5%;
  left: 315px;
  height: 36px;
  background: white;
  $fontsize: 0.875rem;
  box-shadow: 0px 1px 8px 0px rgba(0, 0, 0, 0.4);
  border-radius: 4px;
  font-size: $fontsize;
  color: #666666;
  ::v-deep .el-input__inner {
    width: 125px;
    height: 36px;
    padding: 0;
    border: none;
    color: #006ed4;
  }
  ::v-deep .el-input {
    .el-input-group__append,
    .el-input-group__prepend {
      font-size: 0.875rem;
      color: #666666;
      padding: 0.275rem 0.45rem;
      background-color: #fff;
      border: none;
      font-family: Source Han Sans CN;
    }
  }
}
</style>
<style lang="scss">
.widget-pipespeedinfocheck-mapInfoLook.show {
  display: block !important;
}
.widget-pipespeedinfocheck-mapInfoLook {
  display: none;
  width: 600px;
  height: auto;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 5px;
  color: white;
  position: absolute;
  right: 300px;
  top: 20px;
  padding: 10px;
  .smtj {
    .title {
      color: #03f9f9;
      font-weight: bold;
      font-size: 1.3rem;
      width: 100%;
      display: block;
      white-space: nowrap;
      overflow: hidden;
      text-align: center;
      text-overflow: ellipsis;
    }

    .issg {
      display: block;
      font-size: 1.3rem;
      font-weight: bold;
      padding: 3px;
      color: #03f9f9;
      border-radius: 3px;
      text-align: center;
    }

    .issg.sg {
      background: rgb(8, 154, 0);
      color: white;
      width: 60px;
      left: calc((100% - 60px) / 2);
    }
    .infoDisplay {
      .infoPar {
        margin-bottom: 10px;
        p {
          margin-bottom: 0.24rem;
          font-size: 1.2rem;
          font-weight: bold;
        }
        .sgsmNum {
          display: inline-block;
          text-indent: 0.4rem;
        }
        .tjinfo {
          display: block;
          text-indent: 4rem;
          color: yellow;
        }
      }
    }
  }
}
</style>