<template>
  <div class="widget-infosearch">
    <el-input
      class="search-Input"
      :placeholder="placeholder"
      v-model="searchInput"
      clearable
      @keyup.enter.native="onInputKeyPress()"
      @clear="clearInput"
    >
      <el-select v-model="selectType" slot="prepend" style="width: 70px">
        <el-option label="工程" value="4"></el-option>
        <el-option label="地址" value="0"></el-option>
        <el-option label="坐标" value="1"></el-option>
        <el-option label="部件码" value="2"></el-option>
        <el-option label="PBS编码" value="3"></el-option>
      </el-select>
      <el-button type="primary" slot="append" icon="el-icon-search" @click="onSearchClick()"> </el-button>
    </el-input>
    <div class="treeContainer" v-show="selectType == '4'">
      <commonTree @changeProjectName="changeProjectName($event)" @onInputKeyPress="onInputKeyPress()" />
    </div>
    <div class="resultContainer" v-show="options.length > 0">
      <div id="widget-infosearch-wrap-scroll" class="wrap-scroll">
        <ul>
          <li class="infoitem" v-for="(item, index) of options" :key="index">
            <div class="content">
              <a @click="onOptionClick(item)"
                ><i :style="iconImage">{{ item.text }}</i
                ><em></em
              ></a>
            </div>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>
<script>
import $ from 'jquery'
import axios from 'axios'
import Vue from 'vue'
import Config from './config.json'
import { pbsTreeSearch_api, mapSearch_api, getPidByPbs_api } from '@/api/APIs'
// import xss from '@/utils/xss'
import commonTree from '@/components/PbsTreeList/commonTree.vue'
import PipeUnitInfo from '@/views/widgets/PipeUnitInfo/index.vue'
export default {
  name: 'InfoSearch',
  components: {
    commonTree
  },
  props: {
    isInit: null
  },
  data() {
    return {
      loading: null,
      backImg: require('@/views/widgets/InfoSearch/images/back.png'),
      iconImage:
        'background:url(' +
        require('@/views/widgets/InfoSearch/images/suggestion-icon.png') +
        ') no-repeat 12px -12px;',
      config: Config,
      selectType: '4',
      searchInput: '',
      apiurl: {
        sjfw: '',
        dtfw: '',
        smiddtfw: '',
        pipeAndNodeProcess: '/tofly-sxgk/newPipeAndNodeScan/mapSearch'
      },
      placeholder: '',
      //工程树变量
      treeValue: {},
      datas: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      //
      options: [],
      coloredPipe: [],
      dicInfos: null,
      pointLabel: null,
      handler: null,
      pickSend: null
    }
  },
  computed: {
    AppX: function () {
      return this.$store.getters.AppX
    },
    prjId() {
      return this.$store.getters['project/id'].projectId
    }
  },
  methods: {
    init() {
      this.apiurl.sjfw = this.AppX.appConfig.gisResource.tiplayers.config['sjfw'].url
      this.apiurl.dtfw = this.AppX.appConfig.gisResource.maps.config['sjdt'].url
      this.apiurl.smiddtfw = this.AppX.appConfig.gisResource.tiplayers.config['bjsmidfw'].url
    },
    //搜索查询
    onSearchClick() {
      const searchType = this.selectType
      const inputObj = this.searchInput
      //   if (xss.isXSS(inputObj)) {
      if (!inputObj) {
        this.$message.warning('非法输入!')
        return
      }
      switch (searchType) {
        case '0':
          this.queryOptionsByPOI()
          break
        case '1':
          this.searchLonLat()
          break
        case '2':
          this.searchPbsAndPipeID(searchType, inputObj)
          break
        case '3':
          this.searchPbsAndPipeID(searchType, inputObj)
          break
        case '4':
          this.searchPrjSpeedInfo(inputObj)
          break
      }
    },
    //地址查询
    queryOptionsByPOI() {
      var filterValue = this.searchInput
      if (filterValue === undefined || filterValue.trim().length == 0) {
        this.clearOptions()
        return
      }
      const url = this.AppX.appConfig.gisResource.tiplayers.config['sjfw'].url
      this.removeAllEntities(null)
      const fieldName = this.config.address.fieldName
      var whereSql = fieldName + " LIKE '%" + filterValue + "%'"
      var getFeatureParam, getFeatureBySQLService, getFeatureBySQLParams
      getFeatureParam = new SuperMap.REST.FilterParameter({
        attributeFilter: whereSql,
        orderBy: fieldName
      })
      getFeatureBySQLParams = new SuperMap.REST.GetFeaturesBySQLParameters({
        queryParameter: getFeatureParam,
        toIndex: -1,
        datasetNames: this.config.address.datasetNames
      })
      getFeatureBySQLService = new SuperMap.REST.GetFeaturesBySQLService(url, {
        eventListeners: {
          processCompleted: this.onQueryComplete.bind(this),
          processFailed: this.processFailed.bind(this)
        }
      })
      getFeatureBySQLService.processAsync(getFeatureBySQLParams)
    },
    //地址查询完成
    onQueryComplete(queryEventArgs) {
      this.dicInfos = new Object()
      var selectedFeatures = queryEventArgs.originResult.features
      var infos = []
      const that = this
      if (selectedFeatures && selectedFeatures.length > 0) {
        var fieldIndex = -1
        this.queryForDemHeight(
          selectedFeatures,
          function (features) {
            features.forEach(
              function (item, index) {
                var geo = item.geometry
                var id = item.ID
                if (index == 0) {
                  for (var j = 0; j < item.fieldNames.length; j++) {
                    if (item.fieldNames[j] == this.config.address.fieldName) {
                      fieldIndex = j
                      break
                    }
                  }
                }
                let x = geo.center.x
                let y = geo.center.y
                let h = geo.center.z
                var info = {
                  id: id,
                  text: item.fieldValues[fieldIndex],
                  value: item.fieldValues[fieldIndex],
                  entityInfo: {
                    x: x,
                    y: y,
                    h: h,
                    name: item.fieldValues[fieldIndex]
                  },
                  entity: null
                }
                const isExsit = that.$_.find(infos, (uniqueInfo) => {
                  return uniqueInfo.text === item.fieldValues[fieldIndex]
                })
                if (!isExsit) {
                  infos.push(info)
                }
                this.dicInfos[id] = info
              }.bind(this)
            )
            this.showOptions(infos)
          }.bind(this)
        )
      } else {
        this.$message('无结果信息！')
      }
    },
    /**
     * 该方法用于获取DEM高度
     * @param selectedFeatures
     * @param callback 回调函数
     */
    queryForDemHeight(selectedFeatures, callback) {
      const points = selectedFeatures.map(function (feature) {
        const geo = feature.geometry.center
        return { type: 'POINT3D', x: geo.x, y: geo.y, z: 0 }
      })
      const that = this
      const url = this.AppX.appConfig.gisResource.geometry.config['demgdfw'].url
      var queryObj = {
        geometries: points,
        sceneName: that.config.dem.sceneName,
        layerName: that.config.dem.layerName,
        interpolationDistance: 0
      }
      const queryObjJSON = JSON.stringify(queryObj)
      axios({
        url: url,
        method: 'post',
        data: queryObjJSON
      })
        .then((res) => {
          const data = res
          selectedFeatures.forEach((item, index) => {
            item.geometry.center = {
              x: data.geometries[index].x,
              y: data.geometries[index].y,
              z: data.geometries[index].z
            }
          })
          callback(selectedFeatures)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    //查询失败
    processFailed(queryEventArgs) {
      this.$message.error('查询失败！')
    },
    //该方法用于定位经纬度地址
    searchLonLat() {
      const that = this
      const inputObj = this.searchInput
      const split = inputObj.split(',')
      if (inputObj === undefined || inputObj.trim().length == 0) {
        this.clearOptions()
        return
      }
      if (isNaN(parseFloat(split[0])) || isNaN(parseFloat(split[1]))) {
        this.$message('请检查经纬度输入是否正确')
        return
      }
      const lon = parseFloat(split[0])
      const lat = parseFloat(split[1])
      this.queryForLonLatHeight(
        { lon: lon, lat: lat },
        function (point) {
          const lonlat = new Cesium.Cartographic(
            Cesium.Math.toRadians(point.x),
            Cesium.Math.toRadians(point.y),
            point.z
          )
          var temp_position = []
          temp_position.push(Cesium.Cartesian3.fromRadians(lonlat.longitude, lonlat.latitude, lonlat.height))
          temp_position.push(Cesium.Cartesian3.fromRadians(lonlat.longitude, lonlat.latitude, lonlat.height + 5))
          var entity = new Cesium.Entity({
            position: Cesium.Cartesian3.fromRadians(lonlat.longitude, lonlat.latitude, lonlat.height + 5),
            label: {
              text: lon + ',' + lat,
              font: 'bold 16pt fangsong',
              fillColor: Cesium.Color.WHITE,
              style: Cesium.LabelStyle.FILL,
              scale: 1,
              outlineWidth: 2,
              showBackground: true,
              backgroundColor: Cesium.Color.BLACK,
              horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
              verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
              pixelOffset: new Cesium.Cartesian2(15, -20),
              scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 2000, 0.5)
            },
            billboard: {
              image: require('@/views/widgets/InfoSearch/images/location.png'),
              width: 32,
              height: 32,
              scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 2000, 0.5)
            },
            polyline: {
              positions: temp_position,
              show: true,
              material: Cesium.Color.ALICEBLUE,
              width: 2.0
            }
          })
          that.viewer.entities.add(entity)
          this.pointLabel = entity
          this.viewer.flyTo(entity, {
            offset: {
              heading: Cesium.Math.toRadians(0.0),
              pitch: Cesium.Math.toRadians(-45),
              range: 100
            }
          })
        }.bind(this)
      )
    },
    /**
     * 该功能用于获取经纬度坐标对应的dem高度
     * @param lonlat 经纬度
     * @param callback 回调函数
     */
    queryForLonLatHeight(lonlat, callback) {
      const points = [{ type: 'POINT3D', x: lonlat.lon, y: lonlat.lat, z: 0 }]
      const that = this
      const url = this.AppX.appConfig.gisResource.geometry.config['demgdfw'].url
      var queryObj = {
        geometries: points,
        sceneName: that.config.dem.sceneName,
        layerName: that.config.dem.layerName,
        interpolationDistance: 0
      }
      const queryObjJSON = JSON.stringify(queryObj)
      axios({
        url: url,
        method: 'post',
        data: queryObjJSON
      })
        .then((res) => {
          const data = res
          if (!data.succeed) {
            that.$message.error('查询地形高度失败')
            return
          }
          let point = { x: lonlat.lon, y: lonlat.lat, z: 0 }
          if (data.geometries.length === 1) {
            //标识超出地形范围，高程为0
            point.z = data.geometries[0].z
          }
          callback(point)
        })
        .catch((err) => {
          console.log(err)
        })
    },
    /**
     * 模糊查询psb编码或者部件ID查询
     */
    searchPbsAndPipeID(searchType, code) {
      if (!code) return
      this.dicInfos = new Object()
      const that = this
      const size = 50
      const infos = []
      const valueFiled = searchType === '2' ? 'pipeId' : 'code'
      pbsTreeSearch_api({ prjId: this.prjId, pbs: code, pageSize: size }).then((res) => {
        const result = res
        if (result.code === 1 && result.result) {
          if (result.result.length >= size) {
            that.$message('查询结果过多！当前显示匹配的50条记录')
          }
          const nodes = result.result.forEach((item, index) => {
            var info = {
              id: item.code,
              text: item.childUnitProjectName + ',' + item[valueFiled],
              value: item.layerName,
              structure: item.childUnitProjectName
            }
            infos.push(info)
            this.dicInfos[info.id] = info
          })
          this.showOptions(infos)
        }
      })
    },
    //显示结果
    showOptions(result) {
      if (result && result.length > 0) {
        this.options = result
      } else {
        this.$message('未搜索到相关数据！')
      }
    },
    //结果定位
    onOptionClick(item) {
      let selectedValue = item.value
      let id = item.id
      this.options = []
      let typeID = this.selectType
      if (typeID === '0') {
        this.optionClickPOI(id, selectedValue)
        const text = item.text
        this.searchInput = text
      } else {
        this.optionClickUnit(id, selectedValue)
        const text = item.text.split(',')[1]
        this.searchInput = text
      }
    },
    /**
     * 该方法用于pbs、部件id查询结果展示
     * @param id pbs
     * @param selectedValue layername
     */
    optionClickUnit(id, selectedValue) {
      const layer = selectedValue.split(',')[1]
      const pipeInfoConstructor = Vue.extend(PipeUnitInfo)
      const pipeInfo = new pipeInfoConstructor({
        data: {
          pickType: 'point',
          isInteractive: false,
          locateUnit: {
            name: layer,
            id: id
          }
        },
        store: this.$store
      }).$mount()
    },
    /**
     * 该方法用于地址查询结果展示
     * @param id
     * @param selectedValue
     */
    optionClickPOI(id, selectedValue) {
      var entityInfo = this.dicInfos[id].entityInfo
      var temp_position = []
      temp_position.push(Cesium.Cartesian3.fromDegrees(entityInfo.x, entityInfo.y, entityInfo.h))
      temp_position.push(Cesium.Cartesian3.fromDegrees(entityInfo.x, entityInfo.y, entityInfo.h + 5))
      var enti = new Cesium.Entity({
        position: Cesium.Cartesian3.fromDegrees(entityInfo.x, entityInfo.y, entityInfo.h + 5),
        label: {
          text: entityInfo.name,
          font: 'bold 16pt fangsong',
          fillColor: Cesium.Color.WHITE,
          style: Cesium.LabelStyle.FILL,
          scale: 1,
          outlineWidth: 2,
          showBackground: true,
          backgroundColor: Cesium.Color.BLACK,
          horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          pixelOffset: new Cesium.Cartesian2(15, -20),
          scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 2000, 0.5)
        },
        billboard: {
          image: require('@/views/widgets/InfoSearch/images/location.png'),
          width: 30,
          height: 40,
          scaleByDistance: new Cesium.NearFarScalar(1000, 1.0, 2000, 0.5)
        },
        polyline: {
          positions: temp_position,
          show: true,
          material: Cesium.Color.ALICEBLUE,
          width: 2.0
        },
        name: entityInfo.name
      })
      this.viewer.entities.add(enti)
      this.removeAllEntities()
      this.pointLabel = enti
      if (enti) {
        this.viewer
          .flyTo(enti, {
            offset: {
              heading: Cesium.Math.toRadians(0.0),
              pitch: Cesium.Math.toRadians(-45),
              range: 100
            }
          })
          .then(
            function () {
              // if ($(event.target).parent()[0].className === "start stop") {
              //     this.openPathAnalysis(selectedValue, enti.position, 'start');
              //     this.removeAllEntities();
              // } else if ($(event.target).parent()[0].className === "end stop") {
              //     this.openPathAnalysis(selectedValue, enti.position, 'end');
              //     this.removeAllEntities();
              // }
            }.bind(this)
          )
        this.viewer.selectedEntity = enti
      }
    },
    /**
     * 该方法用于查询工程进度
     * @param prjName 工程(包括工程项目、单项工程、单位工程、子单位工程)
     * @returns
     */
    searchPrjSpeedInfo(prjName) {
      if (!prjName) {
        this.removeLabels()
        this.clearSelection()
        return
      }
      this.loading = this.$loading({
        lock: true,
        text: '正在搜索中，请耐心等待...',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)',
        customClass: 'loadingclass'
      })
      const data = { queryText: prjName } //查询条件
      const pipe = this.config.pipe
      const that = this
      const fieldName = 'CODE'
      const geourl = this.apiurl.smiddtfw
      mapSearch_api(data).then((res) => {
        const result = res
        if (result.code !== 1) return
        if (result.result.length === 0) {
          this.$message('未搜索到相关工程')
          this.loading.close()
          return
        }
        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 = this.$_.find(pipe, function (pipeItem) {
            return pipeItem.origindataset === pipename
          })
          if (!layer) {
            continue
          }
          //组装
          let cwpInfo = {
            name: '',
            roadName: '',
            code: '',
            percent: '',
            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
            }
          }
          cwpInfo.percent = !item.percent ? 0 : item.percent
          cwpInfo.code = item.firstPbs
          cwpInfo.name = item.zdwName
          cwpInfo.roadName = item.roadName
          //设计
          const design = this.$_.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 = this.$_.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
          }
          //监理
          const spv = this.$_.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.loading.close()
          //交互事件
          that.getCurrentInfo()
          that.clickHightLight()
          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 = that.$_.find(cwpInfos, function (scanItem) {
              return scanItem.code === features[0]['fieldValues'][0]
            })

            let labelText = ''
            let imgSrc = that.backImg

            let position = features[0].geometry.points[0]
            position = Cesium.Cartesian3.fromDegrees(position.x, position.y, position.z)
            //缩放定位，默认第一个
            const camera = that.viewer.camera
            const location = Cesium.Cartographic.fromDegrees(
              features[0].geometry.points[0].x,
              features[0].geometry.points[0].y,
              features[0].geometry.points[0].z + 5000
            )
            const cartesian3 = Cesium.Cartographic.toCartesian(location)
            camera.flyTo({
              destination: cartesian3,
              orientation: {
                heading: camera.heading,
                pitch: Cesium.Math.toRadians(-90),
                roll: 0
              }
            })
            scanProj.displayType = 'gcss'
            that.addUnitBillboard({
              id: scanProj.code,
              name: scanProj.code,
              text: labelText,
              position: position,
              scanProj: scanProj,
              imgSrc: imgSrc
            })
          })
        }
        that.queryUnitMapByAttribute({
          url: geourl,
          filterParameters: filters,
          completed: onComplete.bind(this),
          failed: function (err) {
            that.loading.close()
            that.$message.error('查询失败')
            console.log(err)
          }
        })
      })
    },
    /**
     * 属性查询（查询地图服务）根据PBS编码查询部件SMID
     * @param options
     */
    queryUnitMapByAttribute(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)
    },
    /**
     * 该方法用于生成部件定位指示牌
     * @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)
      const percent = isNaN(options.scanProj.percent) ? 0 : parseFloat(options.scanProj.percent)
      options.text = options.scanProj.roadName + '（' + percent + '%）'
      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 = options.imgSrc
      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.fillStyle = 'rgba(0,0,0,0.7)'
        ctx.fillRect(0, 0, canvas.width, canvas.height)
        if (percent !== 0) {
          ctx.drawImage(img, 0, 0, canvas.width * (percent / 100), 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.toDataURL(),
            //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.displayType = options.scanProj.displayType
        entity.displayData = options.scanProj
        that._customDataSource.entities.add(entity)
      }
    },
    /**
     * 获取当前情况
     */
    getCurrentInfo() {
      this.removeLabels()
      this.clearSelection()
      let parentDom = $('#mainMapContainer .widget-infosearch-mapInfoLook')
      if (parentDom.length == 0) {
        let html = "<div class='widget-infosearch-mapInfoLook'></div>"
        $('#mainMapContainer').append(html)
        parentDom = $('#mainMapContainer .widget-infosearch-mapInfoLook')
      }
      this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.canvas)
      this.handler.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) {
              try {
                parentDom.attr('style', 'left:' + movement.endPosition.x + 'px;top:' + movement.endPosition.y + 'px;')
                parentDom.addClass('show')
                this.fillContent(parentDom, info.displayData)
              } catch {}
            }
          } else {
            if (parentDom.hasClass('show')) {
              parentDom.removeClass('show')
              // this.currentEntiy = null;
            }
          }
        }.bind(this),
        Cesium.ScreenSpaceEventType.MOUSE_MOVE
      )
    },
    //内容填充
    fillContent(parentDom, data) {
      let csTitle = data['name']
      let isSG = data['dateRange']
      //施工扫码
      let sgsm = data['con']
      //监理扫码
      let jlsm = data['spv']
      //设计
      let sjinfo = data['design']
      let csHtmlArr = []
      csHtmlArr.push("<div class='smtj'>")
      csHtmlArr.push("<div class='headerTitle'>")
      csHtmlArr.push("<span class='smtj-title'></span>")
      csHtmlArr.push("<span class='issg'></span></div>")
      csHtmlArr.push("<div class='infoDisplay'>")
      csHtmlArr.push("<div class='sj infoPar'>")
      csHtmlArr.push("<p class='smtj-p'><span class='dwmc'>(设计)</span><span class='sgsmNum'></span></p>")
      csHtmlArr.push("<p class='smtj-p'><span class='tjinfo'></span></p></div>")
      csHtmlArr.push("<div class='sg infoPar'>")
      csHtmlArr.push("<p class='smtj-p'><span class='dwmc'>(施工)</span><span class='sgsmNum'></span></p>")
      csHtmlArr.push("<p class='smtj-p'><span class='tjinfo'></span></p></div>")
      csHtmlArr.push("<div class='jl infoPar'>")
      csHtmlArr.push("<p class='smtj-p'><span class='dwmc'>(监理)</span><span class='sgsmNum'></span></p>")
      csHtmlArr.push("<p class='smtj-p'><span class='tjinfo'></span></p></div>")
      csHtmlArr.push('</div></div>')
      let csHtml = csHtmlArr.join('')
      parentDom.empty().append(csHtml)
      let smtjDom = parentDom.find('.smtj')
      smtjDom.find('.smtj-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)
      smtjDom
        .find('.sg.infoPar .tjinfo')
        .text(
          '施工' +
            sgsm.pipeLen +
            '米，扫码' +
            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 +
            '张图片'
        )
    },
    //单击高亮显示部件
    clickHightLight() {
      var that = this
      this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.canvas)
      //点击高亮工程下所有部件
      this.handler.setInputAction(
        function (movement) {
          var pickedObject = this.viewer.scene.pick(movement.position)
          // 使用时，最好利用pickPositionSupported判断一下浏览器是否支持模型高度拾取
          if (this.viewer.scene.pickPositionSupported && Cesium.defined(pickedObject)) {
            if (!pickedObject) return
            if (pickedObject && pickedObject.id && pickedObject.id.displayType === 'gcss') {
              that.clickBillboardHightLight(pickedObject) //点击进度框高亮所有部件
            }
            if (pickedObject) {
              that.removeHightLight(that.pickSend)
              that.showSelect(pickedObject)
            }
          } else {
            return
          }
        }.bind(this),
        Cesium.ScreenSpaceEventType.LEFT_CLICK
      )
      this.handler.setInputAction(function (movement) {
        if (that.display === 1) {
          that.removeHightLight(that.pickSend)
        } else {
          that.clearSelection()
        }
      }, Cesium.ScreenSpaceEventType.RIGHT_CLICK)
    },
    //点击进度框高亮所有部件
    clickBillboardHightLight(pickedObject) {
      let info = pickedObject.id
      var that = this
      const pbsname = info.displayData.code.split('.')[0] + '.' + info.displayData.code.split('.')[1]
      pbsTreeSearch_api({ prjId: this.prjId, pbs: pbsname, pageSize: 9999 }).then((res) => {
        const result = res
        if (result.code !== 1) return
        const pipe = that.config.pipe
        const fieldName = 'CODE'
        const geourl = that.apiurl.smiddtfw
        const filters = []
        const data = result.result
        for (let i = 0; i < data.length; i++) {
          const pipename = data[i].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 + " = '" + data[i].code + "'",
            fields: [fieldName]
          })
          filters.push(JGFilter)
        } //循环结束
        //成功回调函数
        const queryComplete = function (geoResult) {
          if (geoResult.originResult.recordsets.length < 1) return
          geoResult.originResult.recordsets.forEach((item) => {
            if (item.features[0]) {
              const pbsid = item.features[0].fieldValues[0]
              const geometry = item.features[0].geometry
              that.hightLight(geometry, pbsid) //高亮
            }
          })
          this.display = 0
        }
        //属性查找
        that.queryUnitMapByAttribute({
          url: geourl,
          filterParameters: filters,
          completed: queryComplete.bind(this),
          failed: function (err) {
            console.log(err)
          }
        })
      })
    },
    /**
     * 结果二维高亮
     * @param result
     * @returns
     */
    hightLight(result, pbsid) {
      if (!this._pointPrimitiveCollection) {
        this._pointPrimitiveCollection = new Cesium.PointPrimitiveCollection()
        this.viewer.scene.primitives.add(this._pointPrimitiveCollection) //添加点容器
      }
      if (!this._polylineprimitiveCollection) {
        this._polylineprimitiveCollection = new Cesium.PrimitiveCollection()
        this.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
        })
        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
        })
        return polyline
      }
    },
    /**
     * @param pick 屏幕点击获取到的对象
     */
    showSelect(pick) {
      if (pick && pick.id) {
        if (pick.id.displayType === 'gcss') return
        this.pickSend = pick
        this.pickHightLight(pick)
        this.locateUnit(pick.id)
      }
    },
    /**
     * 该方法用于根据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) {
      var attributes = pick.primitive.getGeometryInstanceAttributes(pick.id) //获取某个实例的属性集
      attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromBytes(255, 125, 0)) //设置其高亮
      this.display = 1
    },
    /**
     * 清除对象高亮
     * @param pick
     * @param index
     */
    removeHightLight(pick) {
      if (pick === null) return
      if (pick && pick.id && pick.id.displayType === 'gcss') {
        return
      } else {
        var attributes = pick.primitive.getGeometryInstanceAttributes(pick.id) //获取某个实例的属性集
        attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(Cesium.Color.fromBytes(0, 255, 255, 50)) //设置其初始颜色
        this.display = 0
      }
    },
    //回车事件
    onInputKeyPress() {
      this.clearOptions()
      this.onSearchClick(null)
    },
    changeProjectName(data) {
      if (data != '') {
        const { name, code } = data
        this.searchInput = name
        this.onSearchClick()
      } else {
        this.clearInput()
      }
    },
    //<------------------------------------清除方法----------------------------------------------//
    //清除查询结果
    clearOptions() {
      this.options = []
      this.removeAllEntities(null)
      this.dicInfos = null
      this.viewer.selectedEntity = null
      //清除颜色
      if (this.coloredPipe.length > 0) {
        this.coloredPipe.forEach((item) => {
          item.layer.removeObjsColor([item.fid])
        })
        this.coloredPipe = []
      }
    },
    //移除实体对象
    removeAllEntities(id) {
      if (this.pointLabel) {
        this.viewer.entities.remove(this.pointLabel)
      }
    },
    //清除搜索文本
    clearInput() {
      this.options = []
      this.searchInput = ''
      this.removeLabels()
      this.removeHightLight(this.pickSend)
      this.clearSelection()
      this.clearOptions()
    },
    //清除高亮显示
    clearSelection() {
      this.removeHightLight(this.pickSend)
      this.clearAllPrimitives()
    },
    //该方法用于清除二维点和线的primitivecollection
    clearAllPrimitives() {
      if (this._pointPrimitiveCollection) {
        this._pointPrimitiveCollection.removeAll()
        const isPointDel = this.viewer.scene.primitives.remove(this._pointPrimitiveCollection)
        if (isPointDel) this._pointPrimitiveCollection = null
      }
      if (this._polylineprimitiveCollection) {
        this._polylineprimitiveCollection.removeAll()
        const isPolylineDel = this.viewer.scene.primitives.remove(this._polylineprimitiveCollection)
        if (isPolylineDel) this._polylineprimitiveCollection = null
      }
    },
    //该方法用于清除entity label
    removeLabels() {
      if (Cesium.defined(this._customDataSource)) {
        this._customDataSource.entities.removeAll()
      }
      let parentDom = $('#mainMapContainer .widget-infosearch-mapInfoLook')
      if (parentDom.hasClass('show')) {
        parentDom.removeClass('show')
      }
      if (parentDom.length != 0) {
        parentDom.remove()
      }
      this.otherDestroy()
    },
    otherDestroy() {
      if (this.handler != null && !this.handler.isDestroyed()) {
        this.handler.destroy()
      }
    }
  },
  watch: {
    isInit: {
      handler(n, o) {
        if (n == true) {
          this._customDataSource = new Cesium.CustomDataSource('infosearch')
          window.viewer.dataSources.add(this._customDataSource)
          this.viewer = window.viewer
          this.init()
        }
      }
    },
    selectType: {
      immediate: true,
      handler(n, o) {
        switch (n) {
          case '0':
            this.placeholder = '请输入地址'
            break
          case '1':
            this.placeholder = '经度 , 纬度'
            break
          case '2':
            this.placeholder = '请输入部件码'
            break
          case '3':
            this.placeholder = '请输入PBS编码'
            break
          case '4':
            this.placeholder = ''
            break
        }
        this.searchInput = ''
        this.removeLabels()
        this.clearSelection()
      }
    }
  }
}
</script>
<style lang="scss">
.loadingclass {
  .el-loading-spinner {
    i {
      color: #ffffff;
    }
    .el-loading-text {
      color: #ffffff;
    }
  }
}
</style>
<style lang="scss" scoped>
.widget-infosearch {
  z-index: 990;
  position: absolute;
  display: flex;
  left: 10px;
  top: 13px;
  // overflow: hidden;
  width: 300px;
  $fontsize: 0.875rem;
  background: white;
  border-radius: 4px;
  box-shadow: 0px 1px 8px 0px rgba(0, 0, 0, 0.4);
  .treeContainer {
    z-index: 990;
    position: absolute;
    display: flex;
    left: 70px;
  }
  .resultContainer {
    $width: auto;
    position: absolute;
    display: flex;
    z-index: 1000;
    top: 51px;
    left: 68px;
    width: $width;
    background-color: #fff;
    box-shadow: 1px 2px 1px rgba(0, 0, 0, 0.15);
    border-radius: 0 0 2px 2px;
    .wrap-scroll {
      overflow-y: auto;
      overflow-x: hidden;
      width: $width;
      max-height: 350px;
      ul {
        list-style: none;
      }
      ul,
      li {
        margin: 0;
        padding: 0;
      }
      li {
        width: $width;
        a {
          display: block;
          height: 36px;
          line-height: 36px;
          padding-right: 10px;
          text-decoration: none;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          color: #00c;
          outline: 0;
          cursor: pointer !important;
          font-size: 12px;
          i {
            padding-left: 39px;
            font-style: normal;
            color: #666;
            position: relative;
            z-index: 1;
            padding-top: 1px;
          }
          em {
            margin-left: 10px;
            margin-right: 20px;
            font-style: normal;
            color: #999;
          }
        }
        .content {
          border-bottom: 1px solid #e6e6e6;
        }
      }

      li:hover {
        background-color: #ebebeb;
      }
    }
  }
  ::v-deep .el-input__inner {
    height: 36px;
    padding: 0;
    border: none;
  }
  ::v-deep .el-select {
    width: 170px;
  }
  ::v-deep .el-input--suffix {
    .el-input__inner {
      padding-left: 5px;
      padding-right: 28px;
    }
  }
  ::v-deep .el-input {
    .el-input-group__append,
    .el-input-group__prepend {
      line-height: 0;
      //   font-size: 0.875rem;
      //   color: #666666;
      background-color: #fff;
      border: none;
      font-family: Source Han Sans CN;
      .el-button--primary {
        color: #fff;
        background-color: #409eff;
        border-color: #409eff;
        border-radius: 0;
      }
      .el-button--primary:hover {
        background: #66b1ff;
        border-color: #66b1ff;
        color: #fff;
      }
    }
  }
}
</style>