<template>
  <div>
    <div class="module-title">施工状态</div>
    <div class="module-item"><label>已施工监理未验收</label><el-switch v-model="sgwys"></el-switch></div>
    <div class="module-item"><label>已施工监理已验收</label><el-switch v-model="sgyys"></el-switch></div>
    <div class="module-item"><label>最近三天施工</label><el-switch v-model="zjstsg"></el-switch></div>
  </div>
</template>

<script>
import { getbuiltNotCheck_api, getbuiltCheck_api, getlocdays_api } from '@/api/APIs'
import Config from './config.json'
export default {
  name: 'BuildStatus', //编码显示
  props: {
    apiurl: {}
  },
  data() {
    return {
      sgwys: false,
      sgyys: false,
      zjstsg: false,
      _postUpdate: undefined
    }
  },
  computed: {
    _apiurl: function () {
      return this.apiurl
    },
    config: function () {
      return Config
    }
  },
  watch: {
    sgwys(n, o) {
      if (n) {
        this.pbsLayerApi('sgwys')
      } else {
        this.releaseSelection()
      }
    },
    sgyys(n, o) {
      if (n) {
        this.pbsLayerApi('sgyys')
      } else {
        this.releaseSelection()
      }
    },
    zjstsg(n, o) {
      if (n) {
        this.pbsLayerApi('zjstsg')
      } else {
        this.releaseSelection()
      }
    }
  },
  methods: {
    /**
     * 该方法用于针对反馈图层加PBS编码结构接口的请求
     * @param id 类型
     */
    pbsLayerApi(id) {
      let data = {}
      this.clearPrimitives()
      if (!this._primitiveCollection) {
        this._primitiveCollection = new Cesium.PrimitiveCollection()
        window.viewer.scene.primitives.add(this._primitiveCollection)
      } else {
        return
      }
      switch (id) {
        case 'sgwys':
          getbuiltNotCheck_api(data)
            .then((res) => {
              const result = res
              this.showConstrucInfo(result)
            })
            .catch((err) => {
              console.log(err)
            })
          break
        case 'sgyys':
          getbuiltCheck_api(data)
            .then((res) => {
              const result = res
              this.showConstrucInfo(result)
            })
            .catch((err) => {
              console.log(err)
            })
          break
        case 'zjstsg':
          data = { days: 3 }
          getlocdays_api(data)
            .then((res) => {
              const result = res
              this.showConstrucInfo(result)
            })
            .catch((err) => {
              console.log(err)
            })
          break
      }
    },
    //该方法用于展示施工信息
    showConstrucInfo(result) {
      const that = this
      if (result.code === 1) {
        if (Object.keys(result.result).length === 0) {
          that.$message('无施工信息')
          return
        }
        that.pbsInfo(result.result)
      } else {
        that.$message.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('无施工信息')
        return
      }
      const url = this._apiurl.smiddtfw

      const filterPars = layers.map((item) => {
        const pipeConfig = this.$_.find(this.config.pipe, 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.$emit('queryMapByAttribute', options)
    },
    /**
     * 查询成功
     * @param result
     */
    queryComplete(result) {
      const that = this
      if (result.result.currentCount === 0) {
        return
      }
      //   result.originResult.recordsets.forEach(record => {
      //       if (record.features.length == 0) return false;
      //       const pipe = this.$_.find(that.config.pipe, 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 = window.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 (!this._primitiveCollection) return
      const primtCol = this._primitiveCollection
      //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.CYAN,
            time: 0.0
          },
          source: EllipsoidFadeSource
        }
      })
      records.forEach((record) => {
        if (record.features.length == 0) return false
        const pipe = this.$_.find(that.config.pipe, 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, circlefadeMaterial))
          }
        })
      })
      if (this._postUpdate) {
        this._postUpdate()
        this._postUpdate = undefined
      }
      this._postUpdate = window.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, 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 (this._primitiveCollection) {
        this._primitiveCollection.removeAll()
        const isDel = window.viewer.scene.primitives.remove(this._primitiveCollection)
        if (isDel) this._primitiveCollection = null
      }
    },
    /**
     * 清除选中
     */
    releaseSelection() {
      window.viewer.scene.layers.releaseSelection()
      this.clearPrimitives()
      if (this._postUpdate) {
        this._postUpdate()
        this._postUpdate = undefined
      }
    },
    removeSource() {
      this.releaseSelection()
    }
  }
}
</script>

<style lang="scss" scoped>
.module-title {
  padding: 8px 20px;
  text-align: center;
  font-size: 1rem;
  background: #99c3e8;
}
.module-item {
  padding: 8px 20px;
  display: flex;
  justify-content: space-between;
  label {
    vertical-align: middle;
  }
}
</style>