<template>
  <div>
    <div id="map" class="map-container"></div>
  </div>
</template>

<script>
import 'maptalks/dist/maptalks.css'
import * as maptalks from 'maptalks'
import * as mqtt from 'mqtt'
import { getMQTTCilentId } from '@/utils/mqtt'
import { getRailListJson, getAreaListJson } from '@/api/positioning/map'

export default {
  data() {
    return {
      locationData: null,

      baseRelativeCoordinate0: null,
      baseRelativeCoordinate1: null,
      baseRelativeExtent: null,
      baseGPSCoordinate0: null,
      baseGPSCoordinate1: null,
      baseGPSExtent: null,
      baseExtent: null,

      buildNo: 0,
      buildPanelPos: 0,
      floorNo: 0,
      floorPanelPos: 0,
      floorNoArray: [],
      postExtent: null,

      buildData: null,

      mapBaseLayer: null,
      map: null,
      mapLayer: null,
      personLayer: null,
      railLayer: null,
      railAlarmLayer: null,

      floorPanel: null,
      buildPanel: null,
      trackPerson: '',

      mqttClient: null,

      topic_t: [],
      topicArray: [],

      areaList: [],

      personAlarm: {},
      railAlarm: {},
      areaAlarm: {},
      arearailAlarm: {},
      trackpersonrailAlarm: [],
      alarmingPerson: [],
      alarmingRail: []
    }
  },
  props: {
    query: {
      type: Object,
      default: () => {},
    },
  },
  computed: {
    VUE_APP_BASE_API() {
      return process.env.VUE_APP_BASE_API
    },
    VUE_APP_BASE_WS() {
      return 'ws://' + window.location.host + process.env.VUE_APP_BASE_API
    },
  },
  created() {
    window.moveBuildPanel = this.moveBuildPanel
    window.changeBuild = this.changeBuild
    window.moveFloorPanel = this.moveFloorPanel
    window.changeFloor = this.changeFloor
  },
  mounted() {
    this.$nextTick((_) => {
      this.getLocationData()
    })
    this.$nextTick((_) => {
      const { type, personId } = this.$route.query
      // console.log(this.$route.query)
      type && (this.query.personId = personId)
      if (this.query.personId) this.trackEnabled()
    })
  },
  beforeDestroy() {
    this.mqttClient.end()
  },
  methods: {
    async getLocationData() {
      this.locationData = this.$setting

      if (this.locationData) {
        this.buildNo = this.locationData.DefaultBuild
        this.buildData = this.locationData.BuildList[this.buildNo]
        this.mapBaseLayer = this.locationData.MapBaseLayer //地图底图

        this.floorNo = this.buildData.DefaultFloor
        if (this.buildData.FloorList[this.floorNo].No instanceof Array) {
          this.floorNoArray = this.buildData.FloorList[this.floorNo].No
        } else {
          this.floorNoArray = [this.buildData.FloorList[this.floorNo].No]
        }

        this.baseRelativeCoordinate0 = new maptalks.Coordinate(this.buildData.RelativeCoordinate0)
        this.baseRelativeCoordinate1 = new maptalks.Coordinate(this.buildData.RelativeCoordinate1)
        this.baseRelativeExtent = new maptalks.Extent(
          this.baseRelativeCoordinate0,
          this.baseRelativeCoordinate1
        )

        if (this.buildData.MultiMap) {
          this.postExtent = [
            this.baseRelativeCoordinate0.x,
            this.baseRelativeCoordinate0.y,
            this.baseRelativeCoordinate1.x,
            this.baseRelativeCoordinate1.y,
          ]
        } else {
          this.postExtent = null
        }

        if (this.buildData.Projection == 'identity') {
          this.baseExtent = new maptalks.Extent(
            new maptalks.Coordinate(0, 0),
            new maptalks.Coordinate(
              this.baseRelativeCoordinate1.x - this.baseRelativeCoordinate0.x,
              this.baseRelativeCoordinate0.y - this.baseRelativeCoordinate1.y
            )
          )
        } else {
          this.baseGPSCoordinate0 = new maptalks.Coordinate(this.buildData.GPSCoordinate0)
          this.baseGPSCoordinate1 = new maptalks.Coordinate(this.buildData.GPSCoordinate1)
          this.baseGPSExtent = new maptalks.Extent(this.baseGPSCoordinate0, this.baseGPSCoordinate1)
          this.baseExtent = this.baseGPSExtent
        }
        this.createMap()
      } else {
        console.log('获取定位配置文件失败')
      }
    },
    async createMap() {
      let zoom, maxZoom, minZoom, baseLayer, resolution0, resolutionMax

      if (this.buildData.Projection == 'identity') {
        zoom = this.buildData.RelativeMapZoom
        maxZoom = this.buildData.RelativeMapMaxZoom
        minZoom = this.buildData.RelativeMapMinZoom
        resolution0 = this.buildData.RelativeResolution0
        resolutionMax = this.buildData.RelativeResolutionMax
        baseLayer = null
      } else {
        zoom = this.buildData.GPSMapZoom
        maxZoom = this.buildData.GPSMapMaxZoom
        minZoom = this.buildData.GPSMapMinZoom
        resolution0 = this.buildData.GPSResolution0
        resolutionMax = this.buildData.GPSResolutionMax
        baseLayer = new maptalks.TileLayer('base', this.mapBaseLayer)
      }

      if (this.map) this.map.remove()
      this.map = new maptalks.Map('map', {
        center: this.baseExtent.getCenter(),
        //centerCross: true,
        zoom: zoom,
        maxZoom: maxZoom,
        minZoom: minZoom,
        bearing: this.buildData.MapBearing,
        pitch: this.buildData.MapPitch,
        maxExtent: this.baseExtent,
        zoomControl: {
          position: 'top-left',
          slider: false,
          zoomLevel: false,
        },
        scaleControl: true,
        spatialReference: {
          projection: this.buildData.Projection,
          resolutions: (function () {
            const resolutions = []
            for (let i = 0; i <= resolutionMax; i++) {
              resolutions[i] = resolution0 / Math.pow(2, i)
            }
            return resolutions
          })(),
        },
        baseLayer: baseLayer,
      })

      this.map.fitExtent(this.baseExtent, 0)

      this.mapLayer = new maptalks.ImageLayer(
        'map',
        [
          {
            url: this.buildData.FloorList[this.floorNo].MapPath,
            extent: this.baseExtent,
            opacity: 1,
          },
        ],
        {
          forceRenderOnMoving: true,
          forceRenderOnZooming: true,
          forceRenderOnRotating: true,
        }
      ).addTo(this.map)

      this.personLayer = new maptalks.VectorLayer('person', {
        zIndex: 100,
        forceRenderOnMoving: true,
        forceRenderOnZooming: true,
        forceRenderOnRotating: true,
      }).addTo(this.map)

      // console.log(personLayer.getGeometryById(this.query.personName));
      this.railLayer = new maptalks.VectorLayer('rail', {
        zIndex: 1,
        visible: false,
        forceRenderOnMoving: true,
        forceRenderOnZooming: true,
        forceRenderOnRotating: true,
      }).addTo(this.map)

      this.railAlarmLayer = new maptalks.VectorLayer('railAlarm', {
        zIndex: 2,
        visible: true,
        forceRenderOnMoving: true,
        forceRenderOnZooming: true,
        forceRenderOnRotating: true,
      }).addTo(this.map)

      let _this = this
      new maptalks.control.Toolbar({
        items: [
          {
            item: '复位地图',
            click: function () {
              _this.query.personId = ''
              _this.trackEnabled()
              _this.map.animateTo(
                {
                  //center: baseGPSExtent.getCenter(),
                  //zoom: locationData[buildNo].GPSMapZoom,
                  bearing: _this.buildData.MapBearing,
                  pitch: _this.buildData.MapPitch,
                },
                {
                  duration: 1000,
                },
                (frame) => {
                  if (frame.state.playState === 'finished') {
                    _this.map.fitExtent(_this.baseExtent, 0, {
                      duration: 1000,
                    })
                  }
                }
              )
            },
          },
          {
            item: '显示围栏',
            click: function () {
              _this.railLayer.show()
            },
          },
          {
            item: '隐藏围栏',
            click: function () {
              _this.railLayer.hide()
            },
          },
        ],
      }).addTo(this.map)

      if (this.buildData.FloorPanelDisplay) {
        this.createFloorPanel()
      }

      if (this.locationData.BuildPanelDisplay) {
        this.createBuildPanel()
      }

      await this.getRail()
      await this.getArea()

      this.startMQTT()

      // 点选重叠图形
      this.map.on('contextmenu', (e) => this.identifyAndSelect(e))
    },
    //开始MQTT接收
    startMQTT() {
      this.personAlarm = {}
      this.railAlarm = {}
      this.areaAlarm = {}
      this.arearailAlarm = {}
      this.trackpersonrailAlarm = []
      this.alarmingPerson= []
      this.alarmingRail= []

      this.topicArray.splice(0)
      this.floorNoArray.forEach((f) => {
        this.topicArray.push('Positioning/Positioning/' + this.buildData.BuildId + '/' + f + '/#')
        this.topicArray.push('Positioning/Alarm/Person/' + this.buildData.BuildId + '/' + f + '/#')
        this.topicArray.push('Positioning/Alarm/Rail/' + this.buildData.BuildId + '/' + f + '/#')
      })
      this.topicArray.push('Positioning/Alarm/Rail/' + this.buildData.BuildId + '/0/#')
      this.topicArray.push('Positioning/Alarm/Area/' + this.buildData.BuildId + '/#')

      if (this.mqttClient && this.mqttClient.connected) {
        if (this.topic_t && this.topic_t.length > 0) this.mqttClient.subscribe(this.topic_t)
        if (this.query && this.query.enabled) this.mqttClient.subscribe(this.topicArray)
        return
      }

      // 连接选项
      const options = {
        clean: true, // true: 清除会话, false: 保留会话
        keepalive: 60,
        connectTimeout: 4000, // 超时时间
        // 认证信息
        clientId: getMQTTCilentId("trackmap"),
        username: 'client',
        password: '19c9547ad2029be96774fce5f1b9f099',
      }
      const connectUrl = this.VUE_APP_BASE_WS + '/MQTTOverWebSocket'
      //console.log(connectUrl)
      this.mqttClient = mqtt.connect(connectUrl, options)

      let _this = this
      this.mqttClient.on('connect', () => {
        //订阅主题
        console.log('定位MQTT正在连接')
        if (_this.query && _this.query.enabled) _this.mqttClient.subscribe(_this.topicArray)
        if (_this.topic_t) _this.mqttClient.subscribe(_this.topic_t)
      })
      this.mqttClient.on('message', (topic, message) => {
        if (topic == 'Online') {
          console.log('定位MQTT收到消息：', topic, message.toString())
        } else if (topic.startsWith('Positioning/Positioning/')) {
          this.changePerson(JSON.parse(message.toString()))
          //console.log(JSON.parse(message.toString()))
        } else if (topic.startsWith('Positioning/Alarm/')) {
          let alarm = JSON.parse(message.toString())
          switch (alarm.AlarmSource) {
            case 1:
              this.personAlarm[alarm.Id] = alarm.AlarmList
              this.personAlarming(alarm.Id)
              break
            case 2:
              this.railAlarm[alarm.Id] = alarm.AlarmList
              this.railAlarming(alarm.Id)
              break
            case 3:
              this.areaAlarm[alarm.Id] = alarm.AlarmList
              let area = this.areaList.find((v) => v.id == alarm.Id)
              if (area && area.railIds && area.railIds.length > 0) {
                area.railIds.forEach((a) => {
                  if (this.arearailAlarm[a]) {
                    if (alarm.AlarmList.length > 0) {
                      if (this.arearailAlarm[a].indexOf(area.id) == -1)
                        this.arearailAlarm[a].push(area.id)
                    } else {
                      let i = this.arearailAlarm[a].indexOf(area.id)
                      if (i >= 0) this.arearailAlarm[a].splice(i, 1)
                    }
                  } else {
                    this.arearailAlarm[a] = []
                    if (alarm.AlarmList.length > 0) this.arearailAlarm[a].push(area.id)
                  }
                  this.railAlarming(a)
                })
              }
              break
            default:
              break
          }
        }
      })
    },
    changePerson(person) {
      if (this.trackPerson == person.Id) {
        if (person.Positioning && person.Positioning.BuildId != this.buildData.BuildId) {
          this.mqttClient.unsubscribe(this.topic_t)
          let b, f
          for (let bn in this.locationData.BuildList) {
            if (this.locationData.BuildList[bn].BuildId == person.Positioning.BuildId) {
              b = bn
              break
            }
          }
          if (b != undefined) {
            for (let fn in this.locationData.BuildList[b].FloorList) {
              if (this.locationData.BuildList[b].FloorList[fn].No instanceof Array) {
                if (
                  this.locationData.BuildList[b].FloorList[fn].No.includes(
                    person.Positioning.FloorNo
                  )
                ) {
                  f = fn
                  break
                }
              } else {
                if (this.locationData.BuildList[b].FloorList[fn].No == person.Positioning.FloorNo) {
                  f = fn
                  break
                }
              }
            }
            if (f == undefined) {
              this.$message.error(
                '没有找到建筑【' +
                  person.Positioning.BuildId +
                  '】的楼层【' +
                  person.Positioning.FloorNo +
                  '】'
              )
              return
            }
          } else {
            this.$message.error('没有找到建筑【' + person.Positioning.BuildId + '】')
            return
          }
          this.changeBuild(b, f)
          this.$message.success(
            '切换至【' +
              this.locationData.BuildList[b].BuildAbbName +
              '】的【' +
              this.locationData.BuildList[b].FloorList[f].Name +
              '】'
          )
          return
        } else if (person.Positioning && !this.floorNoArray.includes(person.Positioning.FloorNo)) {
          this.mqttClient.unsubscribe(this.topic_t)
          let f
          for (let fn in this.buildData.FloorList) {
            if (this.buildData.FloorList[fn].No instanceof Array) {
              if (this.buildData.FloorList[fn].No.includes(person.Positioning.FloorNo)) {
                f = fn
                break
              }
            } else {
              if (this.buildData.FloorList[fn].No == person.Positioning.FloorNo) {
                f = fn
                break
              }
            }
          }
          if (f == undefined) {
            this.$message.error('没有找到楼层【' + person.Positioning.FloorNo + '】')
            return
          }
          this.changeFloor(f)
          this.$message.success('切换至【' + this.buildData.FloorList[f].Name + '】')
          return
        }
      }
      if (person.Display == 1) {
        let p = this.personLayer.getGeometryById(person.Id)
        if (p) {
          this.personMove(p, person)
        } else {
          this.addPerson(person)
        }
        if (this.trackPerson == person.Id) this.mapMove(person)
      } else {
        let p = this.personLayer.getGeometryById(person.Id)
        if (p) {
          p.remove()
        }
      }
    },
    async getRail() {
      this.railLayer.clear()
      this.railAlarmLayer.clear()
      const params = {
        BuildId: this.buildData.BuildId,
        FloorNoArray: this.floorNoArray,
        Extent: this.postExtent,
      }

      try {
        const res = await getRailListJson(params)
        const data = res.data.content
        if (data.length > 0) {
          data.forEach((r) => {
            let inExtent = true
            let points = []
            r.points.forEach((p) => {
              if (!this.baseRelativeExtent.contains(new maptalks.Coordinate(p.x, p.y)))
                inExtent = false
              points.push(this.getNewCoordinate(p.x, p.y))
            })
            if (inExtent) {
              this.railLayer.addGeometry(
                new maptalks.Polygon(points, {
                  symbol: {
                    lineColor: 'rgb(0,196,240)',
                    lineWidth: 2,
                    lineOpacity: 1,
                    polygonFill: 'rgb(135,196,240)',
                    polygonOpacity: 0.6,
                  },
                })
              )
              this.railAlarmLayer.addGeometry(
                new maptalks.Polygon(points, {
                  id: r.id,
                  visible: false,
                  symbol: {
                    lineColor: '#C06173',
                    lineWidth: 2,
                    lineOpacity: 1,
                    polygonFill: '#E08193',
                    polygonOpacity: 0.6,
                  },
                })
              )
            }
          })
        }
      } catch (error) {
        console.log(error)
        this.$message.error(error)
      }
    },
    // 获取区域
    async getArea() {
      let params = {
        BuildId: this.buildData.BuildId,
        // riskLevelArray: [1, 2, 3, 4] //四色图参数
      }
      try {
        let res = await getAreaListJson(params)
        let data = res.data.content
        this.areaList = data
      } catch (error) {
        console.log(error)
        this.$message.error(error)
      }
    },

    addPerson(person) {
      let marker = new maptalks.Marker(
        this.getNewCoordinate(person.Positioning.X, person.Positioning.Y),
        {
          id: person.Id,
          visible: true,
          symbol: [
            {
              markerFile: this.VUE_APP_BASE_API + person.IconPath,
              markerWidth: 40,
              markerHeight: 40,
              markerDx: 0,
              markerDy: 20,
              textName: person.Name,
              textDx: 0,
              textDy: 20,
            },
            {
              textName: '',
              textWeight: 'bold',
              textStyle: 'normal',
              textSize: 0,
              textFill: '#FF0000',
              textOpacity: 1,
              textDx: 0,
              textDy: -20,
            },
          ],
        }
      ).addTo(this.personLayer)
      marker.setInfoWindow({
        title: person.Name,
        width: 300,
        autoCloseOn: 'click contextmenu',
        content:
          '<table width = "100%" style="border-bottom: 0px solid rgb(231, 234, 236) !important">\
                         <tr>\
                           <td width = "40%" rowspan="5" align="center">\
                             <img src="' +
          this.VUE_APP_BASE_API +
          person.PhotoPath +
          '" style="width: 85px; height: 140px; object-fit: contain"/>\
                           </td>\
                           <td class="tdname">类型：</td>\
                           <td class="tddata">' +
          person.TypeName +
          '</td>\
                         <tr>\
                           <td class="tdname">部门：</td>\
                           <td class="tddata">' +
          person.DepartmentName +
          '</td>\
                         </tr>\
                         <tr>\
                           <td class="tdname">职位：</td>\
                           <td class="tddata">' +
          person.PositionName +
          '</td>\
                         </tr>\
                         <tr>\
                           <td class="tdname">电话：</td>\
                           <td class="tddata">' +
          person.Telephone +
          '</td>\
                         </tr>\
                         <tr>\
                           <td class="tdname">SN：</td>\
                           <td class="tddata">' +
          person.LabelMAC +
          '</td>\
                         </tr>\
                         <tr style="height:10px"/>\
                      </table>',
      })

      return marker
    },

    personMove(geometry, person) {
      geometry.animate(
        {
          translate: this.getOffset(geometry, person),
        },
        {
          duration: 1000,
        }
      )
    },

    personAlarming(personId, repeat = false) {
      if (!repeat && this.trackPerson == personId) {
        let newpra = []
        if (pa && pa.length > 0) {
          pa.forEach((v) => {
            if (v.ExtraList && v.ExtraList.length > 0) {
              v.ExtraList.forEach((e) => {
                if (e.Type == 2) {
                  if (newpra.indexOf(e.Id) == -1) newpra.push(e.Id)
                } else if (e.Type == 3) {
                  let area = this.areaList.find((a) => a.id == e.Id)
                  if (area && area.railIds && area.railIds.length > 0) {
                    area.railIds.forEach((r) => {
                      if (newpra.indexOf(e.Id) == -1) newpra.push(e.Id)
                    })
                  }
                }
              })
            }
          })
          this.trackpersonrailAlarm = newpra
        } else this.trackpersonrailAlarm.splice(0)
        if (this.trackpersonrailAlarm.length > 0) {
          this.trackpersonrailAlarm.forEach((a) => this.railAlarming(a))
        }
      }

      let p = this.personLayer.getGeometryById(personId)
      let pa = this.personAlarm[personId]

      if (p) {
        if (pa && pa.length > 0) {
          if (!repeat) {
            if (this.alarmingPerson.indexOf(personId) >= 0) return
            else this.alarmingPerson.push(personId)
          }

          let str = ''
          pa.forEach((v) => {
            switch (v.AlarmType) {
              case 11:
                str += '越界(进入),'
                break
              case 12:
                str += '越界(离开),'
                break
              case 20:
                str += '滞留,'
                break
              case 50:
                str += '静止,'
                break
              case 60:
                str += 'SOS,'
                break
              default:
                break
            }
          })
          str = str.substr(0, str.length - 1)
          if (p.getSymbol()[1].textName != str) {
            p.updateSymbol([{}, { textName: str }])
          }

          if (p.getSymbol()[1].textSize == 0) {
            p.updateSymbol([{}, { textSize: 16 }])
          } else {
            p.updateSymbol([{}, { textSize: 0 }])
          }

          setTimeout(() => {
            this.personAlarming(personId, true)
          }, 500)
        } else {
          let index = this.alarmingPerson.indexOf(personId)
          if (index >= 0) this.alarmingPerson.splice(index, 1)
          p.updateSymbol([{}, { textSize: 0 }])
        }
      }
    },
    railAlarming(railId, repeat = false) {
      let r = this.railAlarmLayer.getGeometryById(railId)
      let ra = this.railAlarm[railId]
      let aa = this.arearailAlarm[railId]
      let tpra = this.trackpersonrailAlarm.indexOf(railId) >= 0

      if (r) {
        if ((ra && ra.length > 0) || (aa && aa.length > 0) || tpra) {
          if (!repeat) {
            if (this.alarmingRail.indexOf(railId) >= 0) return
            else this.alarmingRail.push(railId)
          }

          if (r.isVisible()) r.hide()
          else r.show()
          setTimeout(() => {
            this.railAlarming(railId, true)
          }, 500)
        } else {
          let index = this.alarmingRail.indexOf(railId)
          if (index >= 0) this.alarmingRail.splice(index, 1)
          r.hide()
        }
      }
    },

    mapMove(person) {
      this.map.animateTo(
        {
          center: this.getNewCoordinate(person.Positioning.X, person.Positioning.Y),
          zoom: 20,
          pitch: 60,
          //bearing: 0
        },
        {
          duration: 1000,
        }
      )
    },

    getOffset(geometry, person) {
      let start = geometry.getCoordinates()
      let end = this.getNewCoordinate(person.Positioning.X, person.Positioning.Y)
      return end.sub(start)
    },

    getNewCoordinate(x, y) {
      if (this.buildData.Projection == 'identity') {
        return new maptalks.Coordinate(
          x - this.baseRelativeCoordinate0.x,
          this.baseRelativeCoordinate0.y - y
        )
      } else {
        return this.map.locate(
          this.baseGPSCoordinate0,
          (x - this.baseRelativeCoordinate0.x) / 1000,
          -(y - this.baseRelativeCoordinate0.y) / 1000
        )
      }
    },

    createBuildPanel() {
      if (this.buildNo <= 1) {
        this.buildPanelPos = 0
      } else if (this.buildNo >= this.locationData.BuildList.length - 3) {
        this.buildPanelPos = this.locationData.BuildList.length - 3
      } else {
        this.buildPanelPos = this.buildNo - 1
      }

      let mapdiv = document.getElementById('map')
      let mapdivh = mapdiv.clientHeight || mapdiv.offsetHeight

      this.buildPanel = new maptalks.control.Panel({
        position: { top: mapdivh / 2 - 60, left: '20' },
        draggable: false,
        custom: true,
        content: this.makeBuildPanelContent(),
        closeButton: false,
      }).addTo(this.map)
    },

    makeBuildPanelContent() {
      let content
      content = '<table class="map-buildpanel" cellpadding="0" frame=void rules=none>'
      content +=
        '<tr><td><button onclick="moveBuildPanel(0)"><div class="up-arrows"></div></button></td></tr>'
      for (let i = this.buildPanelPos; i <= this.buildPanelPos + 2; i++) {
        if (i == this.buildNo) {
          content +=
            '<tr><td><button style="background: rgb(28,188,156)">' +
            this.locationData.BuildList[i].BuildAbbName +
            '</button></td></tr>'
        } else {
          if (this.locationData.BuildList[i]) {
            content +=
              '<tr><td><button onclick="changeBuild(' +
              i +
              ')">' +
              this.locationData.BuildList[i].BuildAbbName +
              '</button></td></tr>'
          } else {
            content += '<tr><td><button></button></td></tr>'
          }
        }
      }

      content +=
        '<tr><td><button onclick="moveBuildPanel(1)"><div class="down-arrows"></div></button></td></tr>'
      content += '</table>'
      return content
    },

    moveBuildPanel(s) {
      let b = this.buildPanelPos
      if (s == 0) {
        if (b > 0) b--
      } else if (s == 1) {
        if (b < this.buildData.FloorList.length - 3) b++
      }
      if (b != this.buildPanelPos) {
        this.buildPanelPos = b
        this.buildPanel.setContent(this.makeBuildPanelContent())
      }
    },

    changeBuild(b, f) {
      this.buildNo = b
      this.buildPanel.setContent(this.makeBuildPanelContent())

      this.buildData = this.locationData.BuildList[this.buildNo]

      this.floorNo = Number.isFinite(f) ? f : this.buildData.DefaultFloor
      if (this.buildData.FloorList[this.floorNo].No instanceof Array) {
        this.floorNoArray = this.buildData.FloorList[this.floorNo].No
      } else {
        this.floorNoArray = [this.buildData.FloorList[this.floorNo].No]
      }

      this.baseRelativeCoordinate0 = new maptalks.Coordinate(this.buildData.RelativeCoordinate0)
      this.baseRelativeCoordinate1 = new maptalks.Coordinate(this.buildData.RelativeCoordinate1)
      this.baseRelativeExtent = new maptalks.Extent(
        this.baseRelativeCoordinate0,
        this.baseRelativeCoordinate1
      )

      if (this.buildData.MultiMap) {
        this.postExtent = [
          this.baseRelativeCoordinate0.x,
          this.baseRelativeCoordinate0.y,
          this.baseRelativeCoordinate1.x,
          this.baseRelativeCoordinate1.y,
        ]
      } else {
        this.postExtent = null
      }

      if (this.buildData.Projection == 'identity') {
        this.baseExtent = new maptalks.Extent(
          new maptalks.Coordinate(0, 0),
          new maptalks.Coordinate(
            this.baseRelativeCoordinate1.x - this.baseRelativeCoordinate0.x,
            this.baseRelativeCoordinate0.y - this.baseRelativeCoordinate1.y
          )
        )
      } else {
        this.baseGPSCoordinate0 = new maptalks.Coordinate(this.buildData.GPSCoordinate0)
        this.baseGPSCoordinate1 = new maptalks.Coordinate(this.buildData.GPSCoordinate1)
        this.baseGPSExtent = new maptalks.Extent(this.baseGPSCoordinate0, this.baseGPSCoordinate1)
        this.baseExtent = this.baseGPSExtent
      }

      if (this.mqttClient && this.mqttClient.connected) {
        if (this.topicArray && this.topicArray.length > 0) {
          this.mqttClient.unsubscribe(this.topicArray, () => {
            if (this.personLayer) this.personLayer.clear()
            this.createMap()
          })
          return
        }
      }

      this.createMap()
    },

    createFloorPanel() {
      if (this.floorNo <= 1) {
        this.floorPanelPos = 0
      } else if (this.floorNo >= this.buildData.FloorList.length - 3) {
        this.floorPanelPos = this.buildData.FloorList.length - 3
      } else {
        this.floorPanelPos = this.floorNo - 1
      }

      let mapdiv = document.getElementById('map')
      let mapdivh = mapdiv.clientHeight || mapdiv.offsetHeight

      if (this.floorPanel) this.floorPanel.remove()

      this.floorPanel = new maptalks.control.Panel({
        position: { top: mapdivh / 2 - 60, right: '20' },
        draggable: false,
        custom: true,
        content: this.makeFloorPanelContent(),
        closeButton: false,
      }).addTo(this.map)
    },

    makeFloorPanelContent() {
      let content
      content = '<table class="map-floorpanel" cellpadding="0" frame=void rules=none>'
      content +=
        '<tr><td><button onclick="moveFloorPanel(0)"><div class="up-arrows"></div></button></td></tr>'
      for (let i = this.floorPanelPos; i <= this.floorPanelPos + 2; i++) {
        if (i == this.floorNo) {
          content +=
            '<tr><td><button style="background: rgb(28,188,156)">' +
            this.buildData.FloorList[i].Name +
            '</button></td></tr>'
        } else {
          if (this.buildData.FloorList[i]) {
            content +=
              '<tr><td><button onclick="changeFloor(' +
              i +
              ')">' +
              this.buildData.FloorList[i].Name +
              '</button></td></tr>'
          } else {
            content += '<tr><td><button></button></td></tr>'
          }
        }
      }

      content +=
        '<tr><td><button onclick="moveFloorPanel(1)"><div class="down-arrows"></div></button></td></tr>'
      content += '</table>'
      return content
    },

    moveFloorPanel(s) {
      let f = this.floorPanelPos
      if (s == 0) {
        if (f > 0) f--
      } else if (s == 1) {
        if (f < this.buildData.FloorList.length - 3) f++
      }
      if (f != this.floorPanelPos) {
        this.floorPanelPos = f
        this.floorPanel.setContent(this.makeFloorPanelContent())
      }
    },

    changeFloor(f) {
      this.floorNo = f
      this.floorPanel.setContent(this.makeFloorPanelContent())

      if (this.buildData.FloorList[this.floorNo].No instanceof Array) {
        this.floorNoArray = this.buildData.FloorList[this.floorNo].No
      } else {
        this.floorNoArray = [this.buildData.FloorList[this.floorNo].No]
      }

      if (this.mqttClient && this.mqttClient.connected) {
        if (this.topicArray && this.topicArray.length > 0)
          this.mqttClient.unsubscribe(this.topicArray, () => {
            if (this.personLayer) this.personLayer.clear()
            this.startMQTT()
          })
      }

      this.mapLayer.setImages([
        {
          url: this.buildData.FloorList[this.floorNo].MapPath,
          extent: this.baseExtent,
          opacity: 1,
        },
      ])
      // this.trackEnabled()
      this.getRail()
    },
    sendMes(f) {
      this.$message({
        showClose: true,
        message: '楼层切换至' + f + '层',
        type: 'success',
      })
    },

    //叠加右键选择
    identifyAndSelect(e) {
      //identify
      let _this = this
      this.map.identify(
        {
          coordinate: e.coordinate,
          layers: [this.personLayer],
        },
        function (geos) {
          if (geos.length === 0) {
            _this.map.removeMenu()
            return
          }
          var options = { items: [] }
          geos.forEach(function (g) {
            var personN = g.getSymbol()[0].textName
            options.items.push({
              item: personN,
              click: function () {
                // console.log(g.toJSON());
                g.openInfoWindow()
              },
            })
          })
          _this.map.setMenu(options).openMenu(e.coordinate)
        }
      )
    },

    //追踪开关
    trackEnabled() {
      let personId = this.query.personId
      this.personAlarm = {}
      this.railAlarm = {}
      this.areaAlarm = {}
      this.arearailAlarm = {}
      this.trackpersonrailAlarm = []
      this.alarmingPerson = []
      this.alarmingRail= []

      if (personId) {
        if (this.mqttClient && this.mqttClient.connected) {
          this.mqttClient.unsubscribe(this.topicArray, () => {
            this.mqttClient.unsubscribe(this.topic_t, () => {
              if (this.personLayer) this.personLayer.clear()
              this.trackPerson = personId
              this.topic_t.splice(0)
              this.topic_t.push('Positioning/Positioning/+/+/' + this.trackPerson)
              this.topic_t.push('Positioning/Alarm/Person/+/+/' + this.trackPerson)
              this.mqttClient.subscribe(this.topic_t)
              if (this.query && this.query.enabled) this.mqttClient.subscribe(this.topicArray)
            })
          })
        } else {
          this.trackPerson = personId
          this.topic_t.push('Positioning/Positioning/+/+/' + this.trackPerson)
          this.topic_t.push('Positioning/Alarm/Person/+/+/' + this.trackPerson)
        }
      } else {
        this.trackPerson = ''
        if (this.mqttClient && this.mqttClient.connected) {
          this.mqttClient.unsubscribe(this.topicArray, () => {
            this.mqttClient.unsubscribe(this.topic_t, () => {
              if (this.personLayer) this.personLayer.clear()
              this.topic_t.splice(0)
            })
          })
        } else {
          this.topic_t.splice(0)
        }
        //this.$message.warning('清先选择人员')
      }
      //console.log(this.trackPerson);
    },
  },
}
</script>

<style lang="scss" scoped>
::v-deep .map-container {
  width: 100%;
  height: calc(100vh - 156px);
}

::v-deep .map-panel {
  background: rgba(135, 196, 240, 0.8);
  width: 450px;
  height: 120px;
  border: 2px #fff solid;
  padding: 10px;
  color: #fff;
}

::v-deep .map-panel input {
  color: #bbb;
}

::v-deep .map-panel a {
  color: #fff;
  float: right;
  margin-right: 15px;
}
::v-deep .map-floorpanel {
  background: rgb(52, 73, 94);
  width: 40px;
  height: 120px;
  padding: 0px;
  color: #fff;
  border: 0px solid rgb(231, 234, 236) !important;
}

::v-deep .map-floorpanel tr {
  text-align: center;
  height: 30px;
}

::v-deep .map-floorpanel td {
  text-align: center;
  height: 30px;
}

::v-deep .map-floorpanel button {
  width: 40px;
  height: 30px;
  border: none;
  background: rgb(52, 73, 94);
  color: #fff;
}

::v-deep .map-buildpanel {
  background: rgb(52, 73, 94);
  width: 40px;
  height: 120px;
  padding: 0px;
  color: #fff;
  border: 0px solid rgb(231, 234, 236) !important;
  font-size: 14px;
}

::v-deep .map-buildpanel tr {
  text-align: center;
  height: 30px;
}

::v-deep .map-buildpanel td {
  text-align: center;
  height: 30px;
}

::v-deep .map-buildpanel button {
  width: 40px;
  height: 30px;
  border: none;
  background: rgb(52, 73, 94);
  color: #fff;
}

::v-deep .up-arrows {
  width: 0;
  height: 0;
  border-bottom: 20px solid white;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
}

::v-deep .down-arrows {
  width: 0;
  height: 0;
  border-top: 20px solid white;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  position: absolute;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
