<template lang="pug">
  <div class='m_i_dialog'>
    <el-dialog  width="1600px"  :close-on-click-modal='false' :visible.sync='visible' append-to-body>
      .title-bold(slot='title') 漏检数据详情
      <el-card>
        <el-row style="background:#fff;" :span="24">
          <el-col class="resource-container" ref="drag">
            <div id="map" style="width: 100%;height: 508px;position: relative;">
              <div id="popup" class="ol-popup" ref='popup'>
                <a href="#" id="popup-closer" class="ol-popup-closer"></a>
                <div id="popup-content" style="width:300px; height:120px;"></div>
              </div>
            </div>
          </el-col>
        </el-row>
      </el-card>
      <span class="dialog-footer" slot='footer'>
        <el-button type="primary" @click='handleClose'>关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import Vue from 'vue'
// openlayer
import 'ol/ol.css'
import { Map, View, layer, Markers } from 'ol'
import { Projection, transform, fromLonLat } from 'ol/proj'
import { getCenter } from 'ol/extent'
import overviewmap from 'ol/control/OverviewMap'
import interaction from 'ol/interaction/Interaction'
import Modify from 'ol/interaction/Modify'
import ImageLayer from 'ol/layer/Image'
import ImageStatic from 'ol/source/ImageStatic'
import { format } from 'ol/coordinate'
import { control } from 'ol/control/Control'
import Zoom from 'ol/control/Zoom'
import { DoubleClickZoom } from 'ol/interaction'
import MousePosition from 'ol/control/MousePosition'
import Draw from 'ol/interaction/Draw'
import LineString from 'ol/geom/LineString'
import Overlay from 'ol/Overlay'

// 图上图标相关
import OlFeature from 'ol/Feature'
import OlGeomPoint from 'ol/geom/Point'
import OlLayerVector from 'ol/layer/Vector'
import OlSourceVector from 'ol/source/Vector'
import OlStyleStyle from 'ol/style/Style'
import OlStyleIcon from 'ol/style/Icon'
// 用来添加相关文字描述的
import Text from 'ol/style/Text'
import Fill from 'ol/style/Fill'
import Stroke from 'ol/style/Stroke'
import { log } from 'util'
let that
export default {
  computed: {
    ...mapState('d2admin/user', ['info'])
  },
  filters: {
    ellipsis(value) {
      // console.log(value)
      if (!value) return ''
      let len = value.length
      let realLength = 0
      for (var i = 0; i < len; i++) {
        let charCode = value.charCodeAt(i)
        if (charCode >= 0 && charCode <= 128) {
          realLength += 1
        } else {
          realLength += 2
        }
        if (realLength > 20) {
          return value.slice(0, i) + '...'
        }
      }
      return value
    }
  },
  data() {
    return {
      imgLayerList: [],
      controlList: [],

      lineArr: [
        [-639.46, 441.91],
        [-264.16, 223.53],
        [314.96, 218.68]
      ], //线坐标集合
      visible: false,
      title: '详情',
      list: [],
      mapInfo: {},
      nodeKey: 'id',
      defaultExpandedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        level1: 'level'
      },
      urlPath: window.CONFIG.urlPath,
      checkedData: {
        tierId: '',
        tierName: '',
        sId: '',
        subCode: '02'
      },
      pointIdList: [],
      lineDomList: [],
      linePointList: []
    }
  },
  created() {
    that = this
  },
  methods: {
    init(res) {
      this.visible = true
      this.checkedData = { ...res }
      console.log('checkedData', this.checkedData)
      this.getList()
    },
    // 初始化地图
    initMap(url) {
      // 计算静态地图映射到地图上的范围
      let extent = [-1100, 110, 1460, 820]

      let projection = new Projection({
        // 投影
        code: 'xkcd-image',
        units: 'pixels',
        extent: extent
      })

      let layerItem = new ImageLayer({
        // id: mapList[i].id,
        source: new ImageStatic({
          url: url, //这里添加静态图片的地址
          projection: projection,
          imageExtent: extent
        })
      })
      this.imgLayerList.push(layerItem)

      let zoomControl = new Zoom({
        delta: 0.2,
        zoomInTipLabel: '',
        zoomOutTipLabel: ''
      })
      // 大图
      this.map = new Map({
        target: 'map',
        layers: this.imgLayerList,
        controls: [zoomControl],
        view: new View({
          projection: projection,
          center: getCenter([0, 0, 0, 0]), // 获取范围的中心坐标。
          zoom: 2.65,
          maxZoom: 2.65,
          minZoom: 2.65,
          extent: [-1030, 100, 2000, 1000] //[minX, minY, maxX, maxY] 控制拖动
        })
      })
      // 删除默认的双击事件
      const dblClickInteraction = this.map
        .getInteractions()
        .getArray()
        .find((interaction) => {
          return interaction instanceof DoubleClickZoom
        })
      this.map.removeInteraction(dblClickInteraction)
      this.changeVectorLayer(this.list) //

      let element = document.getElementById('popup')
      let content = document.getElementById('popup-content')
      let popup = new Overlay({
          element: element,
          positioning: 'bottom-center',
          stopEvent: false
          // offset: [0, -50]
      })
      this.map.addEventListener('click', function (evt) {
          // console.log('evt', evt)
          let feature = evt.map.forEachFeatureAtPixel(evt.pixel, function(feature) {
                  return feature
              })
          //判断点击的坐标是否在当前图标上
          if (feature) {
              let coordinate = feature.getGeometry().getCoordinates()
             let currentItem = that.list.filter(e => {
               return e.id == feature.id_
             })
              let infoText = ''
              if (currentItem[0].patrolTime) {
                     infoText = `
                  <p><span class="alarm-info">巡查人：${that.checkedData.patrollerName}</span></p>
                  <p><span class="alarm-info" >计划开始时间：${currentItem[0].startTime}</span></p>
                  <p><span class="alarm-info" >计划结束时间：${currentItem[0].endTime}</span></p>
                  <p><span class="alarm-info" >计划巡查时间：${currentItem[0].arrivalTime == null ? '' : currentItem[0].arrivalTime}</span></p>
                  <p><span class="alarm-info" >实际巡查时间：${currentItem[0].patrolTime}</span></p>
                  <p><span class="alarm-info">巡查状态：完成</span></p>
              `
              } else {
                         infoText = `
                  <p><span class="alarm-info">巡查人：${that.checkedData.patrollerName}</span></p>
                  <p><span class="alarm-info" >计划开始时间：${currentItem[0].startTime}</span></p>
                  <p><span class="alarm-info" >计划结束时间：${currentItem[0].endTime}</span></p>
                  <p><span class="alarm-info" >计划巡查时间：${currentItem[0].arrivalTime == null ? '' : currentItem[0].arrivalTime}</span></p>
                  <p><span class="alarm-info">巡查状态：漏检</span></p>

              `
              }

              if (infoText) {
                  let infoHtml = '<code>' + infoText + '</code>'
                  content.innerHTML = infoHtml
                  element.style.display = 'block'
                  popup.setPosition(coordinate)
                  that.map.addOverlay(popup)
              } else {
                  element.style.display = 'none'
              }
          } else {
              element.style.display = 'none'
          }
      })
    },
    getPointStyle(src, name, zoom) {
      let style = new OlStyleStyle({
        image: new OlStyleIcon({
          anchor: [0.5, 0.5],
          scale: zoom || 0.8,
          //rotation:0 旋转度
          src: require('@/assets/images/' + src)
        }),
        text: new Text({
          text: name, // 添加文字描述
          font: '14px font-size', // 设置字体大小
          fill: new Fill({
            // 设置字体颜色
            color: 'black'
          }),
          offsetY: 30 // 设置文字偏移量
        })
      })
      return style
    },
    changeVectorLayer(list) {
      if (list) {
        this.list = list
      } else {
        return
      }
      if (this.map) {
        this.map.removeLayer(this.vectorLayer)
        this.map.removeLayer(this.lineVectorLayer)
        this.map.removeInteraction(this.modify)
      } else {
        return
      }

      this.lineVectorLayer = new OlLayerVector({
        source: new OlSourceVector({
          features: []
        }),
        style: new OlStyleStyle({
          stroke: new Stroke({
            color: '#409EFF',
            width: 3
          })
        })
      })
      this.map.addLayer(this.lineVectorLayer)

      let featuresArr = []
      for (let i in list) {
        featuresArr.push(
          this.getFeature(list[i].coordinateX, list[i].coordinateY)
        )
        let style = this.getPointStyle('xungengdian.png', list[i].name)
        featuresArr[i].setStyle(style)
        featuresArr[i].setId(list[i].id)
      }

      this.vectorLayer = new OlLayerVector({
        source: new OlSourceVector({
          features: featuresArr
        })
      })
      this.map.addLayer(this.vectorLayer)
      //将点和线的Feature对象 ，放在一个数组里面
      let modifyFeatures = this.lineVectorLayer
        .getSource()
        .getFeatures()
        .concat(this.vectorLayer.getSource().getFeatures())
      // this.modify = new Modify({
      //       source: this.vectorLayer.getSource()
      //   })
      this.modify = new Modify({
        source: new OlSourceVector({
          features: modifyFeatures
        })
      })
      this.modify.on('modifyend', (e) => {
        let pixel = this.map.getEventPixel(e.mapBrowserEvent.originalEvent)
        //获取当前拖拽的feature对象，该feature没有id，
        let feature = e.mapBrowserEvent.map.forEachFeatureAtPixel(
          pixel,
          function (feature) {
            return feature
          }
        )
        if (feature) {
          //feature与features数组对象比较Geometry对象的坐标是否相等可得出当前拖拽的feature的对象
          for (let i in that.list) {
            //根据id获取feature对象
            let feature_ = that.vectorLayer
              .getSource()
              .getFeatureById(that.list[i].id)
            //新增的feature对象没保存，是没有id通过，key获取feature对象
            let featureKey = that.vectorLayer
              .getSource()
              .getFeatureById(that.list[i].key)
            //红外探测器和振动光纤的第二点同过key+'end'获取feature对象
            let featureEnd = that.vectorLayer
              .getSource()
              .getFeatureById(that.list[i].key + 'end')
            if (feature_ || featureKey || featureEnd) {
              //获取坐标
              let coordinate
              if (feature_) coordinate = feature_.getGeometry().flatCoordinates
              if (featureKey) {
                coordinate = featureKey.getGeometry().flatCoordinates
              }
              if (
                coordinate.toString() ===
                feature.getGeometry().flatCoordinates.toString()
              ) {
                that.list[i].coordinateX = parseFloat(coordinate[0]).toFixed(2)
                that.list[i].coordinateY = parseFloat(coordinate[1]).toFixed(2)
                break
              }
              if (featureEnd) {
                coordinate = featureEnd.getGeometry().flatCoordinates
              }
              if (
                coordinate.toString() ===
                feature.getGeometry().flatCoordinates.toString()
              ) {
                that.list[i].xpoint = parseFloat(coordinate[0]).toFixed(2)
                that.list[i].ypoint = parseFloat(coordinate[1]).toFixed(2)
                break
              }
            }
          }
        }
      })

      if (this.editable) {
        //添加拖拽监听事件
        this.map.addInteraction(this.modify)
      }
    },
    getFeature(x, y) {
      return new OlFeature({
        type: 'icon',
        geometry: new OlGeomPoint([x, y])
      })
    },
    // 画线
    drawLine(lineArr) {
      if (this.lineFeature) {
        let f = this.lineVectorLayer.getSource().getFeatureById('line')
        if (f) {
          this.lineVectorLayer.getSource().removeFeature(f)
        }
      }
      if (lineArr) {
        //自定义绘制线
        this.lineFeature = new OlFeature(new LineString(lineArr))
        this.lineFeature.setId('line')
        this.lineVectorLayer.getSource().addFeature(this.lineFeature)
      }
    },
    // 改变层级和鹰眼图
    changeImgControl(id) {
      let srcIndex = this.imgLayerList.findIndex((e) => {
        return e.values_.id == id
      })
      for (var k = 0; k < this.imgLayerList.length; k++) {
        if (this.imgLayerList[k].values_.id == id) {
          // that.imgurl=map.readPath
          this.imgLayerList[k].setVisible(true)
        } else {
          this.imgLayerList[k].setVisible(false)
        }
      }
    },
    getList() { //漏检的点
      this.$http({
        url: this.$http.adornUrlEq(
          '/epPatrolMissed/getId'
        ),
        method: 'get',
        params: { id: this.checkedData.id, stationId: this.checkedData.stationId }
      })
        .then((data) => {
          if (data && data.code === 0) {
            this.pointIdList = data.pointIdList
          }
        })
        .then(() => {
          this.getEpPatrolLinePoint()
        })
        .then(() => {})
    },
    getEpPatrolLinePoint() {
      this.$http({
        url: this.$http.adornUrlEq('/epPatrolLine/getResultByLineId'),
        method: 'get',
        params: {
          lineId: this.checkedData.lineId,
          stationId: this.checkedData.stationId,
          planId: this.checkedData.planId
        }
      })
        .then((data) => {
          if (data && data.code === 0) {
            // this.linePointList = data.list
            this.list = data.list
            this.mapInfo = this.urlPath + data.map.filePath
            // console.log('linePointList', this.linePointList)
            // console.log('mapInfo', this.mapInfo)

            this.pointIdList.forEach((el) => {
              this.list.forEach((listRes) => {
                if (el == listRes.pointId) {
                  Vue.set(listRes, 'active', true)
                  // this.lineData.push(listRes)
                }
              })
            })
          }
        })
        .then(() => {
          // console.log('list', this.list)
          if (!this.map) {
            this.initMap(this.mapInfo)
               if (this.list) {
                    let lineGroup = this.list.map(e => {
                   return [Number(e.coordinateX), Number(e.coordinateY)]
                 })
                this.drawLine(lineGroup)
               }
                let newArr = []

                if (this.pointIdList.length) { //漏检id集合
                      this.pointIdList.forEach((el) => {
                        this.list.forEach((k) => {
                          if (el == k.pointId) {
                              let style2 = this.getPointStyle('xungengdian2.png', k.name)
                              this.vectorLayer.getSource().getFeatureById(k.id).setStyle(style2)

                            // newArr.push(k)
                          }
                        })
                    })
                //     for(var i=0;i<newArr.length;i++){
                //       let style2 = this.getPointStyle( "xungengdian1.png", newArr[i].name, 0.3);
                //       this.vectorLayer.getSource().getFeatureById(newArr[i].id).setStyle(style2);
                //  }
              }
          }
          // this.forLine();
        })
    },
    forLine() {
      if (this.list) {
        this.lineDomList = []
        this.list.forEach((res, index) => {
          if (this.list[index + 1]) {
            this.setLine(res, this.list[index + 1])
          }
        })
      }
    },
    setLine(data1, data2) {
      let x1 = data1.coordinateX * 1,
        x2 = data2.coordinateX * 1,
        y1 = data1.coordinateY * 1,
        y2 = data2.coordinateY * 1,
        h = 0,
        w = 0,
        h1 = 0,
        w1 = 0
      let x = x1 > x2 ? x2 : x1,
        deg = 0,
        y = 0
      if (x1 == x2 && y1 != y2) {
        w = 2
        h = Math.abs(y1 - y2)
      }
      if (y1 == y2 && x1 != x2) {
        h = 2
        w = Math.abs(x1 - x2)
      }
      if (y1 != y2 && x1 != x2) {
        h = 2
        w1 = Math.abs(x1 - x2)
        h1 = Math.abs(y1 - y2)
        w = Math.sqrt(w1 * w1 + h1 * h1).toFixed(0)
      }

      if (x1 > x2) {
        y = y2
        if (y1 > y2) {
          deg = Math.atan2(y2 - y1, x2 - x1) / 0.017453292
        } else {
          deg = 360 - Math.abs(Math.atan2(y1 - y2, x1 - x2) / 0.017453292)
          y += 40
          x += 30
        }
      } else {
        y = y1
        if (y2 > y1) {
          deg = Math.atan2(y2 - y1, x2 - x1) / 0.017453292
          if (deg > 45) {
            x += 30
          }
        } else {
          deg = 360 - Math.abs(Math.atan2(y2 - y1, x2 - x1) / 0.017453292)
          x += 30
          y += 40
        }
      }

      if (deg < 0) {
        deg = 180 - Math.abs(deg)
      }
      if (deg < 30) {
        y += 15
      }
      if (deg > 300) {
        x -= 15
      }
      this.lineDomList.push({
        width: w,
        height: h,
        x: x,
        y: y,
        deg: deg
      })
    },
    showResourceByMapId() {
      this.spotData.forEach((spotRes) => {
        if (this.checkedData.tierId == spotRes.id) {
          this.list = spotRes.children || []
        }
      })
      if (this.pointIdList.length) {
        this.pointIdList.forEach((pointRes) => {
          this.list.forEach((listRes) => {
            if (pointRes == listRes.id) {
              Vue.set(listRes, 'active', true)
            }
          })
        })
      }
    },
    handleClose() {
      this.visible = false
      this.$refs.popup.style.display = 'none'
    },
    changeMap(map) {
      // console.log('map.id', map.id, map.name)
      this.checkedData.tierId = map.id
      this.checkedData.tierName = map.name
      this.stationMap = map
      this.showResourceByMapId()
    },
    //取消
    cancel() {
      this.$confirm('确认取消?', '漏检数据详情', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.visible = false
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消退出'
          })
        })
    }
  }
}
</script>
<style lang='scss' scoped>
    .ol-popup {
        display: none;
        position: absolute;
        background-color: white;
        -webkit-filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2));
        filter: drop-shadow(0 1px 4px rgba(0,0,0,0.2));
        padding: 15px;
        border-radius: 10px;
        border: 1px solid #cccccc;
        bottom: 12px;
        left: -50px;
    }
    .ol-popup:after, .ol-popup:before {
        top: 100%;
        border: solid transparent;
        content: " ";
        height: 0;
        width: 0;
        position: absolute;
        pointer-events: none;
    }
    .ol-popup:after {
        border-top-color: #2A2828;
        border-width: 10px;
        left: 48px;
        margin-left: -10px;
        color:#2A2828;
        opacity:0.9;
    }
    .ol-popup:before {
        border-top-color: #cccccc;
        border-width: 11px;
        left: 48px;
        margin-left: -11px;
    }
    .ol-popup-closer {
        text-decoration: none;
        position: absolute;
        top: 2px;
        right: 8px;
    }
    .ol-popup-closer:after {
        content: "✖";
    }
        #popup{
        background:#2A2828;
        opacity:0.9;
        box-shadow:0px 0px 6px 0px rgba(0, 0, 0, 0.1);

    }
    #popup-content{
        opacity:1;
        font-size:12px;
        font-family:Microsoft YaHei;
        font-weight:400;
        color:rgba(196,196,196,1);
        line-height:20px;
        height: auto!important;
        /deep/.alarm-info{
            font-size:14px;
            color: #fff;
            // font-weight: 600;
        }
    }
    #popup-closer{
        color: #FFFFFF;
    }
.resource-container {
  // img {
  //   width: 100%;
  // }
  /deep/.ol-zoom {
      display: none;
    }
}
.el-card {
  height: 99%;
}
.left_list {
  margin-top: 20px;
  .left_list_row_on {
    background-color: #35aff8 !important;
    color: #fff;
  }
  .left_list_row {
    cursor: pointer;
    width: 90%;
    height: 40px;
    border-radius: 20px 0 0 20px;
    background: #fff;
    padding: 0 20px;
    margin-bottom: 10px;
    .left_list_row_name {
      float: left;
      widows: 65%;
      line-height: 40px;
    }
    .left_list_row_size {
      float: right;
      widows: 25%;
      padding-top: 7px;
    }
  }
}
.span-box {
  height: 60px;
  width: 72px;
}
</style>
