<template>
  <div>
    <div class="head-wrap">
      <div class="header">
        <img class="logo" src="./images/logo.png" alt="">
        <div class="title">危险作业动态标识</div>
      </div>
    </div>
    <div class="conatiner">
      <div class="leftSide">
        <div class="title">作业项目</div>
        <div v-for="(item,index) in items" :key="index" :class="checkItemIndex===index?'item active':'item'" @click="checkItem(item,index)">
          <img :src="item.icon" alt="" class="icon">
          <div class="name">{{ item.name }}</div>
        </div>
      </div>
      <div class="map-warp">
        <div id="vmap" />
      </div>
      <div class="rightSide">
        <div v-if="type==1" class="remark">
          <div class="title">使用说明</div>
          <ul>
            <li>1.点击作业项目下面的图标</li>
            <li>2.点击地图绘制点</li>
            <li>3.编辑信息保存点位</li>
          </ul>
        </div>
        <div v-if="type==2||type=='drage'" class="saveForm">
          <div class="title">作业点基本信息</div>
          <div class="item">
            <div class="lable">作业项目：</div>
            <div class="content">
              <img class="icon" :src="saveForm.icon" alt="">
              <span>{{ saveForm.name }}</span>
            </div>
          </div>
          <div class="item">
            <div class="lable">名称：</div>
            <div class="content">
              <span>{{ saveForm.name }}</span>
            </div>
          </div>
          <div class="bt-wrap">
            <div class="bt save" @click="save">保存</div>
            <div class="bt margin" @click="cancel">撤销</div>
          </div>
        </div>
        <div v-if="type==3" class="deleteForm">
          <div class="title">作业点基本信息</div>
          <div class="item">
            <div class="lable">作业项目：</div>
            <div class="content">
              <img class="icon" :src="deleteForm.icon" alt="">
              <span>{{ deleteForm.name }}</span>
            </div>
          </div>
          <div class="item">
            <div class="lable">名称：</div>
            <div class="content">
              <span>{{ deleteForm.name }}</span>
            </div>
          </div>
          <div class="bt-wrap">
            <div class="bt" @click="save">保存</div>
            <div class="bt delete margin" @click="delMarker">删除</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import * as L from 'leaflet'
import '@geoman-io/leaflet-geoman-free'
import { getLayersApi, addApi, delApi, updateApi } from '@/api/aqpt/visualEditor'
import mixins from '@/mixin/mqtt.js'
import { Uint8ArrayToString } from '@/utils'
export default {
  mixins: [mixins],
  data() {
    return {
      checkItemIndex: -1,
      type: 1,
      items: [],
      saveForm: {
        icon: '',
        name: ''
      },
      deleteForm: {
        icon: '',
        name: ''
      },
      dragstartMarker: undefined,
      map: undefined,
      markerGroup: null,
      mapList: [],
      mapId: undefined,
      mapRasterLayer: require('./images/layout_cont.png'),
      layer: null,
      state: 0,
      veditId: undefined
    }
  },
  created() {
    this.init()
  },
  // beforeRouteEnter(to, from, next) {
  //   const params = window.location.href.split('?')[1].split('&')
  //   function getParams(name = 'name') {
  //     let param
  //     params.map(item => item.includes('name') ? (param = item.split('=')[1]) : '')
  //     return param
  //   }
  //   next()
  //   console.log(getParams())
  // },
  methods: {
    init() {
      // console.log(this.$route.query)
      this.initProject()
      this.$nextTick(() => {
        this.initMap()
        this.initMqtt({
          mqttResponse: this.mqttResponse
        })
      })
    },
    initProject() {
      this.items = [
        { icon: require('./images/layers/1.png'), name: '动火作业' },
        { icon: require('./images/layers/2.png'), name: '有限空间作业' },
        { icon: require('./images/layers/3.png'), name: '高处作业' },
        { icon: require('./images/layers/4.png'), name: '起重作业' },
        { icon: require('./images/layers/5.png'), name: '预热器清堵作业' },
        { icon: require('./images/layers/6.png'), name: '篦冷机清大块作业' },
        { icon: require('./images/layers/7.png'), name: '交叉作业' },
        { icon: require('./images/layers/8.png'), name: '临时用电作业' },
        { icon: require('./images/layers/9.png'), name: '动土作业' },
        { icon: require('./images/layers/10.png'), name: '断路作业' },
        { icon: require('./images/layers/11.png'), name: '防护设备拆除' },
        { icon: require('./images/layers/12.png'), name: '高温及其他危险作业' },
        { icon: require('./images/layers/13.png'), name: '盲板抽堵作业' }
      ]
    },
    checkItem(item, index) {
      if (this.state === 1) {
        this.$message('请保存后再操作！')
        return
      }
      this.checkItemIndex = index
      this.type = 2
      this.saveForm.icon = item.icon
      this.saveForm.name = item.name
      this.map.pm.enableDraw('Marker', { snappable: false, tooltips: false })// tooltips: { 'placeMarker': '点击放置标记' },
      console.log({
        ' this.map.pm.enableDraw': this.map.pm.enableDraw
      })
      this.state = 1
    },
    save() {
      if (this.type === 3) {
        // 删除表单里面的保存
        this.type = 1
      } else if (this.type === 'drage') {
        updateApi({
          'jobactivityTitle': this.layer.options.icon.options.name,
          'jobactQywzjd': this.layer._latlng.lng,
          'jobactQywzwd': this.layer._latlng.lat,
          'veditId': this.veditId,
          'typeId': this.layer.options.icon.options.typeId
        }).then(() => {
          this.type = 1
          this.checkItemIndex = -1
          this.state = 2
          this.saveForm.icon = ''
          this.saveForm.name = ''
          this.$message.success('修改成功！')
          this.dragstartMarker = undefined
          // this.getLayers()
        })
      } else {
        // 新增
        addApi({
          'jobactivityTitle': this.layer.options.icon.options.name,
          'jobactQywzjd': this.layer._latlng.lng,
          'jobactQywzwd': this.layer._latlng.lat,
          'veditId': this.veditId,
          'typeId': this.layer.options.icon.options.typeId
        }).then(() => {
          this.type = 1
          this.checkItemIndex = -1
          this.state = 2
          this.saveForm.icon = ''
          this.saveForm.name = ''
          this.$message.success('新增成功！')
          // this.getLayers()
        })
      }
    },
    cancel() {
      this.state = 2
      this.checkItemIndex = -1
      this.saveForm.icon = ''
      this.saveForm.name = ''
      if (this.type === 'drage') {
        this.type = 1
        this.dragstartMarker.marker.setLatLng(this.dragstartMarker._latlng)
        this.dragstartMarker.marker.dragging.disable()
        this.dragstartMarker = undefined
        return
      }
      this.type = 1
      if (this.layer && this.layer._leaflet_id && this.map._layers[this.layer._leaflet_id]) {
        this.map.removeLayer(this.map._layers[this.layer._leaflet_id])
      }
    },
    delMarker() {
      delApi(this.veditId).then(() => {
        this.type = 1
        this.state = 2
        this.checkItemIndex = -1
        this.deleteForm.icon = ''
        this.deleteForm.name = ''
        if (this.map._layers[this.markerId]) {
          this.map.removeLayer(this.map._layers[this.markerId])
        }
        this.$message.success('删除成功！')
        // this.getLayers()
      })
    },
    initMap() {
      this.map = L.map('vmap', {
        minZoom: 1,
        maxZoom: 3,
        center: [30, 50],
        zoom: 1,
        crs: L.CRS.Simple,
        zoomControl: false
      })
      this.setRasterLayer()
      this.mapListener()
    },
    setRasterLayer() {
      var yx = L.latLng
      var xy = function xy(x, y) {
        if (L.Util.isArray(x)) {
          return yx(x[1], x[0])
        }
        return yx(y, x)
      }
      var bounds = [xy(-330, -255), xy(330, 255)]
      L.imageOverlay(this.mapRasterLayer, bounds).addTo(this.map)
      this.map.fitBounds(bounds)
      this.getLayers()
    },
    getLayers() {
      getLayersApi().then((res) => {
        if (this.markerGroup !== null) {
          this.markerGroup?.clearLayers()
        }
        this.initMarkers(res.data)
      })
    },
    initMarkers(markerList = []) {
      const self = this
      const markers = L.layerGroup()
      const coordinates = [-100, 100]
      const options = { id: 1 }
      const icon = 'project-12'
      const tip = '盲板抽堵作业'
      const iconSize = [40.5, 49.5]
      function drawMark(option = { tip, icon, options, coordinates }) {
        const myIcon = L.icon({
          iconUrl: require(`./images/layers/${option.options.typeId}.png`),
          className: option.icon,
          iconSize: iconSize
        })
        const marker = L.marker(option.coordinates, { ...option.options, icon: myIcon, draggable: false })
          // .bindPopup(option.tip)
          .addTo(markers)
        marker.on('click', function(ev) {
          if (self.type === 'drage') {
            self.$message.success('请先确认当前标记点操作！')
            return
          }
          const id = ev.target.options?.id
          self.type = 3
          self.veditId = id
          self.markerId = ev.target._leaflet_id
          self.deleteForm.name = ev.target.options.name
          self.deleteForm.icon = require(`./images/layers/${ev.target.options.typeId}.png`)
          marker.dragging.enable()
        })
        marker.on('dragstart', function(ev) {
          const id = ev.target.options?.id
          self.type = 'drage'
          if (self.dragstartMarker === undefined) {
            self.dragstartMarker = { marker, _latlng: ev.target._latlng }
          }
          self.veditId = id
          self.markerId = ev.target._leaflet_id
          self.saveForm.name = ev.target.options.name
          self.saveForm.icon = require(`./images/layers/${ev.target.options.typeId}.png`)
        })
        marker.on('dragend', function(ev) {
          self.layer = ev.target
        })
      }
      markers.addTo(this.map)
      this.markerGroup = markers
      if (markerList && markerList.length > 0) {
        for (let i = 0; i < markerList.length; i++) {
          drawMark({
            // tip: `${markerList[i].jobactivityTitle}`,
            icon: `project-${markerList[i].typeId}`,
            coordinates: [markerList[i].jobactQywzwd, markerList[i].jobactQywzjd],
            options: { id: markerList[i].veditId, typeId: markerList[i].typeId, name: markerList[i].jobactivityTitle }
          })
        }
      }
    },
    mapListener() {
      const self = this
      this.map.on('pm:drawstart', (e) => { // 绘制开始时事件
        if (e.shape === 'Marker') {
          const iconUrl = this.saveForm.icon
          const layer = e.workingLayer
          var icon = L.icon({
            iconUrl,
            iconSize: [40.5, 49.5]
          })
          layer.setIcon(icon)
        }
      })
      this.map.on('pm:create', (e) => {
        if (e.shape === 'Marker') {
          const iconUrl = this.saveForm.icon
          const name = this.saveForm.name
          const typeId = this.checkItemIndex + 1
          const layer = e.layer
          var icon = L.icon({
            iconUrl,
            name,
            typeId,
            iconSize: [27, 33]
          })
          layer.setIcon(icon)
          layer.on('click', function(ev) {
            self.type = 3
            self.markerId = ev.target._leaflet_id
            self.deleteForm.name = ev.target.options.icon.options.name
            self.deleteForm.icon = ev.target.options.icon.options.iconUrl
          })
          self.layer = layer
          layer.addTo(this.markerGroup)
        }
        this.map.pm.disableDraw(e.shape)
      })
      this.map.on('pm:cut', () => {
        this.$message.success('裁剪完毕!')
      })
      this.map.on('pm:remove', (e) => {
        console.log(e, '移除')
      })
      // this.map.on('pm:globaldragmodetoggled', e => {
      //   console.log(e, '拖拽结束')
      // })
      this.map.on('contextmenu', () => {
        // 取消所有状态
        this.map.pm.disableGlobalDragMode()
        this.cancel()
      })
      // this.map.on('zoomend', (e) => {
      //   const scale = e.target.getZoom()
      //   const markers = document.querySelectorAll('.leaflet-marker-icon')
      //   for (let i = 0; i < markers.length; i++) {
      //     console.log()
      //     markers[i].style.transform = `${markers[i].style.transform} scale(${scale})`
      //   }
      //   console.log({ markers, scale })
      //   // this.markerGroup.eachLayer(item => { // })
      // })
    },
    mqttResponse(message) {
      const data = message ? Uint8ArrayToString(message) : ''
      this.getLayers()
      console.log({ message, data })
    }

  }
}
</script>
<style lang="scss" scoped>
.head-wrap{
  padding: 0 16px;
  background-color: #071C2B;
  .header{
    height: 50px;
    line-height: 50px;
    background-color: #193142;
    color: #fff;
    text-align: center;
    position: relative;

    .logo{
      display: block;
      height: 40px;
      position: absolute;
      left: 16px;
      top: 5px;
    }
    .title{
      font-size: 30px;
      font-weight: 600;
      letter-spacing: 4px;
    }
  }
}

.conatiner{
    height: 100%;
    height: calc(100vh - 70px);
    min-width: 1000px;
    margin: 0 auto;
    padding: 0 16px;
    box-sizing: border-box;
    background-color: #071C2B;
    color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;
    overflow-x: auto;
    margin-top: 20px;
    .leftSide{
        min-width: 266px;
        height: 100%;
        overflow-y: auto;
        background-color: #193142;
        box-sizing: border-box;
        .title{
          height: 42px;
          line-height: 42px;
          background-color: #36556b;
          font-size: 16px;
          color: #666;
          text-indent: 10px;
          color: #fff;
        }
        .item{
          display: flex;
          align-items: center;
          height: 48px;
          padding-left: 10px;
          cursor: default;
          &.active{
            background-color: rgba(45, 140, 240, 0.16);
          }
          .icon{
            width: 17.5px;
            display: block;
          }
          .name{
            font-size: 14px;
            padding-left: 12px;
          }
        }
    }
    .map-warp{
        flex: 1;
        height: 100%;
        background-color: #071c2b;
        #vmap{
          background-color: inherit;
          width: 100%;
          height: 100%;
        }
    }
    .rightSide{
        width: 269px;
        height: 100%;
        overflow-y: auto;
        background-color: #193142;
        box-sizing: border-box;
        padding: 17px 16px;
        .title{
          color: #fff;
          font-size: 16px;
          margin-bottom: 16px;
        }
        .remark{
          ul,li{
            list-style: none;
            margin: 0;
            padding: 0;
          }
          li{
            color: rgba(255, 255, 255, 0.7);
            line-height: 28px;
            font-size: 14px;
            margin-bottom: 8px;
          }
        }
        .saveForm,.deleteForm{
          .item{
            height: 48px;
            display: flex;
            justify-content: flex-start;
            align-items: center;
            font-size: 14px;
            border-bottom:2px solid rgba(45, 140, 240, 0.16);
            .lable{
              width: 80px;
              font-size: 14px;
            }
            .content{
              display: flex;
              justify-content: flex-start;
              align-items: center;
              overflow: hidden;
              text-overflow: ellipsis;
              .icon{
                width: 17.5px;
                display: block;
                margin-right:8px;
              }
            }
          }
        }

    }
    .bt-wrap{
      margin-top: 65px;
      .bt{
        width: 100px;
        height: 36px;
        color: #fff;
        font-size: 14px;
        line-height: 36px;
        text-align: center;
        background-color: rgba(24, 144, 255, 0.3);
        display: inline-block;
        cursor: pointer;
        user-select: none;
      -moz-user-select: none;
      -webkit-user-select: none;
      -ms-user-select: none;
        &.save{
          background-color: #1890ff;
        }
        &.delete{
          background-color: #f97647;
        }
        &.margin{
          margin-left: 12px;
        }
      }
    }
}
</style>
<style>
/* 标记点 */
.leaflet-marker-icon{
  background-size: 100%;
  background-repeat: no-repeat;
}
.leaflet-marker-icon.leaflet-marker-draggable{
  box-shadow: 0 2px 4px #154c74;
  background-color: #52b6ff;
  border-radius: 4px;
}
.leaflet-marker-icon.project-1{
  background-image: url("./images/layers/1.png");
}
.leaflet-marker-icon.project-2{
  background-image: url("./images/layers/2.png");
}
.leaflet-marker-icon.project-3{
  background-image: url("./images/layers/3.png");
}
.leaflet-marker-icon.project-4{
  background-image: url("./images/layers/4.png");
}
.leaflet-marker-icon.project-5{
  background-image: url("./images/layers/5.png");
}
.leaflet-marker-icon.project-6{
  background-image: url("./images/layers/6.png");
}
.leaflet-marker-icon.project-7{
  background-image: url("./images/layers/7.png");
}
.leaflet-marker-icon.project-8{
  background-image: url("./images/layers/8.png");
}
.leaflet-marker-icon.project-9{
  background-image: url("./images/layers/9.png");
}
.leaflet-marker-icon.project-10{
  background-image: url("./images/layers/10.png");
}
.leaflet-marker-icon.project-11{
  background-image: url("./images/layers/11.png");
}
.leaflet-marker-icon.project-12{
  background-image: url("./images/layers/12.png");
}
.leaflet-marker-icon.project-13{
  background-image: url("./images/layers/12.png");
}
</style>
