<template>
  <div class="patrol_plan_dialog">
    <el-dialog  width="90%" :fullscreen="true" :close-on-click-modal="false" :visible.sync="visible" :modal-append-to-body="false" :modal="false" top="5vh" :before-close="handleClose">
      <span slot="title" class="title-bold">{{title}}巡查计划</span>
      <el-row style="padding-bottom:15px;" :gutter="10">
        <el-col :span="4">
          <div class="patrol_line_left">
            <div class="patrol_line_left_top">巡查线路</div>
            <div class="left_list">
              <div :class="{ 'left_list_row_on': item.on, 'left_list_row': true }" v-for="(item, index) in leftListData"
                   :key="index" @click="leftListRowClickQH(item,index)">
                <div class="left_list_row_name" :title="item.name">{{ item.name,16 | ellipsis}}</div>
              </div>
            </div>
          </div>
        </el-col>
        <el-col :span="14">
          <div class="patrol_line_center" style="position: relative;">
            <div class="patrol_line_right_button">
              <el-button v-show='checkedData.tierId===item.id' type="primary" size="small" plain
                         :class="[checkedData.tierId===item.id?'active-tier':'']" style="float:left;margin:3px 0 0 10px"
                         v-for="item in mapList" :key="item.id">
                {{ item.name }}
              </el-button>
            </div>
            <div id="map" style="width: 100%;height: 600px;position: relative;"></div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="patrol_line_right">
            <div class="patrol_line_left_top">巡查计划</div>
            <el-form :model="dataForm" :rules="dataRule" ref="dataForm" :inline="true" label-width="100px">
              <el-form-item label="计划名称:" prop="name">
                <el-input v-model="dataForm.name"></el-input>
              </el-form-item>
              <el-form-item label="巡查员:" prop="patrollerId">
                <el-select v-model="dataForm.patrollerId" placeholder="请选择" clearable>
                  <el-option v-for="item in restaurants" :key="item.value" :label="item.name"
                             :value="item.id"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="开始时间:" prop="startTime">
                <!-- <el-date-picker type="datetime" :disabled="cloneStatus" class="inputWidth" style="width:175px;" v-model="dataForm.startTime" placeholder="选择日期时间" clearable ></el-date-picker> -->
                <el-date-picker type="datetime" class="inputWidth" style="width:175px;" v-model="dataForm.startTime"
                                placeholder="选择日期时间" clearable></el-date-picker>
              </el-form-item>
              <el-form-item label="结束时间" prop="endTime">
                <!-- <el-date-picker type="datetime" :disabled="cloneStatus" class="inputWidth" style="width:175px;" v-model="dataForm.endTime" placeholder="选择日期时间" clearable ></el-date-picker> -->
                <el-date-picker type="datetime" class="inputWidth" style="width:175px;" v-model="dataForm.endTime"
                                placeholder="选择日期时间" clearable></el-date-picker>
              </el-form-item>
              <el-form-item label="巡查周期:" prop="circle" required>
                <!-- <el-select v-model="dataForm.circle" :disabled="cloneStatus" placeholder="请选择"> -->
                <el-select v-model="dataForm.circle" placeholder="请选择">
                  <el-option v-for="item in options" :key="item.value" :label="item.label"
                             :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="备注:" prop="remark">
                <!-- <el-input v-model="dataForm.remark" resize="none" :disabled="cloneStatus" type="textarea" placeholder="请输入内容" maxlength="100" show-word-limit ></el-input> -->
                <el-input v-model="dataForm.remark" resize="none" type="textarea" placeholder="请输入内容" maxlength="100"
                          show-word-limit></el-input>
              </el-form-item>
            </el-form>
            <p style="padding-left:20px">
              到达时间
              <span style="color:#C3C3C3">(按时间排序,实际到达允许{{ waveTime }}分钟时间波动)</span>
            </p>
            <el-table :data="dataList" style="width: 100%;">
              <el-table-column type="index" header-align="center" align="center" width="80"
                               label="序号"></el-table-column>
              <el-table-column prop="pointName" header-align="center" align="center" label="巡查点"></el-table-column>
              <el-table-column header-align="center" align="center" label="到达时间">
                <template slot-scope="scope">
                  <!-- <el-time-picker v-model="scope.row.time" :disabled="!editStatus && title != '复制'" @change="timeChange(scope.row)" ></el-time-picker> -->
                  <el-time-picker v-model="scope.row.time" @change="timeChange(scope.row)"></el-time-picker>
                </template>
              </el-table-column>
              <!-- <el-table-column header-align="center" align="center" width="50" label="操作">
                <template slot-scope="scope">
                  <el-button @click="deleData(scope.row,scope.$index)" type="text">删除</el-button>
                </template>
              </el-table-column> -->
            </el-table>
          </div>
        </el-col>
      </el-row>
      <span class="dialog-footer" slot="footer">
        <el-button type="primary" @click="cancel">取消</el-button>
        <el-button type="primary" @click="saveClick" v-prevent-re-click>保存</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 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'

export default {
  computed: {
    ...mapState('d2admin/user', ['info'])
  },
  filters: {
    ellipsis(value, len) {
      if (!value) return ''
      if (value.length > len) {
        return value.slice(0, len) + '...'
      }
      return value
    }
  },
  data() {
    return {
      nowId: '',
      imgLayerList: [],
      controlList: [],
      lineArr: [
        // [-639.46, 441.91],
        // [-264.16, 223.53],
        // [314.96, 218.68]
      ], //线坐标集合
      idArr: [
        // '559a476a81b941f78ef6dca88e48f2bb',
        // 'cfc9e32598124401b09bbdea4ab59ea3',
        // '4afc3bd2307b4ef18336556a8ea1bd0d'
      ],
      lineFeature: null,
      stationMap: '',
      lineDomList: [],
      lineData: [],
      waveTime: '0',
      editStatus: true,
      cloneStatus: false,
      leftListData: [{ name: '线路1' }, { name: '线路2' }],
      leftListOnData: null,
      urlPath: window.CONFIG.urlPath,
      spotData: [],
      spotDataList: [],
      spotOnData: [],
      visible: false,
      dataForm: {
        name: '',
        patrollerName: '',
        startTime: '',
        endTime: '',
        circle: '1',
        remark: '',
        patrollerId: ''
      },
      activeName: '1',
      title: '新增',
      restaurants: [],
      dataRule: {
        name: [
          { required: true, message: '请输入计划名称', trigger: 'change' },
          {
            min: 1,
            max: 20,
            message: '长度在 1 到 20 个字符',
            trigger: 'blur'
          }
        ],
        patrollerId: [
          { required: true, message: '请选择巡查员', trigger: 'change' }
          // { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
        ],
        startTime: {
          required: true,
          message: '请选择开始时间',
          trigger: 'change'
        },
        endTime: {
          required: true,
          message: '请选择结束时间',
          trigger: 'change'
        }
      },
      list: [],
      mapList: [
        { name: '线路1', id: '1' },
        { name: '线路1', id: '2' }
      ],
      nodeKey: 'id',
      defaultExpandedKeys: [],
      defaultProps: {
        children: 'children',
        label: 'name',
        level1: 'level'
      },
      treeData: [],
      dataList: [],
      dataAllList: [],
      checkedData: {
        tierId: '',
        tierName: '',
        sId: localStorage.getItem('stationId'),
        subCode: '02'
      },
      stationId: localStorage.getItem('stationId'),
      options: [
        {
          value: '1',
          label: '一天'
        },
        {
          value: '7',
          label: '一周'
        },
        {
          value: '30',
          label: '一月'
        }
      ]
    }
  },
  created() {
    this.getStationList()
    this.getFluctuationTime()
  },
  methods: {
    init(sId, res, title) {
      // console.log(res)
      this.visible = true
      this.checkedData.sId = sId
      // this.initTreeStationMap()
      if (title) {
        this.dataForm = { ...res }
        this.dataForm.circle = res.circle.toString()
        this.title = title
        if (title == '复制') {
          this.cloneStatus = true
        }
        this.editStatus = false
      } else {
        this.title = '新增'
        this.editStatus = true
        this.cloneStatus = false
        this.dataForm = {
          name: '',
          patrollerName: '',
          startTime: '',
          endTime: '',
          circle: '1',
          remark: '',
          patrollerId: ''
        }
        if (this.$refs.dataForm) this.$refs.dataForm.resetFields()
      }
      if (title == '编辑' || title == '复制') {
        this.nowId = res.lineId
      }
      this.lineData = []
      this.lineDomList = []
      this.initTreeStationMap()
    },
    // 初始化地图
    initMap(url) {
      let mapList = this.mapList
      this.imgurl = url
      // 计算静态地图映射到地图上的范围
      // let extent = [-1100, 110, 1460, 820]
      let extent = [-600, -100, 800, 1000]

      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: 1.5,
          maxZoom: 3.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])

      if (this.title == '新增') {
        this.imgLayerList[0].setVisible(true) //初始第一个显示
        this.leftListRowClick(this.leftListData[0], 0) //默认选中第一个
      } else {
        let nowId = this.nowId
        let nowIndex = this.leftListData.findIndex((e) => e.id == nowId)
        let imgIndex = this.mapList.findIndex((e) => e.id == this.leftListData[nowIndex].layerId)
        this.imgLayerList[imgIndex].setVisible(true)
        this.leftListRowClick(this.leftListData[nowIndex], nowIndex)
      }
    },
    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])
      })
    },
    // 改变层级和鹰眼图
    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)
        }
      }
    },
    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) {
          //修改选中样式

          if (this.edirStatus) {
            feature_.setStyle(style2)
            console.log('当前选中', item)
          }
          // if(!this.editable) this.openAddOrUpdate(item)  //未编辑状态下 点击查看
          // if (flag) this.openAddOrUpdate(item)
        } else {
          //清除选中以外的样式
          feature_.setStyle(style)
        }
      }
      //  else {
      //     //获取新增的feature对象
      //     let newFeature = this.vectorLayer.getSource().getFeatureById(item.key)

      //     if (newFeature) {
      //         if (newFeature === feature ) {
      //             newFeature.setStyle(style2)
      //         console.log(222);

      //             // if (flag) this.openAddOrUpdate(item) //查看
      //           //  if (flag)   this.$refs.queryDetail.init(item, false)

      //         } else {
      //             //清除选中以外的样式
      //             newFeature.setStyle(style)

      //         }
      //     }
      // }
    },
    handleClick(tab) {
      //左侧tab切换
    },
    addLine() {
      console.log(this.checkedData.sId, '新增站点的id')
      this.$refs.queryDetail.init(this.checkedData.sId)
    },
    getFluctuationTime() {
      this.$http({
        url: this.$http.adornUrlEq('/epPatrolPlan/getFluctuationTime'),
        method: 'get',
        params: { stationId: this.stationId }
      }).then((data) => {
        this.waveTime = data.time
      })
    },
    initTreeStationMap() {
      //获取巡查路线
      this.$http({
        url: this.$http.adornUrlEq('/epPatrolLine/list'),
        method: 'post',
        data: {
          stationId: this.checkedData.sId
        }
      })
          .then((data) => {
            if (data && data.code === 0) {
              this.leftListData = data.nodes

              if (this.editStatus) {
                this.leftListOnData = this.leftListData[0]
                this.leftListData[0].on = true
                if (this.leftListData[0].children) {
                  this.leftListData[0].children.forEach((res) => {
                    this.spotOnData.push(res.id)
                  })
                  // console.log("this.spotOnData", this.spotOnData);
                } else {
                  this.spotOnData = []
                }
              } else {
                this.leftListData.forEach((res) => {
                  if (res.id == this.dataForm.lineId) {
                    this.leftListOnData = res
                    this.getDataList()
                    res.on = true
                    if (res.children) {
                      res.children.forEach((res) => {
                        this.spotOnData.push(res.id)
                      })
                    } else {
                      this.spotOnData = []
                    }
                  }
                })
              }
            }
          })
          .then(() => {
            this.epPatrolPointList()
          })
    },
    epPatrolPointList() {
      //底图以及点位信息
      this.$http({
        url: this.$http.adornUrlEq('/epPatrolPoint/list'),
        method: 'post',
        data: {
          stationId: this.checkedData.sId
        }
      })
          .then((data) => {
            if (data && data.code === 0) {
              data.nodes.forEach(element => {
                element.readPath = this.urlPath + element.filePath
              })
              this.spotDataList = data.nodes
              // console.log("底图 点位信息", data.nodes);
              this.spotData = JSON.parse(JSON.stringify(this.spotDataList))
              this.mapList = data.nodes
              this.checkedData.tierId = this.mapList[0].id
              this.checkedData.tierName = this.mapList[0].name
              this.stationMap = this.mapList[0]
            }
          })
          .then(() => {
            //点位上图
            // if (this.leftListData[0]) this.leftListRowClick(this.leftListData[0], 0)
            this.showResourceByMapId()
            if (!this.map) {
              this.initMap()
            } else {
              if (this.title == '新增') {
                this.imgLayerList[0].setVisible(true) //初始第一个显示
                this.leftListRowClick(this.leftListData[0], 0) //默认选中第一个
              } else {
                let nowId = this.nowId
                let nowIndex = this.leftListData.findIndex((e) => e.id == nowId)
                let imgIndex = this.mapList.findIndex((e) => e.id == this.leftListData[nowIndex].layerId)
                this.imgLayerList[imgIndex].setVisible(true)
                this.leftListRowClick(this.leftListData[nowIndex], nowIndex)
              }
            }
          })
    },
    showResourceByMapId() {
      //选中地图
      // this.mapList.forEach((map) => {
      //   console.log("map", map, "====", this.leftListOnData);
      //   if (
      //     this.leftListOnData.children &&
      //     this.leftListOnData.children[0].layerId == map.id
      //   ) {
      //     // this.changeMap(item)
      //     this.checkedData.tierId = map.id;
      //     this.checkedData.tierName = map.name;
      //     this.stationMap = map;
      //     this.lineData = [];
      //     this.lineDomList = [];
      //   }
      // });

      this.spotData.forEach((spotRes) => {
        if (this.checkedData.tierId == spotRes.id) {
          this.list = spotRes.children || []
        }
      })
      this.lineData = []
      this.lineDomList = []
      if (this.leftListOnData.children) {
        this.leftListOnData.children.forEach((itemRes) => {
          this.list.forEach((listRes) => {
            if (itemRes.id == listRes.id) {
              Vue.set(listRes, 'active', true)
              this.lineData.push(listRes)
            }
          })
          if (this.editStatus && !this.cloneStatus) {
            this.dataList.push({
              pointId: itemRes.id,
              pointName: itemRes.name,
              arrivalTime: '',
              time: null
            })
          }
        })
      }

      this.forLine()
    },
    getDataList() {
      this.$http({
        url: this.$http.adornUrlEq('/epPatrolPlan/getId'),
        method: 'get',
        params: {
          id: this.dataForm.id,
          stationId: this.checkedData.sId
        }
      }).then((data) => {
        if (data && data.code === 0) {
          if (this.cloneStatus) this.dataForm.id = ''
          this.dataList = []
          data.bean.pointList.forEach((res) => {
            this.dataList.push({
              id: '',
              pointId: res.pointId,
              pointName: res.pointName,
              arrivalTime: res.arrivalTime,
              time: new Date('2020-07-01 ' + res.arrivalTime)
            })
          })
        }
      })
    },
    // changeMap(map) {
    //   this.checkedData.tierId = map.id;
    //   this.checkedData.tierName = map.name;
    //   this.stationMap = map;
    //   this.lineData = [];
    //   this.lineDomList = [];
    //   this.showResourceByMapId();
    // },
    querySearch(queryString, cb) {
      let restaurants = this.restaurants
      let results = queryString
          ? restaurants.filter(this.createFilter(queryString))
          : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
            0
        )
      }
    },
    timeChange(row) {
      row.arrivalTime = this.formatTime(row.time, 'hh:mm:ss')
    },
    getStationList() {
      this.dataListLoading = true
      this.$http({
        url: this.$http.adornUrlEq('/sysUser/getAllSysUser'),
        method: 'get',
        params: { stationId: localStorage.getItem('stationId') }
      }).then((data) => {
        data.users.forEach((res) => {
          this.restaurants.push({
            value: res.nameMobile,
            id: res.patrollerId,
            name: res.patrollerName
          })
        })
      })
    },
    handleSelect(item) {
      this.dataForm.patrollerName = item.name
      this.dataForm.patrollerId = item.id
    },
    deleData(row, $index) {
      this.dataList.splice($index, 1)
    },
    // 画线
    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)
      }
    },
    leftListRowClickQH(item, index) {
      if (this.title !== '新增') {
        return
      }
      this.leftListRowClick(item, index)
    },
    leftListRowClick(item, index) {
      this.checkedData.tierId = item.layerId
      //任务列表点击任务
      if (item.children) this.changeVectorLayer(item.children)

      // this.showResourceByMapId()

      if (item.layerId) {
        this.changeImgControl(item.layerId) // 切换图层
      }

      if (item.coordinate) { // 回显线路
        this.drawLine(item.coordinate)
      } else {
        this.map.removeLayer(this.vectorLayer)
        this.map.removeLayer(this.lineVectorLayer)
      }

      if (!this.editStatus) {
        return false
      }
      //切换图层
      // this.mapList.forEach(map => {
      //   // console.log('map', map, '====', item)
      //   if (item.children && item.children[0].layerId == map.id) {
      //     // this.changeMap(item)
      //     this.checkedData.tierId = map.id
      //     this.checkedData.tierName = map.name
      //     this.stationMap = map
      //     this.lineData = []
      //     this.lineDomList = []
      //   }
      // })

      // this.spotData = JSON.parse(JSON.stringify(this.spotDataList))
      this.leftListData.forEach((res, i) => {
        if (index == i) {
          Vue.set(res, 'on', true)
          this.leftListOnData = res
        } else {
          Vue.set(res, 'on', false)
        }
      })

      this.lineData = []
      this.lineDomList = []
      this.dataList = []
      if (this.leftListOnData.children) {
        this.leftListOnData.children.forEach((itemRes) => {
          this.list.forEach((listRes) => {
            if (itemRes.id == listRes.id) {
              Vue.set(listRes, 'active', true)
              this.lineData.push(listRes)
            }
          })
          this.dataList.push({
            pointId: itemRes.id,
            pointName: itemRes.name,
            arrivalTime: '',
            time: null
          })
        })
      }
      this.forLine()
    },
    saveClick() {
      this.$refs.dataForm.validate((valid) => {
        if (valid) {
          if (this.dataForm.startTime > this.dataForm.endTime) {
            this.$message.warning('开始时间不能大于结束时间')
            return false
          }
          let num = 0
          let warn = false
          if (!this.dataList || this.dataList.length === 0) {
            this.$message.warning('所选择的巡查路线没有设置巡查点')
          }
          this.dataList.forEach((res) => {
            if (!warn) {
              num++
              if (!res.time) {
                this.$message.warning('请选择巡查时间')
                warn = true
                return false
              }
              if (num == this.dataList.length) {
                this.saveSet()
              }
            }
          })
        }
      })
    },
    saveSet() {
      let url = ''
      if (this.title == '编辑') {
        url = this.$http.adornUrlEq('/epPatrolPlan/update')
      } else {
        url = this.$http.adornUrlEq('/epPatrolPlan/save')
      }
      this.$http({
        url: url,
        method: 'post',
        data: {
          id: this.dataForm.id,
          stationId: this.checkedData.sId,
          lineId: this.leftListOnData.id,
          lineName: this.leftListOnData.name,
          name: this.dataForm.name,
          patrollerName: this.restaurants.filter((item) => {
            return item.id === this.dataForm.patrollerId
          })[0].name,
          patrollerId: this.dataForm.patrollerId,
          startTime: this.formatTime(
              this.dataForm.startTime,
              'yyyy-MM-dd hh:mm:ss'
          ),
          endTime: this.formatTime(
              this.dataForm.endTime,
              'yyyy-MM-dd hh:mm:ss'
          ),
          circle: this.dataForm.circle,
          remark: this.dataForm.remark,
          pointList: this.dataList
        }
      }).then((data) => {
        if (data && data.code === 0) {
          this.$message.success('保存成功')
          this.visible = false
          this.$emit('closeQ')
        }
      })
    },
    //关闭前
    handleClose() {
      this.map.removeLayer(this.vectorLayer)
      this.map.removeLayer(this.lineVectorLayer)
      this.dataList = []
      this.visible = false
    },
    //转化时间
    formatTime(date, format) {
      if (date) {
        date = new Date(date)
        var o = {
          'M+': date.getMonth() + 1, //月份
          'd+': date.getDate(), //日
          'h+': date.getHours(), //小时
          'm+': date.getMinutes(), //分
          's+': date.getSeconds(), //秒
          'q+': Math.floor((date.getMonth() + 3) / 3), //季度
          S: date.getMilliseconds() //毫秒
        }
        var fmt = format || 'yyyy-MM-dd hh:mm'
        if (/(y+)/.test(fmt)) {
          fmt = fmt.replace(
              RegExp.$1,
              (date.getFullYear() + '').substr(4 - RegExp.$1.length)
          )
        }
        for (var k in o) {
          if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length == 1
                    ? o[k]
                    : ('00' + o[k]).substr(('' + o[k]).length)
            )
          }
        }
        return fmt
      } else {
        return ''
      }
    },
    forLine() {
      // console.log('this.lineData', this.lineData)
      this.lineData.forEach((res, index) => {
        if (this.lineData[index + 1]) {
          this.setLine(res, this.lineData[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
      })
    },
    //取消
    cancel() {
      this.$confirm('确认取消?', `${this.title}巡查计划`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
          .then(() => {
            this.visible = false
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消退出'
            })
          })
    }
  }
}
</script>
<style lang='scss' scope>
.patrol_line_left {
  height: 666px;
  width: 100%;
  background: #fff;
  border: 1px solid rgba(23, 41, 71, 0.08);
  box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.2);

  .patrol_line_left_top {
    height: 40px;
    background: #eef8ff;
    padding-left: 20px;
    line-height: 40px;
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 20px;
  }
}

.patrol_line_center {
  height: 666px;
  width: 100%;
  background: #fff;
  border: 1px solid rgba(23, 41, 71, 0.08);
  box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.2);
  overflow: auto;

  .patrol_line_right_button {
    height: 40px;
    background: #eef8ff;

    .el-button {
      background-color: #d8e3ec;
      color: #000;
    }

    .el-button:hover {
      background-color: #fff;
      color: #409eff;
    }

    .active-tier {
      background-color: #409eff;
      color: #ffffff;
    }
  }
}

.patrol_line_right {
  height: 666px;
  width: 100%;
  background: #fff;
  border: 1px solid rgba(23, 41, 71, 0.08);
  box-shadow: 0px 2px 8px 0px rgba(0, 0, 0, 0.2);
  overflow: auto;

  .patrol_line_left_top {
    height: 40px;
    background: #eef8ff;
    padding-left: 20px;
    line-height: 40px;
    font-size: 14px;
    font-weight: bold;
    margin-bottom: 20px;
  }
}
</style>
<style lang='scss'>
.patrol_plan_dialog {
  .el-card {
    height: 99%;
  }

  .left_list {
    margin-top: 20px;

    .left_list_row_on {
      background-color: #35aff8 !important;
      color: #fff;
    }

    .left_list_row {
      cursor: pointer;
      height: 40px;
      background: #f6f7fb;
      padding: 0 20px;
      margin-bottom: 1px;

      .left_list_row_name {
        float: left;
        widows: 65%;
        line-height: 40px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .left_list_row_size {
        float: right;
        widows: 25%;
        padding-top: 7px;
      }
    }
  }

  // .span-box {
  //   height: 60px;
  //   width: 72px;
  // }
  .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);
    }
  }

  .el-table {
    input {
      width: 180px;
    }
  }

  .el-dialog__body {
    padding: 15px 25px !important;
  }

  .el-input,
  .el-textarea {
    width: 220px !important;
  }
}
</style>