<template lang="pug">
  <div class="patrol_spot">
    <el-container style='padding-left:0px;'>
      <el-aside width='333px' style='height:758px'>
          <el-card style="overflow: auto">
            <div class="patrol_spot_left_top">
              <div class="patrol_spot_left_topL">
                <div :class="[activeName==1?'on':'']" @click="handleClick(1)">巡查点列表</div>
                <div :class="[activeName==2?'on':'']" @click="handleClick(2)">收藏夹</div>
              </div>
              <div style="float:right; margin:5px 5px 0 5px">
                <el-button type="text" size="mini" icon='el-icon-shoucang' @click="treeDataOffClick()"></el-button>
              </div>
              <div class="patrol_spot_left_topR">
                <el-input suffix-icon="el-icon-search" clearable size="small" v-model="searchInput"></el-input>
              </div>
            </div>
            <div class="tree-container">
              <el-tree v-if="treeVisiable" class="dic_tree" :data="treeData" ref='tree' :accordion='true' :highlight-current='true' :filter-node-method="filterNode" :props="defaultProps" :default-expand-all='false' @node-click="handleNodeClick" :default-expanded-keys='defaultExpandedKeys' :node-key='nodeKey' >
                <span class="custom-tree-node" style='width:100%;line-height: 18px;' slot-scope="{ node, data }">
                  <span v-if="node.data.level != 6 && node.data.iconB" class="el-icon-wq-treeIcon1 xa-icon"></span>
                  <span v-if="node.data.level != 6 && !node.data.iconB" class="el-icon-wq-treeIcon xa-icon"></span>
                  <span v-if="node.data.level == 6" class="el-icon-xunchadian xa-icon"></span>
                  <span :title="node.label">&nbsp;{{node.label,15 |ellipsis}}</span>
                  <span style="float:right;">
                    //- <el-button style="padding:0;" v-if="activeName == 1 && node.data.level == 6" type='text' icon="el-icon-star-off" @click="treeDataOffClick(node,data)" ></el-button>
                    <el-button style="padding:0;" v-if="activeName == 2 && node.data.level == 6" type='text' icon="el-icon-delete" @click="treeDataDeleteClick(node,data)" ></el-button>
                  </span>
                  span(v-if=" node.data.iconB" class='el-icon-my-treeFlag')
                </span>
              </el-tree>
            </div>
          </el-card>
      </el-aside>

      <el-main style="padding:0px;" onselectstart="return false;">
        <el-card>
          <div class="patrol_spot_right_button">
            <el-row style="padding-bottom:15px;" :span="24">
                <el-col :md='12' :sm="5" class='tier-btn'>
                    <el-button type="primary" size="small" plain :class="[checkedData.tierId===item.id?'active-tier':'']" style="float:left;margin-left:10px;" v-for="item in mapList" :key='item.id' @click="changeMap(item)">{{item.name}}</el-button>
                </el-col>
                <el-col :md='12' :sm="5" style="float:right;">
                    <div  style="float:right; margin-right:10px;">
                      //- <el-button type="primary" v-if="editable" size="small" @click="addSpot" style="float:left;margin:10px 0 0 10px;">新增</el-button>
                      //- <div :class='iconClass' v-if="editable" style="float:left;" @click="addSpot" title='新增巡查点'></div>
                      <el-button type="primary" v-if="editable && isAuth('patrol:spot:save')" size="small" style="float:left;margin:10px 0 0 10px;" :disabled="isAdd" @click="addSpot" title='新增巡查点'>新增</el-button>
                      <el-button type="primary"  @click="updateSpot"  v-if="editable && isAuth('patrol:spot:update')" :disabled='listItem?false:true' size="small" style="float:left;margin:10px 0 0 10px;">修改</el-button>
                      <el-button type="primary"  @click="removeSpot"  v-if="editable && isAuth('patrol:spot:delete')" :disabled='listItem?false:true' size="small" style="float:left;margin:10px 0 0 10px;">删除</el-button>
                      <el-button type="primary" v-if="!editable && isAuth('patrol:spot:update') && activeName != 2" size="small" @click="editClick" style="float:left;margin:10px 0 0 10px;">编辑图层</el-button>
                      <el-button type="primary" v-if="editable && isAuth('patrol:spot:update')" size="small" @click="saveClick" :disabled="saveDisabled"  style="float:left;margin:10px 0 0 10px;" v-prevent-re-click>保存图层</el-button>
                      <el-button type="primary" v-if="editable && isAuth('patrol:spot:update')" size="small" @click="escClick" style="float:left;margin:10px 0 0 10px;">取消编辑</el-button>
                    </div>
                </el-col>
            </el-row>
          </div>
          <el-row style="height:708px;background:#fff;" :span="24">
              <el-col class="resource-container" :style="obj" ref="drag">
                <div id="map" class="map"  ref='map' style="width: 100%;height: 680px;position: relative;"></div>
              </el-col>
          </el-row>
        </el-card>
      </el-main>
      <add-or-update ref="addOrUpdate" :isAdd='isAdd' @closeQ="closeQueryDetailVisible"></add-or-update>
      <query-detail ref='queryDetail' :isAdd='isAdd' @closeQ="closeQueryDetailVisible"></query-detail>
      //- <query-detail ref='queryDetail'></query-detail>
    </el-container>
  </div>

</template>

<script>
import QueryDetail from './query-detail'
import AddOrUpdate from './add-or-update'
import { getUUID } from '@/util'
import Vue from 'vue'

import 'ol/ol.css'
import { Map, View, layer, Markers } from 'ol'
import { Projection, Transform } from 'ol/proj'
import { getCenter } from 'ol/extent'
import Modify from 'ol/interaction/Modify'
import overviewmap from 'ol/control/OverviewMap'
import ImageLayer from 'ol/layer/Image'
import ImageStatic from 'ol/source/ImageStatic'
import { control } from 'ol/control/Control'
import Zoom from 'ol/control/Zoom'
import { DoubleClickZoom, Select } from 'ol/interaction'
// 图上图标相关
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 LineString from 'ol/geom/LineString'
// 用来添加相关文字描述的
import { Text, Fill, Stroke, Circle, Style } from 'ol/style'

import { log } from 'util'

let that
export default {
  name: 'sys-user',
  filters: {
    ellipsis (value, len) {
      if (!value) return ''
     if (value.length > len) {
        return value.slice(0, len) + '...'
      }
      return value
    }
  },
  data () {
    return {
      isAdd: false,
      systemList: [],
      imgLayerList: [],
      controlList: [],
      iconClass: 'el-icon-xungengdian',
      drawType: 'None',
      listItem: null,
      iconStyle: null,
      modify: null,
      vectorLayer: null,
      transformationSta: 1,
      urlPath: window.CONFIG.urlPath,
      isCollapse: true,
      treeVisiable: true,
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      addOrUpdateVisible: false,
      queryDetailVisible: false,
      treeData: [],
      delDisabled: true,
      defaultExpandedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        level1: 'level'
      },
      nodeKey: 'id',
      station: {}, //当前选择的站点
      mapList: [], //当前站点的所有层
      stationMap: {}, //当前选择的层
      resource: {}, //当前选择的资源点
      checkedData: {
        lineId: '',
        lineName: '',
        stationId: '',
        stationName: '',
        subSystem: '',
        tierId: '',
        tierName: '',
        resourceId: '',
        sId: localStorage.getItem('stationId'),
        subCode: '02',
        layerId: ''
      },
      currentNode: {},
      dragAble: false,
      list: [],
      obj: 'pointer-events:initial',
      editable: false,
      activeName: '1',
      searchInput: '',
      //当前选择的层级
      tierMap: null,
      saveDisabled: false
    }
  },
  components: {
    QueryDetail,
    AddOrUpdate
  },
  // beforeRouteLeave :(to,from,next)=>{
  //   if(confirm('你还没有保存，是否离开？') == true){
  //       next()
  //   }else{

  //   }
  // },
  watch: {
    searchInput (val) {
      this.$refs.tree.filter(val)
    }
  },
  created () {
    that = this
    this.initTreeStationMap()
  },
  methods: {
    // 初始化地图
    initMap(url) {
      let mapList = this.mapList
      this.imgurl = url
      // 计算静态地图映射到地图上的范围
      let extent = [-1100, 110, 1460, 820]

      let projection = new Projection({
        // 投影
        code: 'xkcd-image',
        units: 'pixels',
        extent: extent
      })
      if (mapList.length > 0) {
         for (var i = 0; i < mapList.length; i++) {
              let layerItem = new ImageLayer({
                  id: mapList[i].id,
                  source: new ImageStatic({
                    url: mapList[i].readPath, //这里添加静态图片的地址
                    projection: projection,
                    imageExtent: extent
                  }),
                  visible: false
                })
              this.imgLayerList.push(layerItem)

             let controlItem = new overviewmap({
                  className: 'ol-overviewmap myOverview', //鹰眼控件样式
                  // 在鹰眼中加载相同坐标系下不同数据源的图层
                  layers: [
                    new ImageLayer({
                      source: new ImageStatic({
                        url: mapList[i].readPath, //这里添加静态图片的地址
                        projection: projection,
                        imageExtent: extent
                      })
                    })
                  ],
                  // layers:this.controlList,
                  collapseLabel: '\u00BB', //鹰眼控件展开时功能按钮上的标识
                  label: '\u00AB', //鹰眼控件折叠时功能按钮上的标识
                  collapsed: false //初始为展开方式
                })
              this.controlList.push(controlItem)
        }
      }
      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.5,
          maxZoom: 5.0,
          minZoom: 1.5,
          extent: [-1100, -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) //

    //将鹰眼控件加载到map中
    this.map.addControl(this.controlList[0])

      //点击事件
      this.map.on('click', function (evt) {
        let feature = evt.map.forEachFeatureAtPixel(evt.pixel, function (feature) {
          return feature
        })
        if (feature) {
          //  console.log(111, '添加后点击')
          //  console.log('选中的点',feature);
          //  console.log(that.list);
            // 新增
            //  that.listItem=null
              for (let i in that.list) {
                if (feature.id_ === that.list[i].id) { //已添加的item
                  that.listItem = JSON.parse(JSON.stringify(that.list[i]))
                  }
                  //true弹出详情页面
                   that.mapClick(feature, that.list[i], true)
              }
        } else {
            let coordinate = evt.coordinate //鼠标单击点的坐标
            if (that.iconStyle === null || !that.editable) {
              //
            } else {
               //console.log('添加点')
                // that.list=[]
                let bean = that.addPoint(coordinate)
                that.list.push(bean)
                that.iconStyle = null
            }
        }
      })
    },
    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.removeInteraction(this.modify)
      } else {
          return
      }

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

      this.vectorLayer = new OlLayerVector({
        source: new OlSourceVector({
        features: featuresArr
        })
      })
      this.map.addLayer(this.vectorLayer)
      this.modify = new Modify({
            source: this.vectorLayer.getSource()
      })
      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
                 // if (that.list[i].key) {
                 //     featureKey = that.vectorLayer.getSource().getFeatureById(that.list[i].key)
                 // }
                 if (feature_) {
                     //获取坐标
                     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)
                         if (that.listItem) {
                             that.listItem = that.list[i]
                         }
                         break
                     }
                 }
             }
          }
      })

      if (this.editable) {
          //添加拖拽监听事件
          this.map.addInteraction(this.modify)
      }
    },
    getFeature(x, y) {
       return new OlFeature({
                    type: 'icon',
                    geometry: new OlGeomPoint([x, y])
                 })
    },
            // 改变层级和鹰眼图
    changeImgControl(id) {
          let srcIndex = this.imgLayerList.findIndex((e) => {
             return e.values_.id == id
          })
          this.map.removeControl(this.controlList[srcIndex])
          this.map.addControl(this.controlList[srcIndex])
          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)
            }
        }
    },
    mapClick(feature, item, flag) {
        //默认样式
        let style = this.getPointStyle(item.byx2 + '.png', item.name)
        //选中样式
        let style2 = this.getPointStyle(item.byx2 + '1.png', item.name, 0.3)
        //获取feature对象
        let feature_ = this.vectorLayer.getSource().getFeatureById(item.id)

        if (feature_) {
            if (feature_ === feature) {
                //console.log(feature_)
                //修改选中样式
                feature_.setStyle(style2)

                if (this.editable) {
                  // that.listItem=JSON.parse(JSON.stringify(item))
                  // this.$refs.queryDetail.init(item, 1) // 1 编辑
                  // this.updateSpot(item)
                } else {
                     if (flag) this.$refs.queryDetail.init(item.id, 2) // 2 查看
                }
                  that.listItem = JSON.parse(JSON.stringify(item))
            } else {
                //清除选中以外的样式
                feature_.setStyle(style)
            }
        } else {
            //获取新增的feature对象
            // let newFeature = this.vectorLayer.getSource().getFeatureById(item.key)
            // if (newFeature) {
            //   if (newFeature === feature) {
            //         newFeature.setStyle(style2)
            //         if (!this.editable) {
            //             this.$refs.queryDetail.init(item, 2)
            //         }
            //           that.listItem = null
            //         if (newFeature.id_ == item.key) {
            //           that.listItem = JSON.parse(JSON.stringify(item))
            //         }
            //     } else {
            //         //清除选中以外的样式
            //       newFeature.setStyle(style)
            //     }
            // }
        }
    },
    // 清除所有选中样式
    cleanStyle() {
            for (let i in this.list) {
                    let style = this.getPointStyle(this.list[i].byx2 + '.png', this.list[i].name)
                    //获取feature对象
                    let feature_ = this.vectorLayer.getSource().getFeatureById(this.list[i].id)
                    feature_.setStyle(style)
            }
    },
    // 树节点过滤
    filterNode (value, data) {
      if (!value) return true
      return data.name.indexOf(value) !== -1
    },
    handleClick (tab) { //左侧tab切换
      if (tab) {
        this.activeName = tab
        }
      //手动销毁tree
      this.treeData = []
      if (this.activeName == 1) {
        this.initTreeStationMap()
      } else {
        this.initTreeStationMap(true)
      }
    },
    escClick () { //退出编辑
        this.iconClass = 'el-icon-xungengdian'

      this.editable = false
      this.initTreeStationMap()
    },
    treeDataDeleteClick (node, data) { //左侧tree取消收藏按钮
      this.$confirm('确认取消该收藏?', '取消收藏', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        closeOnClickModal: false
      })
      .then(() => {
        this.$http({
          url: this.$http.adornUrlEq('/epPointEnshrine/delete'),
          method: 'post',
          data: {
            pointId: node.data.id,
            stationId: this.checkedData.sId
          }
        }).then(data => {
          if (data && data.code === 0) {
            this.$message.success('取消收藏成功')
            this.initTreeStationMap(true)
          }
        })
      })
    },
    treeDataOffClick () { //左侧tree收藏按钮
      let node = this.$refs.tree.getCurrentNode()
      if (node.level != 6) {
        this.$message.warning('只能收藏巡查点')
        return
      }
      this.$http({
        url: this.$http.adornUrlEq('/epPointEnshrine/save'),
        method: 'post',
        data: {
          pointId: node.id,
          stationId: this.checkedData.sId
        }
      }).then(data => {
        if (data && data.code === 0) {
          if (data.msg === '收藏成功') {
            this.$message.success(data.msg)
          } else {
            this.$message.warning(data.msg)
          }
        }
      })
    },
    editClick () { //点击编辑按钮
        this.editable = true
        if (this.editable) {
            //添加拖拽监听事件
            this.map.addInteraction(this.modify)
        } else {
            this.map.removeInteraction(this.modify)
        }
    },
    saveClick () { //点击保存图层按钮
      // this.listItem=null
      this.saveSet()
      this.iconClass = 'el-icon-xungengdian'
      // let num = 0, warn = false
      // this.list.forEach(res => {
      //   if (!warn) {
      //     num++
      //     if (!res.name) {
      //       this.$message.warning('检查点名称不能为空')
      //       warn = true
      //       return false
      //     }
      //     if (num == this.list.length) {
      //       this.saveSet()
      //     }
      //   }
      // })
    },
    saveSet () {
      if (this.list) {
          let len = this.list.length
          for (let i in this.list) {
              this.list[i].byx3 = len.toString()
              len--
          }
      }
      this.saveDisabled = true
      this.$http({
        url: this.$http.adornUrlEq('/epPatrolPoint/updateList'),
        method: 'post',
        data: this.list
      }).then(data => {
          this.saveDisabled = false
        // console.log('初始化线路树：', data.nodes)
        if (data && data.code === 0) {
          this.$message.success(data.msg)
          this.editable = false
          this.initTreeStationMap()
        }
      })
    },
    //初始化站点下的资源点
    initTreeStationMap (save) {
      let url = ''
      if (!save) { // 摄像头列表接口路径
        url = this.$http.adornUrlEq('/epPatrolPoint/list')
      } else { // 收藏夹接口路径
        url = this.$http.adornUrlEq('/epPointEnshrine/getEnshrinePointTreeList')
      }

      let initTreeData = null
      this.$http({
        url: url,
        method: 'post',
        data: {
          stationId: this.checkedData.sId,
          name: this.searchInput
        }
      }).then(data => {
        if (data && data.code === 0) {
          this.treeData = data.nodes
          if(this.treeData){
            this.treeData.forEach(element => {
              element.readPath = this.urlPath + element.filePath
            })
          }
          if (this.tierMap && this.treeData) {
            for (let i in this.treeData) {
              if (this.treeData[i].id === this.tierMap.id) {
                initTreeData = this.treeData[i]
                break
              }
            }
          } else {
            if (this.treeData) {
              initTreeData = this.treeData[0]
            }
          }
          if (!initTreeData && this.treeData) {
            initTreeData = this.treeData[0]
          }
        }
      }).then(() => {
        if (this.checkedData.sId && initTreeData) {
          this.defaultExpandedKeys = [initTreeData.id]
          this.list = JSON.parse(JSON.stringify(initTreeData.children || []))
          this.checkedData.layerId = initTreeData.id
        }
        this.initStation(this.checkedData.sId, initTreeData)
      })
    },
    pointListClick (item) {
      this.delDisabled = false
      if (item.id == '') {
        this.activeChooseResourceBox(item.nid, 'nid')
      } else {
        this.activeChooseResourceBox(item.id, 'id')
        this.defaultExpandedKeys = [item.id]
        this.$refs.tree.setCurrentKey(item.id)
        this.isFlag(this.treeData, item.id) 
      }
    },
    getTierMap(id) {
        for (let i in this.mapList) {
            if (id === this.mapList[i].id) {
                this.tierMap = this.mapList[i]
                this.currentNode = this.$refs.tree.getNode(this.tierMap.id).data
                this.defaultExpandedKeys = [this.currentNode.id]
                break
            }
        }
    },
    initStation (id, initTreeData) {
      this.$http({
        url: this.$http.adornUrl(`/liStation/getId/${id}`),
        method: 'get',
        params: this.$http.adornParams()
      }).then(data => {
        if (data && data.code === 0) {
          this.station = null
          this.mapList = []
          this.station = data.bean
          this.mapList = data.bean.mapList
          this.mapList.forEach(element => {
            element.readPath = this.urlPath + element.filePath
          })
          // console.log(this.mapList, '------------')
          if (!this.tierMap) {
              this.tierMap = this.mapList[0]
          }
          this.checkedData.stationId = this.station.id
          this.checkedData.stationName = this.station.stationName
          this.checkedData.tierId = !this.tierMap ? '' : this.tierMap.id
          if (!this.checkedData.tierId) {
            return
          }
          if (initTreeData) {
            this.defaultExpandedKeys = [initTreeData.id]
            this.$nextTick(() => {
              this.$refs.tree.setCurrentNode(initTreeData)
            })
            this.isFlag(this.treeData, this.tierMap.id)
          }
          this.stationMap = this.tierMap
        }
      }).then(() => {
        if (!this.checkedData.tierId) {
          return
        }
          if (!this.map) {
                this.initMap()
                this.changeImgControl(this.tierMap.id)
                //this.imgLayerList[0].setVisible(true) //初始第一个显示
            } else {
                this.changeVectorLayer(this.list)
            }
      })
    },
    isFlag(data, id) {
      data.forEach(res => {
        if (res.id === id) {
          Vue.set(res, 'iconB', true)
        } else {
          Vue.set(res, 'iconB', false)
        }
        if (res.children) {
          this.isFlag(res.children, id)
        }
      })
    },
    //线路资源点树节点点击事件
    handleNodeClick (node) {
      this.delDisabled = false
      this.currentNode = node
      let name = node.name
      let id = node.id
      this.isFlag(this.treeData, id)
      // this.treeData.forEach(res => {
      //   if (res.id === id) {
      //     Vue.set(res, 'iconB', true)
      //   } else {
      //     Vue.set(res, 'iconB', false)
      //   }
      // })
      if (node.level === 4) { //站层
      // this.listItem = null
        this.checkedData.layerId = node.id
        this.checkedData.tierId = id
        this.checkedData.tierName = name
        this.checkedData.stationId = node.stationId
        this.stationMap = node
        this.getTierMap(id)
        this.showResourceByMapId()
        this.changeImgControl(id)
        //console.log(this.list)
        this.changeVectorLayer(this.list)
      } else if (node.level === 6) { //资源点1
        this.checkedData.layerId = node.layerId
        this.checkedData.tierId = node.layerId
        this.checkedData.stationId = node.stationId
        this.stationMap = { 'readPath': node.readPath }
        this.showResourceByMapId()

        this.checkedData.resourceId = id
        this.activeChooseResourceBox(id, 'id')
        // 资源点
        let subNode = this.$refs.tree.getNode(node.layerId).data
        // console.log('当前要选中的层级节点', subNode)
        this.list = []
        subNode.children.forEach(res => {
            this.list.push(res)
        })
        this.getTierMap(node.layerId)
        this.changeImgControl(node.layerId)
        this.changeVectorLayer(this.list)
        let feature = this.vectorLayer.getSource().getFeatureById(id)
        if (feature) {
            for (let i in this.list) {
              // if(feature.id_==that.list[i].id){
              //     this.listItem=that.list[i]
              // }
                //flag为ture打开详情或者编辑页面
              this.mapClick(feature, that.list[i], false)
            }
        }
        // console.log('资源点列表：', this.list)
      }
    },
    //激活选中资源点位节点
    activeChooseResourceBox (id, idName) {
      this.list.forEach(res => {
        if (res[idName] === id) {
          Vue.set(res, 'active', true)
        } else {
          Vue.set(res, 'active', false)
        }
      })
    },
    //切换层级
    changeMap (map) {
      //图层缩放级别设置为默认
      this.map.getView().setZoom(1)
      this.tierMap = map
      this.changeImgControl(map.id)
      this.currentNode = this.$refs.tree.getNode(map.id).data
      //console.log('当前要选中的节点', this.currentNode)
      //将选中的层级树节点设置为选中
      this.$nextTick(() => {
         this.$refs.tree.setCurrentNode(this.currentNode)
      })
      this.defaultExpandedKeys = [this.currentNode.id]
      this.isFlag(this.treeData, this.currentNode.id)

      // console.log('当前要选中的节点2', this.currentNode)
      this.checkedData.tierId = map.id
      this.checkedData.layerId = map.id
      this.checkedData.tierName = map.name
      this.stationMap = map
      this.showResourceByMapId()
      this.changeVectorLayer(this.list)
    },
    //根据层级id展示当前层级所有的资源点
    showResourceByMapId () {
      let tierNode = this.$refs.tree.getNode(this.checkedData.tierId).data
      // console.log('当前要选中的层级节点', tierNode.children
      this.list = []

      if (tierNode && tierNode.children) {
        tierNode.children.forEach(subSystem => {
          this.list.push(subSystem)
        })
      }
    },
    //详情
    closeQueryDetailVisible (now, boolean) {
      this.listItem = now
      this.isAdd = boolean
      for (let i in this.list) {
          if (this.list[i].id === now.id) {
              this.list[i] = now
              let style = this.getPointStyle(this.list[i].byx2 + '1.png', this.list[i].name, 0.3)
              let feature_ = this.vectorLayer.getSource().getFeatureById(this.list[i].id)
              feature_.setStyle(style)
              break
          }
      }
      // this.$nextTick(()=>{
      //   this.isAdd=JSON.parse(JSON.stringify(boolean))
      // })

      //this.initTreeStationMap()
      // for (let i in this.list) {
      //     if (this.list[i].key === now.key) {
      //         Vue.set(this.list, i, now)
      //
      //         break
      //     } else if (this.list[i].id === now.id) {
      //         Vue.set(this.list, i, now)
      //         break
      //     }
      // }
    },
    transformation (now) { //2D3D转换
      this.transformationSta = now
    },
    // 移动资源位坐标
    changeResourceLocation (id, x, y) {
      // console.log('changeResourceLocation:', id, x, y)
      this.list.forEach(res => {
        if (res.id == '') {
          if (res.nid == id) {
            // console.log('移动坐标1：', res.name, res.xpoint, res.ypoint)
            res.coordinateX = x
            res.coordinateY = y
            // console.log('移动坐标2：', res.name, res.xpoint, res.ypoint)
          }
        } else {
          if (res.id == id) {
            // console.log('移动坐标1：', res.name, res.xpoint, res.ypoint)
            res.coordinateX = x
            res.coordinateY = y
            // console.log('移动坐标2：', res.name, res.xpoint, res.ypoint)
          }
        }
      })
    },
    editDetail (id, disabled) {
      // let resource = null
      if (!disabled) {
        this.list.forEach(res => {
          if (res.id == '') {
            if (res.nid == id) {
              this.$refs.addOrUpdate.init(JSON.parse(JSON.stringify(res)), disabled)
              this.activeChooseResourceBox(res.nid, 'nid')
            }
          } else {
            if (res.id == id) {
              this.$refs.addOrUpdate.init(JSON.parse(JSON.stringify(res)), disabled)
              this.activeChooseResourceBox(res.id, 'id')
            }
          }
        })
      } else {
        this.list.forEach(res => {
          if (res.id == id) {
            this.$refs.addOrUpdate.init(JSON.parse(JSON.stringify(res)), disabled)
            this.activeChooseResourceBox(res.id, 'id')
          }
        })
      }

      //
    },
        //新建资源点对象
    getNewBox(item, j, w, src) {
        let id = getUUID()
        return {
        id: id,
        key: id,
        level: 6,
        name: item.name,
        password: '',
        port: '',
        remark: '',
        lineId: this.checkedData.lineId,
        lineName: this.checkedData.lineName,
        stationId: this.checkedData.stationId,
        stationName: this.checkedData.stationName,
        subCode: this.checkedData.subCode,
        subSystem: this.checkedData.subSystem,
        tierId: this.checkedData.tierId,
        layerId: this.checkedData.tierId,
        tierName: this.checkedData.tierName,
        type: item.id,
        icon: item.value,
        iconPath: '',
        username: 'admin',
        // xpoint: x || '100',
        // ypoint: y || '100',
        width: 200,
        coordinateX: j || '',
        coordinateY: w || '',
        byx2: src,
        isLine: 0,
        //生成资源点编码的前缀
        codeType: item.remark,
        deleted: 0,
        addOrUpdate: 'save'
      }
    },
          //添加点
    addPoint(coordinate) {
        let bean = this.getNewBox(this.iconStyle, parseFloat(coordinate[0]).toFixed(2), parseFloat(coordinate[1]).toFixed(2), this.iconStyle.value)
              //新建一个要素ol.Feature
              let newFeature = new OlFeature({
                  geometry: new OlGeomPoint(coordinate) //几何信息
              })
              newFeature.setStyle(this.getPointStyle(this.iconStyle.value + '.png', this.iconStyle.name)) //设置要素样式
              newFeature.setId(bean.key)
              this.vectorLayer.getSource().addFeature(newFeature)
              //添加需要拖动的点
              this.modify.source_.addFeature(newFeature)
        return bean
    },
    addSpot () {
      //this.isAdd = true
      if (this.listItem) {
        this.cleanStyle()
        this.listItem = null
      }

        this.iconClass = 'el-icon-xungengdian1'
        this.drawType = 'None'
        this.map.removeInteraction(this.draw)
        this.drawType = 'Point'
        this.iconStyle = {
          id: getUUID(),
          name: '巡查点',
          value: 'xungengdian',
          parentId: this.checkedData.sId
        }
      //   let arr = {
      //       id: '',
      //       name: '',
      //       layerId: this.checkedData.layerId,
      //       stationId: this.checkedData.sId,
      //       nid: this.list.length,
      //       coordinateY: '0',
      //       coordinateX: '0',
      //       active: false,
      //       level: 6
      //   }
      // this.list.push(arr)
      // this.$refs.queryDetail.init(arr, false)
      // this.activeChooseResourceBox(arr.nid, 'nid')
    },
    // 修改
    updateSpot() {
      //console.log('点击修改', this.listItem.name)
      if (this.listItem) { this.$refs.addOrUpdate.init(this.listItem, 1) } // 1 编辑
    },
    // 删除
    removeSpot () {
      this.isAdd = false
      //  console.log(this.list)
      for (let i in this.list) {
          if (this.list[i].id === this.listItem.id) {
              this.list[i].deleted = 1
              let newFeature = this.vectorLayer.getSource().getFeatureById(this.listItem.id)
              if (newFeature) {
                  this.vectorLayer.getSource().removeFeature(newFeature)
                  this.listItem = null
              }
              break
          }
      }

     //    if (this.listItem !== null) {
     //           let itemId = this.listItem.id
     // if (itemId) {
     //      this.$confirm('此操作将删除选中巡查点, 是否继续?', '提示', {
     //        confirmButtonText: '确定',
     //        cancelButtonText: '取消',
     //        type: 'warning'
     //          }).then(() => {
     //                this.$http({
     //                  url: this.$http.adornUrlEq('/epPatrolPoint/delete'),
     //                  method: 'post',
     //                  data: { id: itemId, stationId: this.checkedData.sId }
     //                }).then(data => {
     //                  if (data && data.code === 0) {
     //                    this.$message.success('删除成功')
     //                    this.initTreeStationMap()
     //                    this.listItem = null
     //                    this.iconClass = 'el-icon-xungengdian'
     //                  } else {
     //                    this.$message.error('删除失败')
     //                  }
     //                })
     //          })
     //   }
     //    }

            // this.list.forEach((res, index) => {
        //   if (res.active) {
        //     this.$http({
        //       url: this.$http.adornUrlEq('/epPatrolPoint/delete'),
        //       method: 'post',
        //       data: { id: res.id }
        //     }).then(data => {
        //       if (data && data.code === 0) {
        //         this.$message.success('删除成功')
        //         this.initTreeStationMap()
        //       } else {
        //         this.$message.error('删除失败')
        //       }
        //     })
        //   }
        // })
    }
  },
  directives: {
    //拖拽&&缩放指令
    drag: {
      bind: (el, binding) => {
        // console.log(el)
        // console.log('binding:', binding)
        // console.log(binding.value)
        //绑定默认样式
        el.style.zIndex = 9
        el.style.opacity = 1
        // el.style.backgroundColor = 'rgba(0,0,0,1)'
        //如果为编辑状态
        if (binding.value || binding.value === undefined) {
          //定义该元素的 top left width height
          let x, y, w, h
          //鼠标的起始和结束坐标
          let cx_start, cy_start, cx_end, cy_end
          //鼠标双击弹出信息框
          el.ondblclick = e => {
            // alert('新增/编辑信息弹出框')
            // console.log('el', el)
            // console.log('that', that)
            //编辑资源位信息
            if (that.editable) {
              that.editDetail(el.id, false)
            } else {
              that.editDetail(el.id, true)
            }
          },
            //判断鼠标样式
            el.onmousemove = e => {
              //获取鼠标当前位置
              let cx_now = e.clientX
              let cy_now = e.clientY
              //获取div右下角相对浏览器的位置
              let {
                top: el_top,
                left: el_left
                // width: el_width,
                // height: el_height
              } = el.getBoundingClientRect()

              // let el_bottom_height = el_top + el_height;
              // let el_right_width = el_left + el_width;
              //判断鼠标是否在div下边界
              // let mouse_in_bottom =
              //   cy_now <= el_bottom_height + 5 && cy_now >= el_bottom_height - 5;
              //判断鼠标是否在div右边界
              // let mouse_in_right =
              //   cx_now <= el_right_width + 5 && cx_now >= el_right_width - 5;
              // if (mouse_in_bottom && mouse_in_right) {
              // el.style.cursor = "se-resize";
              // } else if (mouse_in_right) {
              // el.style.cursor = "e-resize";
              // } else if (mouse_in_bottom) {
              // el.style.cursor = "s-resize";
              // } else {
              el.style.cursor = 'move'
              // }
            }
          el.onmousedown = e => {
            //div1   所有图标，去除选中颜色，当前选中给予选中颜色边框
            // var divs = document.getElementsByClassName('div1')
            // let boxs = this.$refs.drag
            // for (var i = 0; divs.length > i; i++) {
            // divs[i].style.border = '0'
            // }
            //当前选中给予选中颜色边框
            // el.style.border = '1px solid red'
            // console.log(divs)
            //border: 1px solid red;
            let mouse = el.style.cursor
            //更改默认样式
            // el.style.backgroundColor = 'rgba(0,0,0,.5)'
            el.style.opacity = 0.5
            el.style.zIndex = 99
            //对象解构赋值
            let { left: el_x, top: el_y, width: el_w, height: el_h } = window.getComputedStyle(el)
            // let { left: el_x, top: el_y } = window.getComputedStyle(el);
            x = el_x
            y = el_y
            w = el_w
            h = el_h
            // console.log(x, y, w, h)
            cx_start = e.clientX
            cy_start = e.clientY
            //绑定移动事件
            document.onmousemove = e => {
              cx_end = e.clientX
              cy_end = e.clientY
              //默认左下方向配置
              let x_move = cx_end - cx_start
              let y_move = cy_end - cy_start
              let direct = ['width', 'height']
              let pos = [w, h]
              let move = [x_move, y_move]
              let limit = 50
              //判断鼠标的类型进行对应的操作
              switch (mouse) {
                // case "e-resize":
                //   direct = ["width"];
                //   pos = [w];
                //   move = [x_move];
                //   break;
                // case "s-resize":
                //   direct = ["height"];
                //   pos = [h];
                //   move = [y_move];
                //   break;
                case 'move':
                  direct = ['left', 'top']
                  pos = [x, y]
                  limit = 0
                  break
              }
              handle_div(direct, pos, move, limit)
            }
            //取消移动事件
            document.onmouseup = e => {
              //还原默认样式
              el.style.zIndex = 9
              // el.style.backgroundColor = 'rgba(0,0,0,1)'
              el.style.opacity = 1
              document.onmousemove = null
              //移动结束后弹出修改弹窗
              // that.addOrUpdateHandle(el.id, parseInt(x), parseInt(y))
            }
            /**
             * 操作DOM位置和大小方法
             * @param direct 方向
             * @param pos 尺寸/坐标
             * @param move 拖动距离
             * @param limit 限定范围
             */
            function handle_div (direct, pos, move, limit) {
              if (that.editable) {
                that.changeResourceLocation(el.id, parseInt(pos[0]) + parseInt(move[0]), parseInt(pos[1]) + parseInt(move[1]))
                for (let i = 0; i < direct.length; i++) {
                  let val = parseInt(pos[i]) + move[i]
                  val = val <= limit ? limit : val
                  el.style[direct[i]] = val + 'px'
                }
              }
            }
          }
        } else {
          el.style.cursor = 'default'
          //移除点击事件
          el.onmousedown = null
          el.onmousemove = null
        }
      }
    }
  }

}
</script>
<style lang='scss' scoped>
  .el-icon-xungengdian1, .el-icon-xungengdian{
    width:50px;
    height: 50px;
  }
    .dic_tree {
        background: #f4f4f4;
        font-size: 14px;
        transform: translateX(-6px);
        margin-top: 20px;
    }
    // .dic_tree /deep/ .el-tree-node__content {
        // padding-left: 0px !important;
    // }

    .dic_tree /deep/ .el-tree-node {
        position: relative;
        padding-left: 16px;
    }

    .dic_tree /deep/ .el-tree-node__children {
        padding-left: 8px;
    }

    .dic_tree /deep/ .el-tree-node :last-child:before {
        height: 38px;
    }

    .dic_tree /deep/ .el-tree > .el-tree-node:before {
        border-left: none;
    }

    .tree-container /deep/ .el-tree > .el-tree-node:after {
        border-top: none;
    }

    .dic_tree /deep/ .el-tree-node:before {
        content: "";
        left: -4px;
        position: absolute;
        right: auto;
        border-width: 1px;
    }

    .dic_tree /deep/ .el-tree-node:after {
        content: "";
        left: -4px;
        position: absolute;
        right: auto;
        border-width: 1px;
    }

    .dic_tree /deep/ .el-tree-node:before {
        border-left: 1px dashed #bfbfbf;
        bottom: 0px;
        height: 100%;
        top: -26px;
        width: 1px;
    }

    .dic_tree /deep/ .el-tree-node:after {
        border-top: 1px dashed #bfbfbf;
        height: 20px;
        top: 12px;
        width: 36px;
    }
    .tree-container /deep/ .el-tree > .el-tree-node:after {
        border-top: none;
    }

    .tree-container {
        /* 树的parent，样式自定 */
    }
    .dic_tree /deep/ .el-tree-node__expand-icon.expanded {
        transform: rotate(0deg);
        -webkit-transform: rotate(0deg);
    }
    .dic_tree /deep/ .el-icon-caret-right:before {
        background: url("../../../assets/images/add.png");
        content: "";
        display: block;
        width: 18px;
        height: 18px;
        font-size: 18px;
        background-size: 18px;
    }
    .dic_tree
    /deep/
    .el-tree-node__expand-icon.expanded.el-icon-caret-right:before {
        background: url("../../../assets/images/sub.png");
        content: "";
        display: block;
        width: 18px;
        height: 18px;
        font-size: 18px;
        background-size: 18px;
    }
.dic_tree /deep/.el-tree-node__content > .el-tree-node__expand-icon{
  padding:0 2px 0 0;
}
    .dic_tree /deep/.el-tree-node__expand-icon.is-leaf::before {
        display: none;
    }
    .dic_tree /deep/.is-leaf.el-tree-node__expand-icon.el-icon-caret-right {
      // margin-left: -15px !important;
    }
</style>
<style lang='scss'>
.inputWidth {
  width: 130px;
}

.resource-container {
  width: 100%;
  height: 100%;
  position: relative;
  border: 0px solid black;
  overflow: auto;
  .span-box {
    height: 48px;
    width: 60px;
    font-size: 12px;
    border-radius: 5px;
    position: absolute;
    // left: 0;
    // top: 0;
    .span-info {
      line-height: 0px;
      display: inline-block;
      width: 100px;
      transform: translate(-17px,-10px);
    }
  }
  .span-box.el-icon-wq-qiangji1 {
    height: 60px;
    width: 72px;
  }
  .span-box.el-icon-wq-qiuji1 {
    height: 60px;
    width: 72px;
  }
  .active {
    background-color: #fd949d;
  }
  .pointer {
    cursor: pointer !important;
  }
}

.tier-btn {
  .active-tier {
    background-color: #409eff;
    color: #ffffff;
  }
}
.patrol_spot {
  .el-tree {
    // overflow: auto;
    background: #f4f4f4;
    font-size: 12px;
    overflow-y: auto;
    height: 675px;
  }
  .el-card__body {
    padding: 0;
  }
  .el-card {
    height: 99%;
    background: #f4f4f4;
  }
  .el-tree--highlight-current
    .el-tree-node.is-current
    > .el-tree-node__content {
    background-color: #f4f4f4 !important;
    color: #fff !important;
    .el-button--text {
      color: #fff;
    }
    .custom-tree-node {
      background-color: #35aff8 !important;
    }
  }

  .patrol_spot_left_top {
    height: 50px;
    background: #e1edf4;
    padding-left: 10px;
    .patrol_spot_left_topL {
      height: 40px;
      padding-top: 10px;
      float: left;
      div {
        height: 40px;
        float: left;
        padding: 0 10px 0 10px;
        border: 1px solid transparent;

        line-height: 40px;
        cursor: pointer;
        font-size: 14px;
        span {
          color: #35aff8;
        }
      }
      div.on {
        background: #fff;
        border: 1px solid #c3c3c3;
        border-bottom: none;
        font-family: Microsoft YaHei;
        font-weight: 400;
      }
    }
    .patrol_spot_left_topR {
      float: right;
      margin-top: 10px;
      .el-input {
        width: 109px;
      }
    }
  }
  .patrol_spot_right_button {
    height: 50px;
    width: 100%;
    background: #e3e4e6;
    patrol_spot_right_button_l {
      margin-left: 20px;
    }
    .el-button--primary.is-plain {
      margin-top: 10px;
      background: #ced1d6;
      border: none;
      color: #656565;
    }
    .tier-btn .active-tier {
      background-color: #409eff;
      color: #ffffff;
    }
    .el-button.is-plain:hover {
      background: #fff;
      border-color: #32a5ea;
      color: #32a5ea;
    }
    .patrol_spot_right_button_r {
      float: right;
      margin-top: 10px;
      width: 95px;
      height: 26px;
      font-size: 12px;
      line-height: 25px;
      overflow: hidden;
      border-radius: 13px;
      background: #ced1d6;
      border: 1px solid rgba(0, 0, 0, 0.2);
      box-shadow: 0px 1px 0px 1px rgba(255, 255, 255, 0.25),
        0px 2px 4px 0px rgba(0, 0, 0, 0.1);
      div {
        width: 46px;
        height: 24px;
        float: left;
        text-align: center;
        cursor: pointer;
      }
      div.on {
        background: #45b5f8;
        color: #fff;
        border-radius: 13px;
        border: 1px solid rgba(23, 41, 71, 0.5);
        box-shadow: 0px 1px 0px 0px rgba(255, 255, 255, 0.3),
          0px 2px 0px 0px rgba(255, 255, 255, 0.15);
      }
    }
  }
}
.ol-overviewmap .ol-overviewmap-map{
  height: 110px!important;
}
</style>
