<template>
  <transition
    appear
    name="animate__animated animate__move"
    enter-active-class="animate__flipInX"
    leave-active-class="animate__flipOutX"
  >
    <div class="widget-SearchBox" ref="widget-SearchBox">
      <div class="search">
        <el-input placeholder="" v-model="searchInput" class="input-with-select" size="small" clearable>
          <el-select v-model="selectType" slot="prepend" placeholder="请选择" :popper-append-to-body="false">
            <el-option label="工程" value="4"></el-option>
          </el-select>
          <el-button slot="append" icon="el-icon-search" @click="searching()"></el-button>
        </el-input>
        <ComTreeList
          :prjId="prjId"
          style="position: absolute; top: 0; left: 0.46875rem; /* 90/192 */"
          @changeProjectName="changeProjectName($event)"
        />
      </div>
      <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'
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 } })
export default class SearchBox extends Vue {
  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
  mounted() {
    let target = this.$refs['widget-SearchBox'] as any
    target.style.setProperty('--left', '2.34375rem')
  }
  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')
  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()
      }
    })
  }
  //工程搜索模块
  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() {
    const searchType = this.selectType
    const inputObj = this.searchInput
    //   if (xss.isXSS(inputObj)) {
    if (!inputObj) {
      this.$message.warning('请选择工程!')
      return
    }
    switch (searchType) {
      case '4':
        this.searchPrjSpeedInfo(inputObj)
        break
    }
  }
  /**
   * 该方法用于查询工程进度
   * @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
      }
      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.addUnitBillboard({
            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)
        }
      })
    })
  }
  /**
   * 该方法用于生成部件定位指示牌
   * @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
      _customDataSource.entities.add(entity)
    }
  }
  //该方法用于清除entity label
  removeLabels() {
    if (Cesium.defined(_customDataSource)) {
      _customDataSource.entities.removeAll()
    }
  }
}
</script>

<style lang="scss" scoped>
.animate__flipInX,
.animate__flipOutX {
  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 */;
      }
      .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-icon-arrow-up:before {
          content: '';
          display: block;
          // 定义元素宽高
          margin-top: 0.041667rem /* 8/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%;
          transform: rotate(180deg);
        }
      }
    }
  }
  .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;
      }
    }
  }
}
</style>