<script>
import commonMixin from '../base/mixins/common.js'
import {unByKey} from 'ol/Observable'
import Overlay from 'ol/Overlay'
import {getArea, getLength, getDistance } from 'ol/sphere'
import View from 'ol/View'
import {LineString, Polygon, MultiPoint } from 'ol/geom'
import Draw from 'ol/interaction/Draw'
import {Tile as TileLayer, Vector as VectorLayer} from 'ol/layer'
import {OSM, Vector as VectorSource} from 'ol/source'
import {Circle as CircleStyle, Fill, Stroke, Style} from 'ol/style'
import SymbolConfig from '../base/SymbolConfig'
import {convertObjToStyle} from '../base/SymbolUtil'
import {transform} from 'ol/proj'
import { generateID, addOverLay, gerOverLay, removeOverLay, getOverLays } from '../base/util.js'
import turf_area from '@turf/area'
import turf_polygon from 'turf-polygon'
export default {
  name: 'sl-measurelx',
  mixins: [commonMixin('interaction')],
  render(h) { },
  data() {
    return {
      measureClickTooltips: [],
      sketch: null,  // 当前绘制的草图------
      helpTooltipElement: null, // 测量绘制帮助提示所对应的元素---
      helpTooltip: null, // 绘制测量帮助信息提示----
      measureTooltipElement: null, // 测量结果显示对应的元素
      measureTooltip: null, // 测量结果提示---
      continuePolygonMsg: '单击继续绘制多边形,双击结束绘制',
      continueLineMsg: '单击继续绘制线,双击结束绘制',
      counter:0, // 判断是否第一次单击
    }
  },
  props: {
    type: {
      type: String
    },
    id: { type: String },
    name: { type: String },
    actived: {
      type: Boolean,
      default: false
    },
    isClear: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isClear(flag) {
      const { $rootComponent, id} = this
      if (flag) {
        $rootComponent.getLayer(id).getSource().clear()
        this.$emit('update:isClear', false)
        let overlays = getOverLays()
        for(let key in overlays){
           const _overlays = gerOverLay(key)
            for (var info of _overlays) {
              $rootComponent.removeOverlay(info)
            }
            removeOverLay(key)
        }       
      }
    },
    actived(flag) {
      this.originInstance.setActive(flag)
    },
    type(val){
      unByKey(this.mouseMoveListener) // 删除鼠标移动事件监听------
      unByKey(this.clickListener) // 删除鼠标单击事件监听------
      this.reload()
    }
  },
  methods: {
    load() {
      const { $rootComponent, id, name } = this
      // 添加客户端图层-------并制定图层的标识以及名称----胡红勋
      var vector = $rootComponent.addLayer({ id, name })
      vector.getSource().on('addfeature', function(event) {
             event.feature.set('drawMark', true)
      })
      // 设置图层样式-----结束------
      const styles = [
        new  Style({
          fill: new Fill({
            color: 'rgba(255, 255, 255, 0.2)' // 填充颜色
          }),
          stroke: new Stroke({
            color: '#ffcc33', // 边框颜色
            width: 2 // 边框宽度
          }),
          image: new CircleStyle({
            radius: 5,
            fill: new Fill({
              color: 'orange'
            })
          })
        }),
        new Style({
          image: new CircleStyle({
            radius: 5,
            fill: new Fill({
              color: 'orange'
            })
          }),
          geometry: function (feature) {
            var coordinates = feature.getGeometry().getCoordinates()
            return new MultiPoint(coordinates)
          }
        })
      ]
      // 样式设置结束---------
      vector.setStyle(styles)
      this.addInteraction()
      this.mouseMoveListener = $rootComponent.$on('mousemove', (evt) => {
        // 判断绘制控件是否激活，激活添加绘制地图提示-----
        if(this.actived) {
            this.mouseMoveHandler(evt)
        }
      })
    },
    // 地图鼠标移动事件处理器
    mouseMoveHandler(evt) {
       if (evt.dragging) {
          return
        }
        var helpMsg = '单击开始绘制'
        // 判断当前绘制的要素是否存在----
        if (this.sketch) {
          var geom = this.sketch.getGeometry() // 获取正绘制要素对应的几何体
          if (geom instanceof Polygon) { // 如果为多边形，则多边形绘制的相关提示-----
            helpMsg = this.continuePolygonMsg
          } else if (geom instanceof LineString) { // 如果为线，则线绘制的相关提示-----
            helpMsg = this.continueLineMsg
          }
        }
        this.helpTooltipElement.innerHTML = helpMsg
        this.helpTooltip.setPosition([evt.lon, evt.lat])
        this.helpTooltipElement.classList.remove('hidden')
    },
    // 创建绘制帮助提示元素以及弹出框-------
    createHelpTooltip() {
        if (this.helpTooltipElement) {
          this.helpTooltipElement.parentNode.removeChild(this.helpTooltipElement)
        }
        this.helpTooltipElement = document.createElement('div')
        this.helpTooltipElement.className = 'tooltip hidden'
        this.helpTooltip = new Overlay({
          element: this.helpTooltipElement,
          offset: [15, 0],
          positioning: 'center-left'
        })
        this.map.addOverlay(this.helpTooltip)
      },
      // 创建绘制结果提示元素，以及弹出框---
    createMeasureTooltip() {
        if (this.measureTooltipElement) {
          this.measureTooltipElement.parentNode.removeChild(this.measureTooltipElement)
        }
        this.measureTooltipElement = document.createElement('div')
        this.measureTooltipElement.className = 'tooltip tooltip-measure'
        this.measureTooltip = new Overlay({
          element: this.measureTooltipElement,
          offset: [0, -15],
          positioning: 'bottom-center'
        })
        this.map.addOverlay(this.measureTooltip)
      },
    addInteraction() {
      const { type, $rootComponent, id} = this
      const source = $rootComponent.getLayer(id).getSource()
      const style = convertObjToStyle(SymbolConfig.defaultMeasuretyle)
      this.originInstance = new Draw({
        source: source, // 测量绘制层数据源
        type,
        style
      })
      $rootComponent.addInteraction(this.originInstance, this.actived)
      this.createMeasureTooltip() // 创建测量工具提示框
      this.createHelpTooltip() // 创建帮助提示框
      // var listener = null
      // 绑定交互绘制工具开始绘制的事件
      this.originInstance.on('drawstart', (evt) => {
             // 设置草图要素-------
            this.sketch = evt.feature
            var tooltipCoord = evt.coordinate
            let resStr = ''
            this.listener = this.sketch.getGeometry().on('change', (evt) => {
              var geom = evt.target
              if (geom instanceof Polygon) {
                this.output = this.formatArea(geom)
                console.log(geom.getCoordinates())
                tooltipCoord = geom.getInteriorPoint().getCoordinates()
                resStr = ''
              } 
              if (geom instanceof LineString) {
                this.output = this.formatLength(geom)
                tooltipCoord = geom.getLastCoordinate()
                resStr = '长度为:'
              }
  
              this.measureTooltipElement.innerHTML = resStr + this.output
              this.measureTooltip.setPosition(tooltipCoord)
            })
      })
      // 绑定交互绘制工具结束绘制的事件
      this.originInstance.on('drawend', (evt) => {
            let measureResult = ''
            let pos = null
            if (evt.feature.getGeometry() instanceof Polygon) {
                measureResult = '总面积为:'
                pos = evt.feature.getGeometry().getInteriorPoint().getCoordinates()
            } 
            if (evt.feature.getGeometry() instanceof LineString) {
                measureResult = '总长度为:'
                pos = evt.feature.getGeometry().getLastCoordinate()
            }
           // 设置结果弹出框偏移以及样式------开始---
           this.measureTooltipElement.className = 'tooltip tooltip-static'
           this.measureTooltip.setOffset([0, -7])
           // 胡红勋添加 -------------------开始------18-24
           // 删除 结果弹出框--
          this.$rootComponent.removeOverlay(this.measureTooltip)
          // 创建新的结果弹出框
          const contaner = document.createElement('div')
          const span = document.createElement('span')
          contaner.style.background = '#ffcc33'
          contaner.style.border = ' 1px solid red'
          contaner.style.color = '#333'
          contaner.style.fontSize = '12px'
          contaner.style.fontFamily = '宋体,Simsun'
          contaner.style.paddingLeft = '3px'
          contaner.style.borderRadius = '4px'
          const a = document.createElement('a')
          a.style.border = '1px solid rgb(255, 1, 3)'
          a.style.background = '#ffffff'
          a.style.width = '15px'
          a.style.height = '18px'
          a.style.marginLeft = '5px'
          a.style.marginRight = '3px'
          a.style.cursor = 'hand'
          a.innerHTML = '✖'
          // if (evt.feature.getGeometry() instanceof Polygon) {
          //     span.innerHTML = measureResult + this.output
          //     contaner.appendChild(span)
          //     contaner.appendChild(a)
          // }
          span.innerHTML = measureResult + this.output
          contaner.appendChild(span)
          contaner.appendChild(a)
        let tips = new Overlay({
          element: contaner,
          offset: [7, 0],
          positioning: 'center-left'
        })
        tips.setPosition(pos)
        this.$rootComponent.addOverlay(tips)
        this.measureClickTooltips.push(tips)
        const unique = generateID()
        addOverLay(unique, [...this.measureClickTooltips])
        a.onclick = ((attr, feature) => {
          return (e) => {
            $rootComponent.getLayer(this.id).getSource().removeFeature(feature)
            const overlays = gerOverLay(attr)
            for (var info of overlays) {
              this.$rootComponent.removeOverlay(info)
            }
            removeOverLay(attr)
          }
        })(unique, evt.feature)
           // 胡红勋添加 -------------------结束------18-24
           this.counter = 0
           this.sketch = null
           this.measureClickTooltips=[]
           // 重新设置测量弹出框对象
           this.measureTooltipElement = null
           this.helpTooltip.setPosition(undefined)
           this.createMeasureTooltip()
           unByKey(this.listener) // 删除监听------
           this.$emit("mesureEnd", {isMeasureEnd: true})
      })
      // 添加单击处理程序---添加弹出窗显示分段的距离-----
      this.clickListener = $rootComponent.$on('singleclick', (evt) => {
       // 判断组件是否激活----
          if(this.actived) {
            if(this.type === 'Polygon') {
              return
            }
            var content = "长度为：" + this.output
            var border = '1px solid red'
          if (this.counter === 0) {
              this.counter++
              content = '起点'
              border = '1px solid green'
            }
            const pos = [evt.lon, evt.lat]
            const elem = document.createElement('div')
            elem.style.background = '#ffcc33'
            elem.style.border = border
            elem.style.color = '#333'
            elem.style.fontSize = '12px'
            elem.style.fontFamily = '宋体,Simsun'
            elem.style.paddingLeft = '3px'
            elem.style.borderRadius = '4px'
            elem.innerHTML = content
            let overlay = new Overlay({
              element: elem,
              offset: [7, 0],
              positioning: 'center-left'
            })
            // overlay.setPosition(pos)
            //  this.measureTooltip.setPosition(undefined)
            // $rootComponent.addOverlay(overlay)
            // this.measureClickTooltips.push(overlay)
          }   
      })
    },
    formatLength(line) {
      var coordinates = line.getCoordinates() // 解析线的坐标
      var length = 0
      const { $rootComponent } = this
      var sourceProj = $rootComponent.getView().getProjection()
      // 通过遍历坐标计算两点之前距离，进而得到整条线的长度
      for (var i = 0, ii = coordinates.length - 1; i < ii; ++i) {
        var c1 = transform(coordinates[i], sourceProj, 'EPSG:4326')
        var c2 = transform(coordinates[i + 1], sourceProj, 'EPSG:4326')
        length += getDistance(c1, c2)
      }
      var output = ''
      if (length > 100) {
        output = (Math.round(length / 1000 * 100) / 100) + ' ' + 'km' // 换算成KM单位
      } else {
        output = (Math.round(length * 100) / 100) + ' ' + 'm' // m为单位
      }
      return output // 返回线的长度
    },
    formatArea(polygon) {
      const coods  = polygon.getLinearRing(0).getCoordinates()
      console.log(coods)
      if(coods.length <= 3){
         return "总面积为:0"
      } 
      var polygon = turf_polygon([coods])
      var area = turf_area(polygon)
      var area = Math.abs(area)
      console.log(area+"面积")
      var output = ''
      if (area > 10000) {
        output = (Math.round(area / 1000000 * 100) / 100) + ' ' + 'km<sup>2</sup>'// 换算成KM单位
      } else {
        output = (Math.round(area * 100) / 100) + ' ' + 'm<sup>2</sup>'// m为单位
      }
      return output
      }
   }
}
</script>
 <style>
      .tooltip {
        position: relative;
        background: rgba(0, 0, 0, 0.5);
        border-radius: 4px;
        color: white;
        padding: 4px 8px;
        opacity: 0.7;
        white-space: nowrap;
      }
      .tooltip-measure {
        opacity: 1;
        font-weight: bold;
      }
      .tooltip-static {
        background-color: #ffcc33;
        color: black;
        border: 1px solid white;
      }
      .tooltip-measure:before,
      .tooltip-static:before {
        border-top: 6px solid rgba(0, 0, 0, 0.5);
        border-right: 6px solid transparent;
        border-left: 6px solid transparent;
        content: "";
        position: absolute;
        bottom: -6px;
        margin-left: -7px;
        left: 50%;
      }
      .tooltip-static:before {
        border-top-color: #ffcc33;
      } 
</style>
