<template>
  <transition
    appear
    name="animate__animated animate__move"
    enter-active-class="animate__fadeInLeftBig"
    leave-active-class="animate__fadeOutLeftBig"
  >
    <div class="widget-SearchBox" ref="widget-SearchBox">
      <div class="search">
        <el-input
          placeholder=""
          v-model="searchInput"
          class="input-with-select"
          size="small"
          clearable
          @focus="inputFocus()"
          @blur="inputBlur()"
          @clear="clearInput()"
          @keyup.enter.native="searching()"
        >
          <el-select v-model="selectType" slot="prepend" placeholder="请选择" :popper-append-to-body="false">
            <el-option label="工程" value="4"></el-option>
            <el-option label="PBS编码" value="3"></el-option>
            <el-option label="部件标识码" value="2"></el-option>
            <el-option label="设备" value="1"></el-option>
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="searching()" :loading="isSearching"></el-button>
        </el-input>
        <!-- <ComTreeList
          :prjId="prjId"
          style="position: absolute; top: 0; left: 0.46875rem; /* 90/192 */"
          @changeProjectName="changeProjectName($event)"
        /> -->
      </div>
      <transition
        appear
        name="animate__animated animate__move"
        enter-active-class="animate__fadeIn"
        leave-active-class="animate__fadeOut"
      >
        <div class="infoPanel" v-if="isShowInfoPanel" @mouseenter="PanelEnter()" @mouseleave="PanelLeave()">
          <pbs-tree ref="pbsTree" @selectChange="pbsTreeSelectChange" />
        </div>
        <div class="devicePanel" v-if="!isShowInfoPanel && searchDeviceList.length > 0">
          <div class="deviceItem" v-for="item of searchDeviceList" :key="item.id" @click="deviceClickLocated(item)">
            {{ item.id }}
          </div>
        </div>
      </transition>
      <!-- <div class="lifting">
        <span>抬升：</span>
        <el-input-number v-model="layerdown" size="small" controls-position="right"></el-input-number>
        <span class="unit">米</span>
      </div>
      <div class="setOpacity">
        <span>透明度：</span>
        <el-input-number v-model="opacity" size="small" controls-position="right" :min="0" :max="100" :step="10">
        </el-input-number>
        <span class="unit">%</span>
      </div> -->
    </div>
  </transition>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import { mapSearch_api } from '@/api/APIs'
import { queryMapByAttribute } from '@/views/groupPage/util'
import ComTreeList from '@/views/groupPage/components/ComTreeList.vue'
import Config from '@/views/groupPage/districtPageModules/commonModules/config.json'
import _ from 'lodash'
import SearchInfo from '@/views/groupPage/districtPageModules/customTools/infoComponents/serachInfo.vue'
import pbsTree from '@/views/groupPage/districtPageModules/customTools/pbsTree.vue'
const Cesium = (window as any).Cesium
const SuperMap = (window as any).SuperMap
let _customDataSource = null
const gLayerList = [
  'NETWORK_SJ_PSWS@sxgk#1',
  'NETWORK_SJ_PSYS@sxgk#1',
  'NETWORK_SJ_PSWS_Node@sxgk#1',
  'NETWORK_SJ_PSYS_Node@sxgk#1',
  'TF_SJ_PSYS_JG_B_3D@sxgk#1',
  'TF_SJ_PSYS_JG_B_3D@sxgk#2',
  'TF_SJ_PSWS_JG_B_3D@sxgk#2',
  'TF_SJ_PSWS_JG_B_3D@sxgk#1'
]
//搜索栏
@Component({ name: 'SearchBox', components: { ComTreeList, pbsTree } })
export default class SearchBox extends Vue {
  isSearching: boolean = false
  searinfoModules = [] //地图信息面板收集
  searchInput = ''
  selectType = '4'
  loading = null
  apiurl = {
    sjfw: '',
    dtfw: '',
    smiddtfw: ''
  }
  backImg = require('@/views/groupPage/images/searchBoxBack.png')
  layerdown = 0
  //地表透明度配置
  opacity = 0
  disVisibleLayers = ['Config']
  g_modelTransparent = false
  //工程树相关配置
  isShowInfoPanel: boolean = false
  isEnterPanel: boolean = false
  //设备查询列表
  searchDeviceList = []
  mounted() {
    let target = this.$refs['widget-SearchBox'] as any
    if (this.$store.state.bigScreen.currentActive) target.style.setProperty('--left', '2.34375rem')
    else target.style.setProperty('--left', '.10417rem')
  }
  viewer
  get prjId() {
    return 45
  }
  get config() {
    return Config
  }
  get mapConfig() {
    return this.$store.state.bigScreen.mapConfig
  }
  get isInitViewer() {
    return this.$store.state.bigScreen.isInitViewer
  }
  @Watch('isInitViewer',{immediate:true})
  onChangeMethod() {
    this.viewer = (window as any).viewer
    this.init()
  }
  //透明度变化
  @Watch('opacity')
  changeOpacity(newVal) {
    const val = parseFloat(newVal)
    const alpha = parseFloat((1 - val / 100).toString())
    const layers = this.disVisibleLayers
    if (this.g_modelTransparent && layers.length > 0) {
      this.viewer.scene.layers.layerQueue.forEach((layer) => {
        if (_.indexOf(layers, layer.name) !== -1) {
          layer.style3D.fillForeColor.alpha = alpha
        }
      })
    }
    this.viewer.scene.globe.globeAlpha = 1 - val / 100
    for (var i = 0; i < this.viewer.scene.imageryLayers.length; i++) {
      var ly = this.viewer.scene.imageryLayers.get(i)
      ly.alpha = alpha
    }
  }
  //管线抬升
  @Watch('layerdown')
  changeDepth(value) {
    let height = parseFloat(value)
    if (isNaN(height)) {
      return
    }
    this.mapConfig.upDepth = height
    const style3D = new Cesium.Style3D()
    style3D.altitudeMode = 0
    style3D.bottomAltitude = height
    gLayerList.forEach((item) => {
      var layer = this.viewer.scene.layers.find(item)
      if (layer) {
        layer.style3D = style3D
        layer.refresh()
      }
    })
  }
  // @Watch('selectType')
  // changeSelectTypeMethod(val) {
  //   if (val !== '4') {
  //     this.isShowInfoPanel = false
  //   }
  // }

  /**页面全局键盘事件监听 */
  // created() {
  //   this.keyDown()
  // }
  // beforeDestroy() {
  //   this.keyDownReview()
  // }
  // //按键恢复
  // keyDownReview() {
  //   document.onkeydown = function (event) {
  //     var e = event || window.event
  //     e.returnValue = true
  //   }
  // }
  // //按钮监听键盘
  // keyDown() {
  //   //监听键盘按钮
  //   document.onkeydown = function (event) {
  //     var e: any = event || window.event
  //     var keyCode = e.keyCode || e.which
  //     switch (keyCode) {
  //       case 13: //enter
  //         alert('enter')
  //         break
  //       default:
  //         break
  //     }
  //     if (e && e.preventDefault) {
  //       e.preventDefault()
  //     } else {
  //       window.event.returnValue = false
  //     }
  //   }
  // }
  //工程搜索模块
  init() {
    this.apiurl.sjfw = this.mapConfig.gisResource.tiplayers.config['sjfw'].url
    this.apiurl.dtfw = this.mapConfig.gisResource.maps.config['sjdt'].url
    this.apiurl.smiddtfw = this.mapConfig.gisResource.tiplayers.config['bjsmidfw'].url
    _customDataSource = new Cesium.CustomDataSource('SearchBox')
    this.viewer.dataSources.add(_customDataSource)
  }
  // changeProjectName(data) {
  //   if (data != '') {
  //     const { name, code } = data
  //     this.searchInput = name
  //     this.searching()
  //   } else {
  //     this.clearInput()
  //   }
  // }
  // clearInput() {
  //   this.searchInput = ''
  //   this.removeLabels()
  // }
  searching() {
    this.isSearching = true
    const searchType = this.selectType
    const inputObj = this.searchInput.toString().trim()
    //   if (xss.isXSS(inputObj)) {
    if (!inputObj) {
      this.$message.warning('请输入内容!')
      this.isSearching = false
      return
    }
    switch (searchType) {
      case '4':
        this.searchPrjSpeedInfo(inputObj)
        this.filterPbsTree(inputObj)
        break
      case '3':
        this.searchPbsTree(inputObj)
        break
      case '2':
        this.searchPbsTree(inputObj)
        break
      case '1':
        this.searchEntity(inputObj)
        break
    }
    this.isSearching = false
  }
  /**
   * 该方法用于查询工程进度
   * @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 as any).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
      }
      this.searinfoModules = []
      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: '',
          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 = _.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
        }
        //监理
        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.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 = _.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.addUnitContent({
            id: scanProj.code,
            name: scanProj.code,
            text: labelText,
            position: position,
            scanProj: scanProj,
            imgSrc: imgSrc
          })
        })
      }
      queryMapByAttribute({
        url: geourl,
        filterParameters: filters,
        completed: onComplete.bind(this),
        failed: function (err) {
          that.loading.close()
          that.$message.error('查询失败')
          console.log(err)
        }
      })
    })
  }
  //添加站点指示牌
  addUnitContent(options) {
    const searchInfoConstructor = Vue.extend(SearchInfo)
    let searinfoModule = new searchInfoConstructor({
      data: {
        id: options.name.replaceAll('.', ''),
        options
      },
      store: this.$store
    }).$mount()
    this.searinfoModules.push(searinfoModule)
  }
  //该方法用于清除entity label
  removeLabels() {
    if (Cesium.defined(_customDataSource)) {
      _customDataSource.entities.removeAll()
    }
    if (this.searinfoModules.length > 0) {
      this.searinfoModules.forEach((item) => {
        item.remove()
      })
    }
  }
  //--------------------------------------工程树搜索模块
  //工程树面板显示逻辑
  inputFocus() {
    if (this.selectType !== '1') {
      this.isShowInfoPanel = true
    }
  }
  inputBlur() {
    setTimeout(() => {
      if (this.searchInput !== '' || this.isEnterPanel) return
      else this.isShowInfoPanel = false
    }, 300)
  }
  clearInput() {
    this.isShowInfoPanel = false
    this.removeLabels()
    //
    this.searchDeviceList = []
  }
  PanelEnter() {
    this.isEnterPanel = true
  }
  PanelLeave() {
    this.isEnterPanel = false
    if (document.activeElement.className == 'el-input__inner') return
    if (this.searchInput === '') this.isShowInfoPanel = false
  }
  //选择搜索
  pbsTreeSelectChange(data) {
    switch (this.selectType) {
      case '4':
        this.searchInput = data.originname
        break
      case '3':
        this.searchInput = data.code
        break
      case '2':
        this.searchInput = data.pipeId
        break
    }
  }
  filterPbsTree(input) {
    ;(this.$refs['pbsTree'] as any).searchLocal(input, true)
  }
  searchPbsTree(code) {
    ;(this.$refs['pbsTree'] as any).searchOnline(code)
  }
  searchEntity(input) {
    this.searchDeviceList = []
    let dataSource = this.viewer.dataSources.getByName('monitorTree')
    // let target = dataSource[0].entities.getById(input)
    let targetArr = dataSource[0].entities.values
    let target: any = this.unsharpMask(
      targetArr.map((item) => item.id),
      input
    )
    target.forEach((item) => {
      let index = targetArr.findIndex((e) => e.id === item)
      if (index != -1) {
        this.searchDeviceList.push(targetArr[index])
      }
    })
  }
  deviceClickLocated(target) {
    this.$store.state.bigScreen.currentDeviceShow = null
    if (target) {
      this.viewer.flyTo(target).then(() => {
        this.$store.state.bigScreen.currentDeviceShow = target.info
      })
    } else {
      this.$message('暂无设备位置信息')
    }
  }
  unsharpMask(list, keyword) {
    let arr = []
    for (let index = 0; index < list.length; index++) {
      if (JSON.stringify(list[index]).indexOf(keyword) !== -1) {
        arr.push(list[index])
      }
    }
    return arr
  }
}
</script>

<style lang="scss" scoped>
// .animate__fadeInLeftBig,
// .animate__fadeOutLeftBig {
//   animation-duration: 3s; //动画持续时间
//   animation-delay: 0s; //动画延迟时间
// }
.widget-SearchBox {
  $size10: 0.052083rem /* 10/192 */;
  $size20: 0.104167rem /* 20/192 */;
  z-index: 2;
  //position
  top: 0.505208rem /* 97/192 */;
  margin-left: var(--left); //2.34375rem /* 450/192 */;
  position: absolute;
  left: 0;
  //font
  font-family: Source Han Sans CN;
  .search {
    float: left;
    margin-right: 0.052083rem /* 10/192 */;
    & ::placeholder {
      color: rgba(43, 167, 255, 1);
    }
    /deep/ .el-input {
      $backgroundColor: rgba(7, 48, 80, 0.9);
      // .el-select .el-input {
      //   width: 0.46875rem /* 90/192 */;
      // }
      .el-input__inner {
        color: #eee;
        background-color: $backgroundColor;
        border: none;
        // width: 0.78125rem /* 150/192 */;
        width: 0.625rem; /* 120/192 */
      }
      .el-input-group__append,
      .el-input-group__prepend {
        background-color: $backgroundColor;
        border: none;
        color: #2ba7ff;
      }
      .el-input-group__prepend {
        .el-select {
          margin: -0.015625rem /* 3/192 */ -0.109375rem /* 21/192 */;
          position: relative;
        }
        .el-input__inner {
          font-size: 0.072917rem /* 14/192 */;
          font-family: Source Han Sans CN;
          font-weight: 500;
          color: #2ba7ff;
          position: relative;
        }
        .el-input::after {
          content: '';
          position: absolute;
          top: 0;
          bottom: 0;
          right: 0;
          margin: auto 0;
          width: 1px;
          height: 80%;
          background-color: rgba(41, 177, 255, 0.3);
        }
        .el-select .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-input-group__append {
        .el-button {
          padding: 0;
        }
      }
    }
    /deep/ .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;
      }
    }
  }
  .lifting,
  .setOpacity {
    float: left;
    $background: rgba(7, 48, 80, 0.9);
    background: $background;
    border-radius: 0.010417rem /* 2/192 */;
    margin-right: 0.052083rem /* 10/192 */;
    span {
      padding: 0.052083rem /* 10/192 */ 0 0.052083rem /* 10/192 */ 0.052083rem /* 10/192 */;
      font-size: 0.072917rem /* 14/192 */;
      font-family: Source Han Sans CN;
      font-weight: 500;
      color: #82bae2;
    }
    .unit {
      padding: 0.052083rem /* 10/192 */ 0.052083rem /* 10/192 */ 0 0 !important;
    }
    /deep/ .el-input-number {
      width: 0.3125rem /* 60/192 */;
      .el-input-group__append,
      .el-input-group__prepend {
        padding: 0 0.026042rem /* 5/192 */;
      }
      .el-input__inner {
        color: rgba(43, 167, 255, 1);
        border: none;
        background-color: $background;
        position: relative;
        padding-right: 0.15625rem /* 30/192 */;
        padding-left: 0;
      }
      .el-input-number__decrease,
      .el-input-number__increase {
        background: transparent;
        border: none;
        height: 50%;
      }
      .el-input-number__increase .el-icon-arrow-up:before {
        content: '';
        display: block;
        // 定义元素宽高
        margin-top: 0.010417rem /* 2/192 */;
        width: 0.130208rem /* 25/192 */;
        height: 0.078125rem /* 15/192 */;
        background: url('~@/views/groupPage/images/三角上.png') no-repeat center center;
        background-size: 100% 100%;
        object-fit: contain;
      }
      .el-input-number__decrease .el-icon-arrow-down:before {
        content: '';
        display: block;
        // 定义元素宽高
        // margin-top: 0.010417rem /* 2/192 */;
        width: 0.130208rem /* 25/192 */;
        height: 0.078125rem /* 15/192 */;
        background: url('~@/views/groupPage/images/三角下.png') no-repeat center center;
        background-size: 100% 100%;
        object-fit: contain;
      }
    }
  }
  .infoPanel {
    position: absolute;
    top: 0.21875rem /* 42/192 */;
    background: linear-gradient(180deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.24) 100%);
    height: 2.5625rem /* 492/192 */;
    width: 2.395833rem /* 460/192 */;
  }
  .devicePanel {
    position: absolute;
    top: 0.21875rem /* 42/192 */;
    background: linear-gradient(180deg, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.24) 100%);
    max-height: 1.354167rem /* 260/192 */;
    width: 1.40625rem /* 270/192 */;
    overflow-y: auto;
    .deviceItem {
      display: inline-flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      padding: 0.104167rem /* 20/192 */;
      font-size: 0.072917rem /* 14/192 */;
      color: #eee;
    }
    .deviceItem:hover {
      background-color: rgba(130, 186, 226, 0.3);
    }
  }
}
</style>