<template>
  <div class="orientation-container">
    <div class="top-container">
      <div class="person-info">
        <div>全部<span class="number">{{ personStatistics.allNum }}</span>人</div>
        <div>
          <div class="normal"></div>
          正常<span class="number">{{ personStatistics.normalNum }}</span>人
        </div>
        <div>
          <div class="off-line"></div>
          离线<span class="number">{{ personStatistics.offlineNum }}</span>人
        </div>
        <div>
          <div class="out-line"></div>
          违规<span class="number">{{ personStatistics.violationNum }}</span>人
        </div>
        <div>
          <div class="sos"></div>
          SOS<span class="number">{{ personStatistics.sosNum }}</span>人
        </div>
        <div class="time">当前时间：{{ nowDate | dateFormat }}</div>
      </div>
      <div class="right-content">
        <t-button
          color="success"
          icon="map-marker-outline"
          @click="trackClick"
        >轨迹</t-button
        >
        <div style="min-width:100px">悬浮窗<t-switch v-model="switch1" rounded @change="switchChange"></t-switch></div>
      </div>
    </div>
    <div id="div1" style="height: 100%"></div>
    <div class="label">
      <div class="item">
        <div :class="mapShow.sos?'':'cancel'">
          <div class="sos"></div>
          <div>SOS</div>
        </div>
        <div :class="mapShow.offLine?'':'cancel'">
          <div class="offline"></div>
          <div>离线</div>
        </div>
        <div :class="mapShow.outLine?'':'cancel'">
          <div class="outline"></div>
          <div>违规</div>
        </div>
        <div :class="mapShow.normal?'':'cancel'">
          <div class="normal"></div>
          <div>正常</div>
        </div>
      </div>
      <div class="item">
        <div v-for="(item, index) in toolTypes" :key="index" :class="item.show?'':'cancel'" @click="showOrHide(layer.equipmentLayer,item)">
          <div :style="{ 'background-image': 'url('+item.iconUrl+')' }" class="chuanbo"></div>
          <div>{{ item.name }}</div>
        </div>
      </div>
      <div class="item">
        <div v-for="(item, index) in markTypes" :key="index" :class="item.show?'':'cancel'" @click="showOrHide(layer.areaLayer,item)">
          <div :style="{ background: item.color}" class="dzwl"></div>
          <div>{{ item.name }}</div>
        </div>
      </div>
    </div>

    <t-modal
      :visibled.sync="trackModal"
      :footer-visibled="false"
      :mask-closable="false"
      :width="1400"
      :height="800"
      :cancel="stopPlayback"
      title="历史轨迹"
    >
      <div class="track-modal-container">
        <div class="track-modal-right">
          <t-button-group>
            <t-button
              v-for="(item, index) in trackTypeList"
              :class="
                index == trackTypeCondition.currentIndex ? 'active' : ''
              "
              :key="index"
              @click="changeTrackType(index)"
            >{{ item }}</t-button
            >
          </t-button-group>
          <div style="display: flex;padding: 5px 0px">
            <span class="track-span">人员</span>
            <t-select v-if="trackTypeCondition.currentIndex == 1" v-model="trackSearchs" multiple collapse-tags filterable placeholder="请选择人员" style="width: 300px" @change="personTrack()">
              <t-option v-for="(item, index) in personList" :key="index" :value="item">{{ item.workEmployeeName }}</t-option>
            </t-select>
            <t-select v-if="trackTypeCondition.currentIndex == 0" v-model="trackSearch" filterable placeholder="请选择人员" style="width: 200px" @change="personTrack()">
              <t-option v-for="(item, index) in personList" :key="index" :value="item">{{ item.workEmployeeName }}</t-option>
            </t-select>
            <span class="track-span">时间</span>
            <t-date-picker
              v-model="rangeDate"
              align-right
              style="width:320px"
              type="dateTimeRange"
              placeholder="请选择时间"
              @date-change="onChangeDate">
            </t-date-picker>
            <span class="track-span">速度</span>
            <t-select v-model="playbackRate" placeholder="回放速度" style="width: 60px;">
              <t-option v-for="(item, index) in speeds" :key="index" :value="item">{{ item + 'X' }}</t-option>
            </t-select>
            <t-button v-if="!playbacking" color="success" icon="video-outline" @click="playback()">回放</t-button>
            <t-button v-if="playbacking" color="secondary" icon="video-outline" @click="stopPlayback()">停止</t-button>
            <span v-if="playbacking" class="track-span">回放时刻: {{ trackTime }}</span>
          </div>
          <div>
            <div id="track-map" style="height: 610px;"></div>
            <div v-if="trackTypeCondition.currentIndex == 0 && timelineList.length > 0" class="track-label">
              <t-timeline :horizontal="true">

                <t-timeline-item v-for="(item,index) in timelineList" :key="index" :time="item.inTime" :color="item.color">
                  <slot>
                    <div class="card card-has-border" style="width: 100px">
                      <div class="card-block">
                        <span class="card-block-name">{{ item.areaName }}</span>
                        <span class="card-block-time">{{ item.durationTime }}min</span>
                        <div>
                          <t-progress :percent="item.proportion" :status="item.status" hide-info></t-progress>
                        </div>
                      </div>
                    </div>
                  </slot>
                </t-timeline-item>
              </t-timeline>
            </div>
          </div>
        </div>
      </div>
    </t-modal>
    <t-modal :visibled.sync="rescueModal" title="指派救援人员">
      <t-form
        ref="formValidate"
        :model="formValidate"
        :rules="ruleValidate"
        :label-width="80"
        label-position="left"
      >
        <t-form-item label="救援人员" prop="rescue">
          <t-select v-model="formValidate.rescue" placeholder="请选择">
            <t-option v-for="(item, index) in rescuer" :key="index+'rescuer'" :value="item.ID">{{ item.NAME }}</t-option>
          </t-select>
        </t-form-item>
      </t-form>
      <div slot="footer">
        <t-button @click="cancel">取消</t-button>
        <t-button class="submit-button" @click="appointSubmit()">指派</t-button>
      </div>
    </t-modal>
  </div>
</template>

<script>
import './orientation.scss'
import services from '../../conf/services'
import EventBus from '../../bus'
import { GIS_SEA_LAYER_URL, GIS_SEA_URL } from '../../constants'
export default {
  filters: {
    dateFormat(value) {
      var year = value.getFullYear()
      var month = value.getMonth() + 1
      month >= 10 ? month : '0' + month
      var day = value.getDate() >= 10 ? value.getDate() : '0' + value.getDate()
      var hours =
        value.getHours() >= 10 ? value.getHours() : '0' + value.getHours()
      var minutes =
        value.getMinutes() >= 10
          ? value.getMinutes()
          : '0' + value.getMinutes()
      var seconds =
        value.getSeconds() >= 10
          ? value.getSeconds()
          : '0' + value.getSeconds()
      return (
        year +
        '.' +
        month +
        '.' +
        day +
        ' ' +
        hours +
        ':' +
        minutes +
        ':' +
        seconds
      )
    }
  },
  data() {
    return {
      trackData: [{
        entityId: 1,
        name: '张三',
        icon: '',
        status: '',
        color: 'red',
        traceList: [{
          // entityId  人员ID
          // longitude  经度
          // latitude  维度
          // height  高度
          // createDate  定位时间
          // playDurationTime  播放时间
          // toolIndex  当前所在围栏 isStopPlay
          lng: 122.09930419921876,
          lat: 29.96089241772908,
          time: '2020-11-11 31312',
          second: 1,
          index: 0
        }, {
          lng: 122.09930419921876,
          lat: 30.06089241772908,
          time: '2020-11-11 2323',
          second: 2,
          index: 1
        }, {
          lng: 122.39930419921876,
          lat: 30.06089241772908,
          time: '2020-11-11 4433',
          second: 5,
          index: 2
        }, {
          lng: 122.59930419921876,
          lat: 30.26089241772908,
          time: '2020-11-11 111',
          second: 10,
          isStopPlay: true,
          index: 2
        }]
      }, {
        entityId: 2,
        name: '李四',
        icon: '',
        status: '',
        color: 'blue',
        traceList: [{
          lng: 122.59930419921876,
          lat: 29.96089241772908,
          time: '2020-11-11 233456',
          second: 3,
          index: 0
        }, {
          lng: 122.59930419921876,
          lat: 30.06089241772908,
          time: '2020-11-11 633',
          second: 4,
          index: 1
        }, {
          lng: 122.89930419921876,
          lat: 30.06089241772908,
          time: '2020-11-11 5445',
          second: 6,
          index: 2
        }, {
          lng: 122.99930419921876,
          lat: 30.26089241772908,
          time: '2020-11-11 23434',
          second: 8,
          index: 2
        }]
      }, {
        entityId: 3,
        name: '王五',
        icon: '',
        status: '',
        color: 'blue',
        traceList: [{
          lng: 122.59930419921876,
          lat: 29.96089241772908,
          time: '2020-11-11  242',
          second: 3,
          index: 0
        }, {
          lng: 122.59930419921876,
          lat: 30.06089241772908,
          time: '2020-11-11  1322',
          second: 4,
          index: 1
        }, {
          lng: 122.89930419921876,
          lat: 30.06089241772908,
          time: '2020-11-11 122112',
          second: 6,
          index: 2
        }, {
          lng: 122.89930419921876,
          lat: 30.26089241772908,
          time: '2020-11-11 12',
          second: 9,
          index: 2
        }]
      }],
      timeouts: [],
      speeds: [1, 4, 16, 24, 48],
      playbackRate: 1,
      playbacking: false,
      trackTime: '',
      map: null,
      layersGroup: new Ai.LayerGroup(),
      pointsGroup: new Ai.LayerGroup(),
      lineColors: ['#26B728', '#280e9e', '#dc8020', '#EAFF00',
        '#cc48ca', '#83b5ff', '#4D4128', '#08570c'], // 定义几种颜色多人轨迹回放使用,不够再取随机颜色
      tal: 32.465444444444444,
      switch1: true,
      pointsarr: null,
      markTypes: [],
      toolTypes: [],
      aggregatedMapAreaList: {
        mapAreas: [], // 围栏集合
        coreEntitys: [] // 聚合设备集合
      },
      personStatistics: {
        all: 0,
        offLine: 0,
        outLine: 0,
        sos: 0,
        normal: 0
      },
      popup: null,
      dataList: [
      ],
      nowDate: new Date(),
      modal: false,
      trackModal: false,
      trackSearch: '',
      trackSearchs: [],
      trackTimeList: ['-10min', '-1h', '本日', '自定义'],
      trackTypeList: ['单人模式', '多人模式'],
      trackQueryCondition: {
        currentIndex: 0
      },
      trackTypeCondition: {
        currentIndex: 0
      },
      trackMap: null,
      trackPath: null,
      rangeDate: '',
      rescueModal: false,
      formValidate: {
        rescue: ''
      },
      ruleValidate: {
        rescue: [
          {
            required: true,
            message: '救援人员不能为空',
            trigger: 'blur',
            validator(rule, value, callback) {
              console.log(value)
              if (!value) {
                callback(rule.message)
              } else {
                callback()
              }
            }
          }
        ]
      },
      layer: {
        areaLayer: new Ai.FeatureGroup(),
        equipmentLayer: new Ai.FeatureGroup(),
        personLayer: new Ai.FeatureGroup()
      },
      mapShow: {
        dzwl: true,
        zyqy: true,
        fenji: true,
        chuanbo: true,
        shengyazhan: true,
        sos: true,
        offLine: true,
        outLine: true,
        normal: true
      },
      personList: [],
      timelineList: [],
      rescuer: [],
      appointAlarmId: '',
      trackPerson: '',
      orgId: ''
    }
  },
  // beforeRouteEnter(to, form, next) {
  //   console.log(form)
  //   if (form.path != '/refresh') {
  //     next(vm => {
  //       vm.$router.replace('/refresh')
  //     })
  //   } else {
  //     next()
  //   }
  // },
  mounted() {
    // this.getGisToken().then(() => { // 获取gistoken后加载地图
    // })
    this.getTagType().then(() => { // 初始化区域类型
      this.getToolType().then(() => { // 初始化设备类型
        this.initMap()
        this.initTrackMap()
        this.initStatusCount() // 初始化人数统计数据
      })
    })
    setInterval(() => { // 当前时间
      this.nowDate = new Date()
    }, 1000)
    EventBus.$on('person', (msg) => { // 获取镜屏推送消息,镜屏每次只推送一个元素的变化
      msg = JSON.parse(msg)
      console.log(msg)
      this.personStatistics = msg.data.countMap
      if (msg.data.aggregatedMapAreaList.length === 1 && msg.data.unaggregatedEntityPositionList.length === 0) {
        this.removeUnaggregated(msg.data.currentEntityPosition) // 删除离散的人员
      }
      if (msg.data.aggregatedMapAreaList) {
        this.changeLocation(msg.data.aggregatedMapAreaList) // 改变区域和设备
      }
      if (msg.data.unaggregatedEntityPositionList) {
        this.changeUnaggregated(msg.data.unaggregatedEntityPositionList) // 改变离散的人员
      }
    })
    EventBus.$on('ship', (msg) => { // 获取镜屏推送消息
      console.log(msg)
      this.changeShip(msg)
    })
  },
  methods: {
    // async getGisToken() { // 获取GIS token并存入store
    //   await this.$test
    //     .post(services.mapTag.GET_MAP_PARAM, '')
    //     .then((res) => {
    //       this.$store.commit('setGisToken', res.data.ak)
    //       this.$store.commit('setMapParam', {center: [res.data.latitude, res.data.longitude], zoom: res.data.scale})
    //     })
    //     .catch((res) => {
    //       // 请求失败处理...
    //     })
    // },
    async getTagType() {
      await this.$test
        .post(services.mapTag.MAP_TAG_TYPE, {})
        .then((res) => {
          // 请求成功处理...
          this.markTypes = res.data
          this.markTypes.forEach(e => {
            e.show = true
          })
        })
        .catch((res) => {
          // 请求失败处理...
        })
    },
    async getToolType() {
      await this.$test.post(services.equipment.EQUIPMENT_TYPE, {}
      ).then(res => {
        // 请求成功处理...
        this.toolTypes = res.data
        this.toolTypes.forEach(e => {
          e.show = true
        })
      }).catch(res => {
        // 请求失败处理...
      })
    },
    initMap() { // 加载主屏地图
      if (this.map != null && this.map != '') {
        this.map.remove()
      }
      this.map = new Ai.Map('div1', {
        ak: this.$store.getters.getGisToken,
        center: this.$store.getters.getMapParam.center,
        zoom: this.$store.getters.getMapParam.zoom
      })
      var maplayer = Ai.TileLayer(GIS_SEA_LAYER_URL)
      this.map.addLayer(maplayer)
      var la = Ai.WMTSLayer(
        GIS_SEA_URL,
        { opacity: 0.5 }
      )
      this.map.addLayer(la)
      Ai.Scale({ position: 'bottomright' }).addTo(this.map)
      Ai.Zoom({ type: 'small' }).addTo(this.map)
      this.$test.post(services.organization.INIT_LOCATION_DETAILS, {}
      ).then(res => {
        // 请求成功处理...
        this.loadUnaggregated(res.data.unaggregatedEntityPositionList)
        res.data.aggregatedMapAreaList.forEach(e => {
          if (e.mapAreaContent) {
            this.aggregatedMapAreaList.mapAreas.push(e)
          } else {
            this.aggregatedMapAreaList.coreEntitys.push(e)
          }
        })
        this.map.on('popupclose', this.popClose)
        this.map.on('popupopen', this.popOpen)
        this.loadMapArea()
        this.loadCoreEntity()
      }).catch(res => {
        // 请求失败处理...
      })
    },
    loadCoreEntity() {
      this.map.addLayer(this.layer.equipmentLayer)
      this.aggregatedMapAreaList.coreEntitys.forEach(e => {
        if (e.latitude) {
          var url = ''
          var businessTypeName = ''
          this.toolTypes.forEach(t => {
            if (e.coreEntityType == t.resourceToolType) {
              url = t.iconUrl
              businessTypeName = t.name
            }
          })
          var coreEntity = Ai.Point([e.latitude, e.longitude], {
            icon: Ai.Icon({
              // 设置图标URL路径
              iconUrl: url,
              // 设置图标大小
              iconSize: [20, 20],
              // 设置点对象和图标的相对偏移量
              iconAnchor: [100, 100]
            })
          })
          coreEntity.setAttributes({'elementId': e.coreEntityId, 'resourceToolType': e.coreEntityType})
          this.layer.equipmentLayer.addLayer(coreEntity)
          if (e.employeeCount > 0) {
            var classStr = this.getClassByStatus(e.locationStatus)
            var point = Ai.Point([e.latitude, e.longitude], {
              icon: Ai.DivIcon({
                html: '<div class="' + classStr + '">' + e.employeeCount + '人</div>',
                className: 'person-count',
                // 设置图标大小
                // iconSize: [20, 20],
                // 设置点对象和图标的相对偏移量
                iconAnchor: [15, 50]
              })
            })
            this.map.addLayer(point)
            this.getPopup(point, e.ebcEntityPositionList, businessTypeName, e.mapAreaName, [0, -40], url)
            coreEntity.point = point
          }
        }
      })
    },
    loadMapArea() {
      this.map.addLayer(this.layer.areaLayer)
      this.aggregatedMapAreaList.mapAreas.forEach(e => {
        var coverWktStr = e.mapAreaContent
        var coverLayer = Ai.Polygon(coverWktStr, {color: e.areaColor, opacity: 1.0, weight: 1.2})
        coverLayer.setAttributes({'elementId': e.mapAreaId, 'mapAreaBusinessType': e.businessType})
        this.layer.areaLayer.addLayer(coverLayer)
        // if (e.ebcEntityPositionList.length > 0) {
        //   var la = coverLayer.getCenter()
        //   var classStr = this.getClassByStatus(e.locationStatus)
        //   var point = Ai.Point(la, {
        //     icon: Ai.DivIcon({
        //       html: '<div class="' + classStr + '">' + e.ebcEntityPositionList.length + '人</div>',
        //       className: 'person-count',
        //       // 设置图标大小
        //       // iconSize: [20, 20],
        //       // 设置点对象和图标的相对偏移量
        //       iconAnchor: [15, 15]
        //     })
        //   })
        //   this.map.addLayer(point)
        //   coverLayer.point = point
        //   var businessTypeName
        //   this.markTypes.forEach(m => {
        //     if (m.mapAreaBusinessType == e.businessType) {
        //       businessTypeName = m.name
        //     }
        //   })
        //   this.getPopup(point, e.ebcEntityPositionList, businessTypeName, e.mapAreaName, [0, -10], '')
        // }
      })
    },
    switchChange(status) {
      for (var i = 0; i < 6; i++) {
        (function(i) {
          setTimeout(function() {
            console.log(i)
          }, (i + 1) * 1000)
        })(i)
      }
      if (status) {
        // this.layer.areaLayer.eachLayer((la) => {
        //   if (la.point) {
        //     la.point.popup.openOn(this.map)
        //   }
        // })
        this.layer.equipmentLayer.eachLayer((la) => {
          if (la.point) {
            la.point.popup.openOn(this.map)
          }
        })
        this.layer.personLayer.eachLayer((la) => {
          if (la.popup) {
            la.popup.openOn(this.map)
          }
        })
      } else {
        // this.layer.areaLayer.eachLayer((la) => {
        //   if (la.point) {
        //     this.map.closePopup(la.point.popup)
        //   }
        // })
        this.layer.equipmentLayer.eachLayer((la) => {
          if (la.point) {
            this.map.closePopup(la.point.popup)
          }
        })
        this.layer.personLayer.eachLayer((la) => {
          if (la.popup) {
            this.map.closePopup(la.popup)
          }
        })
      }
    },
    changeLocation(msg) {
      msg.forEach(e => {
        if (e.mapAreaContent) {
          // this.layer.areaLayer.eachLayer((la) => {
          //   if (e.mapAreaId == la.getAttributes().elementId) {
          //     if (la.point) {
          //       this.map.closePopup(la.point.popup)
          //       la.point.popup.remove()
          //       this.map.removeLayer(la.point)
          //     }
          //     if (e.ebcEntityPositionList.length > 0) {
          //       var classStr = this.getClassByStatus(e.locationStatus)
          //       var point = Ai.Point(la.getCenter(), {
          //         icon: Ai.DivIcon({
          //           html: '<div class="' + classStr + '">' + e.ebcEntityPositionList.length + '人</div>',
          //           className: 'person-count',
          //           // 设置图标大小
          //           // iconSize: [20, 20],
          //           // 设置点对象和图标的相对偏移量
          //           iconAnchor: [15, 15]
          //         })
          //       })
          //       this.map.addLayer(point)
          //       la.point = point
          //       var businessTypeName
          //       this.markTypes.forEach(m => {
          //         if (m.mapAreaBusinessType == e.businessType) {
          //           businessTypeName = m.name
          //         }
          //       })
          //       this.getPopup(point, e.ebcEntityPositionList, businessTypeName, e.mapAreaName, [0, -10], '')
          //     }
          //   }
          // })
        } else {
          this.layer.equipmentLayer.eachLayer((la) => {
            if (e.coreEntityId == la.getAttributes().elementId) {
              if (la.point) {
                this.map.closePopup(la.point.popup)
                this.map.removeLayer(la.point)
              }
              console.log(la.getAttributes().elementId)
              la.setLatLng([e.latitude, e.longitude])
              if (e.ebcEntityPositionList.length > 0) {
                var classStr = this.getClassByStatus(e.locationStatus)
                var point = Ai.Point([e.latitude, e.longitude], {
                  icon: Ai.DivIcon({
                    html: '<div class="' + classStr + '">' + e.employeeCount + '人</div>',
                    className: 'person-count',
                    // 设置图标大小
                    // iconSize: [20, 20],
                    // 设置点对象和图标的相对偏移量
                    iconAnchor: [15, 50]
                  })
                })
                this.map.addLayer(point)
                var businessTypeName = '设备'
                var url
                this.toolTypes.forEach(t => {
                  if (e.coreEntityType == t.resourceToolType) {
                    url = t.iconUrl
                    businessTypeName = t.name
                  }
                })
                this.getPopup(point, e.ebcEntityPositionList, businessTypeName, e.mapAreaName, [0, -40], url)
                la.point = point
              }
            }
          })
        }
      })
      // this.loadMapArea()
      // this.loadCoreEntity()
    },
    getPopup(point, positionList, type, name, offset, url) { // 生成Popup
      var container = 'container'
      if (positionList.length < 3) {
        container += positionList.length
      }
      var maxWidth = 100
      if (type) {
        if (positionList.length === 1) {
          maxWidth = 120
        } else if (positionList.length === 2) {
          maxWidth = 200
        } else {
          maxWidth = 300
        }
      }
      point.popup = Ai.Popup({
        maxWidth: maxWidth,
        minWidth: maxWidth,
        offset: offset,
        autoClose: false,
        autoPan: false,
        closeButton: true
      })
      var content = '<div class="tips-item">'
      if (type) {
        content += '<div class="top">'
        if (url) {
          content += '<div><img src="' + url + '" width="20" height="20"></div>'
        }
        content += '<div>' + name + '</div></div>'
        content += '<div class="' + container + '">'
        positionList.forEach(e => {
          content +=
              '<div class="' + this.getClassByStatus(e.locationStatus) + '">' + e.name + '</div>'
        })
        content += '</div></div>'
      } else {
        content += '<div class="container1">'
        positionList.forEach(e => {
          content +=
              '<div class="' + this.getClassByStatus(e.locationStatus) + '">' + e.name + '</div>'
        })
        content += '</div></div>'
      }
      // 设置弹出框弹出位置
      point.popup.setLatLng(point.getLatLng())
      // 设置弹出框弹出内容
      point.popup.setContent(content)
      point.popup.openo = this.switch1
      point.popup.openOn(this.map) // 需要先显示
      if (!this.switch1) { // 如果全局关闭则立即关闭
        this.map.closePopup(point.popup)
      }
      point.on('click', (e) => { // 配置点击事件 点击开关
        if (point.popup.openo) {
          this.map.closePopup(point.popup)
        } else {
          point.popup.openOn(this.map)
        }
      })
    },
    popClose(e) {
      e.popup.openo = false
    },
    popOpen(e) {
      e.popup.openo = true
    },
    loadUnaggregated(dataList) { // 加载不聚合的人
      this.map.addLayer(this.layer.personLayer)
      dataList.forEach(element => {
        var classStr = this.getClassByStatus(element.locationStatus)
        var point = Ai.Point([element.latitude, element.longitude], {
          icon: Ai.DivIcon({
            html: '<div class="' + classStr + '">1人</div>',
            className: 'person-count',
            // 设置图标大小
            // iconSize: [20, 20],
            // 设置点对象和图标的相对偏移量
            iconAnchor: [15, 15]
          })
        })
        point.setAttributes({'elementId': element.entityId})
        this.layer.personLayer.addLayer(point)
        // this.map.addLayer(point)
        this.getPopup(point, [element], '', '', [0, -10], '')
      })
      // this.map.setViewPort([points])
    },
    changeUnaggregated(dataList) { // 修改不聚合的人
      dataList.forEach(element => {
        var is = true
        this.layer.personLayer.eachLayer((la) => {
          if (element.entityId == la.getAttributes().elementId) {
            is = false
            this.map.closePopup(la.popup)
            la.popup.remove()
            console.log('修改' + element.name)
            la.setLatLng([element.latitude, element.longitude])
            var classStr = this.getClassByStatus(element.locationStatus)
            var icon = Ai.DivIcon({
              html: '<div class="' + classStr + '">1人</div>',
              className: 'person-count',
              // 设置图标大小
              // iconSize: [20, 20],
              // 设置点对象和图标的相对偏移量
              iconAnchor: [15, 15]
            })
            la.setIcon(icon)
            // point.setAttributes({'elementId': element.entityId})
            // this.layer.personLayer.addLayer(point)
            // this.map.addLayer(point)
            this.getPopup(la, [element], '', '', [0, -10], '')
          }
        })
        if (is) {
          console.log('新增' + element.name)
          var classStr = this.getClassByStatus(element.locationStatus)
          var point = Ai.Point([element.latitude, element.longitude], {
            icon: Ai.DivIcon({
              html: '<div class="' + classStr + '">1人</div>',
              className: 'person-count',
              // 设置图标大小
              // iconSize: [20, 20],
              // 设置点对象和图标的相对偏移量
              iconAnchor: [15, 15]
            })
          })
          point.setAttributes({'elementId': element.entityId})
          this.layer.personLayer.addLayer(point)
          // this.map.addLayer(point)
          this.getPopup(point, [element], '', '', [0, -10], '')
        }
      })
      // this.map.setViewPort([points])
    },
    removeUnaggregated(po) { // 删除不聚合的人
      this.layer.personLayer.eachLayer((la) => {
        var e
        if (po.entityId === la.getAttributes().elementId) {
          console.log('删除' + po.name)
          this.map.closePopup(la.popup)
          la.popup.remove()
          e = la
        }
        if (e) {
          this.map.removeLayer(e)
          this.layer.personLayer.removeLayer(e)
        }
      })
    },
    getClassByStatus(status) {
      switch (status) {
        case '050': // 自动告警 ------ 红色
        case '040': // 手动告警 ------ 红色
          return 'sos'
          break
        case '030': // 超时离线 ------ 灰色
        case '035': // 关机离线报警 ------ 灰色
          return 'offline'
          break
        case '060': // 救援人员 ------ 黄色
        case '020': // 进入了禁入区域 ------ 黄色
        case '015': // 在限制区域超时 ------ 黄色
          return 'outline'
          break
        case '010': // 进入限制区域（尚未超时） ------ 绿色
        case '000': // 正常 ------ 绿色
          return 'normal'
          break
        default:
          return 'normal'
      }
    },
    loadAggregated(dataList) {
    },
    showOrHide(layer, item) { // 地图设备人员围栏显示和隐藏
      item.show = !item.show
      layer.eachLayer((e) => {
        if ((e.getAttributes().resourceToolType == item.resourceToolType && item.resourceToolType != undefined) || (e.getAttributes().mapAreaBusinessType == item.mapAreaBusinessType && item.mapAreaBusinessType != undefined)) {
          if (this.map.hasLayer(e)) {
            this.map.removeLayer(e)
            if (e.point) {
              this.map.removeLayer(e.point)
              if (e.point.popup) {
                this.map.closePopup(e.point.popup)
              }
            }
          } else {
            this.map.addLayer(e)
            if (e.point) {
              this.map.addLayer(e.point)
              if (e.point.popup) {
                e.point.popup.openOn(this.map)
                if (!this.switch1) { // 如果全局关闭则立即关闭
                  this.map.closePopup(e.point.popup)
                }
              }
            }
          }
        }
      })
    },
    changeTrackTime(index) { // 速度选择
      this.stopPlayback()
      this.trackMap.removeLayer(this.layersGroup)
      this.trackMap.removeLayer(this.pointsGroup)
      this.trackQueryCondition.currentIndex = index
    },
    changeTrackType(index) { // 模式选择
      this.stopPlayback()
      this.trackMap.removeLayer(this.layersGroup)
      this.trackMap.removeLayer(this.pointsGroup)
      this.trackTypeCondition.currentIndex = index
      this.trackSearch = ''
      this.trackSearchs = []
    },
    initTrackMap() { // 加载轨迹地图
      if (this.trackMap != null && this.trackMap != '') {
        this.trackMap.remove()
      }
      this.trackMap = new Ai.Map('track-map', {
        ak: this.$store.getters.getGisToken,
        center: this.$store.getters.getMapParam.center,
        zoom: this.$store.getters.getMapParam.zoom
      })
      var maplayer = Ai.TileLayer(GIS_SEA_LAYER_URL)
      var la = Ai.WMTSLayer(GIS_SEA_URL, {opacity: 0.5})
      this.trackMap.addLayer(maplayer)
      this.trackMap.addLayer(la)

      Ai.Scale({position: 'bottomright'}).addTo(this.trackMap)
      Ai.Zoom({type: 'small'}).addTo(this.trackMap)
      this.loadBindDevicePerson()
      this.loadNotBindEquipment()
      this.$test
        .post(services.alarm.LOAD_MAP_AREA_TOOL, {})
        .then((res) => {
          console.log(res)
          res.data.mapAreaList.forEach(e => {
            var typeObj = res.data.mapAreaTypeList.filter(type => {
              return e.businessType == type.mapAreaBusinessType
            })
            var polygon = Ai.Polygon(e.mapAreaContent, {color: typeObj[0].color, opacity: 1.0, weight: 1.2})
            this.trackMap.addLayer(polygon)
          })
          res.data.toolList.forEach(e => {
            var typeObj = res.data.toolTypeList.filter(type => {
              return e.resourceToolType == type.resourceToolType
            })
            var point = Ai.Point([e.latitude, e.longitude], {
              icon: Ai.Icon({
                // 设置图标URL路径
                iconUrl: typeObj[0].iconUrl,
                // 设置图标大小
                iconSize: [20, 20],
                // 设置点对象和图标的相对偏移量
                iconAnchor: [100, 100]
              })
            })
            this.trackMap.addLayer(point)
          })
        })
        .catch((res) => {
          // 请求失败处理...
        })
    },
    loadBindDevicePerson() {
      this.$test
        .post(services.organization.BIND_DEVICE, {})
        .then((res) => {
          console.log(res)
          this.personList = res.data
        })
        .catch((res) => {
          // 请求失败处理...
        })
    },
    initStatusCount() {
      this.$test
        .post(services.organization.INIT_STATUS_COUNT, {})
        .then((res) => {
          this.personStatistics = res.data
        })
        .catch((res) => {
          // 请求失败处理...
        })
    },
    loadNotBindEquipment() {
      this.$test
        .post(services.organization.EQUIPMENT_NOT_BIND, {})
        .then((res) => {
          console.log(res)
          res.data.forEach(e => {
            var url = ''
            this.toolTypes.forEach(t => {
              if (e.resourceToolType == t.resourceToolType) {
                url = t.iconUrl
              }
            })
            var point = Ai.Point([e.latitude, e.longitude], {
              icon: Ai.Icon({
                // 设置图标URL路径
                iconUrl: url,
                // 设置图标大小
                iconSize: [20, 20],
                // 设置点对象和图标的相对偏移量
                iconAnchor: [0, 0]
              })
            })
            this.trackMap.addLayer(point)
          })
        })
        .catch((res) => {
          // 请求失败处理...
        })
    },
    onChangeDate() { // 轨迹时间选择
    },
    toExport() { // 轨迹导出
    },
    close(item) { // 人员报警关闭
      this.$Confirm.confirm({
        title: '确认要关闭张三落水报警吗？',
        content: '关闭后将不再进行报警显示',
        ok: () => {
          console.log(item.alarmLogId)
          var params = new FormData()
          params.append('data', JSON.stringify({
            alarmLogId: item.alarmLogId
          }))
          this.$test
            .post(services.rescue.CLOSE_RESCUE, params)
            .then((res) => {
              console.log(res.data.result)
              if (res.data.result) {
                this.layer.personLayer.eachLayer(layer => {
                  if (layer.getAttributes().deviceId === item.deviceId) {
                    item.locationStatus = '0'
                    this.popupContent(item, layer)
                  }
                })
              }
            })
            .catch((res) => {

            })
        },
        cancel: () => {
          console.log('点击了取消')
        }
      })
    },
    appoint(item) { // 打开指派Modal
      console.log(item)
      this.$test
        .post(services.rescue.RESCUER_LIST, '')
        .then((res) => {
          this.rescueModal = true
          console.log(res)
          this.appointAlarmId = item.alarmLogId
          this.rescuer = res.data.dataList
        })
        .catch((res) => {

        })
    },
    cancel() {
      this.rescueModal = false
    },
    appointSubmit() { // 指派
      console.log(this.formValidate.rescue)
      this.$refs['formValidate'].validate(valid => {
        console.log(valid)
        if (valid) {
          var params = new FormData()
          params.append('data', JSON.stringify({
            alarmLogId: this.appointAlarmId,
            rescuersId: this.formValidate.rescue
          }))
          this.$test
            .post(services.rescue.ASSIGN_RESCUER, params)
            .then((res) => {
              if (res.data.result) {
                this.$Message.success('指派成功！')
                this.rescueModal = false
              } else {
                this.$Message.danger('指派失败！')
                this.rescueModal = false
              }
            })
            .catch((res) => {

            })
        }
      })
    },
    personTrack() {
      this.stopPlayback()
      this.trackMap.removeLayer(this.layersGroup)
      this.trackMap.removeLayer(this.pointsGroup)
      var item
      if (this.trackTypeCondition.currentIndex == 0) {
        item = this.trackSearch
        this.timelineList = []
      } else {
        item = this.trackSearchs[0]
      }
      if (!item) {
        return
      }
      console.log(item)
      console.log(this.trackMap.hasLayer(this.trackPath))
      if (this.trackMap.hasLayer(this.trackPath)) {
        this.trackMap.removeLayer(this.trackPath)
      }
    },
    trackClick() {
      this.trackModal = true
      var now = new Date()
      var year = now.getFullYear()
      var month = now.getMonth() + 1
      month >= 10 ? month : '0' + month
      var day = now.getDate() >= 10 ? now.getDate() : '0' + now.getDate()
      var hours =
          now.getHours() >= 10 ? now.getHours() : '0' + now.getHours()
      var minutes =
          now.getMinutes() >= 10
              ? now.getMinutes()
              : '0' + now.getMinutes()
      var seconds =
          now.getSeconds() >= 10
              ? now.getSeconds()
              : '0' + now.getSeconds()
      var statr = year +
          '-' +
          month +
          '-' +
          day +
          ' ' +
          '00:00:00'
      var end = year +
          '-' +
          month +
          '-' +
          day +
          ' ' +
          hours +
          ':' +
          minutes +
          ':' +
          seconds
      this.rangeDate = [statr, end]
    },
    playback() {
      var entityIds
      if (this.trackTypeCondition.currentIndex == 0) {
        if (!this.trackSearch.workEmployeeId) {
          this.$Message.warning('请选择人员！')
          return
        }
        entityIds = this.trackSearch.workEmployeeId
      } else {
        if (this.trackSearchs.length == 0) {
          this.$Message.warning('请选择人员！')
          return
        }
        entityIds = ''
        this.trackSearchs.forEach(e => {
          entityIds += e.workEmployeeId + ','
        })
        entityIds = entityIds.substring(0, entityIds.length - 1)
      }
      var params = {}
      if (!this.rangeDate) {
        this.$Message.warning('请选择时间！')
        return
      } else {
        params = {
          entityId: entityIds,
          timeType: 4,
          playbackRate: this.playbackRate,
          startTime: this.rangeDate[0],
          endTime: this.rangeDate[1]
        }
      }
      if (this.trackTypeCondition.currentIndex == 0) {
        this.$test
          .post(services.trackAnalysis.GET_SINGLE_TRACE, params)
          .then((res) => {
            this.timelineList = res.data.toolRecordList
            this.timelineList.forEach(e => {
              e.inTime = e.inTime.split(' ')[1]
              e.color = 'info'
              e.status = 'normal'
            })
            this.trackData = [res.data]
            var mapOfPerson = {}
            this.personList.forEach(e => {
              mapOfPerson[e.workEmployeeId] = e.workEmployeeName
            })
            this.trackData.forEach(e => {
              e.entityName = mapOfPerson[e.entityId]
            })
            this.startPlayback()
          })
          .catch((res) => {
            // 请求失败处理...
          })
      } else {
        this.$test
          .post(services.trackAnalysis.GET_MORE_TRACE, params)
          .then((res) => {
            this.trackData = res.data
            var mapOfPerson = {}
            this.personList.forEach(e => {
              mapOfPerson[e.workEmployeeId] = e.workEmployeeName
            })
            this.trackData.forEach(e => {
              e.entityName = mapOfPerson[e.entityId]
            })
            this.startPlaybackMulti()
          })
          .catch((res) => {
            // 请求失败处理...
          })
      }
    },
    startPlaybackMulti() {
      this.playbacking = true
      this.trackMap.removeLayer(this.layersGroup)
      this.layersGroup = new Ai.LayerGroup() // 定义图层数组
      this.trackMap.addLayer(this.layersGroup)
      this.trackMap.removeLayer(this.pointsGroup)
      this.pointsGroup = new Ai.LayerGroup() // 定义图层数组
      this.trackMap.addLayer(this.pointsGroup)
      this.trackData.forEach((e, index) => {
        var point = Ai.Point([e.traceList[0].latitude, e.traceList[0].longitude], {
          icon: Ai.Icon({
            // 设置图标URL路径
            iconUrl: 'static/images/track.png',
            // 设置图标大小
            iconSize: [40, 55],
            // 设置点对象和图标的相对偏移量
            iconAnchor: [20, 25]
          })
        })
        point.entityId = e.entityId
        this.pointsGroup.addLayer(point)
        var popup = Ai.Popup({
          maxWidth: 60,
          minWidth: 50,
          offset: [-3, -45],
          autoClose: false,
          autoPan: false,
          closeButton: false
        })
        popup.setLatLng(point.getLatLng())
        // 设置弹出框弹出内容
        popup.setContent('<div style="text-align: center;color: white;">' + e.entityName + '</div>')
        popup.entityId = e.entityId
        this.pointsGroup.addLayer(popup)
        popup.openOn(this.trackMap) // 需要先显示
        var newLineWktStr = 'LINESTRING ( '
        e.traceList.forEach(el => {
          (function(i, that) {
            var task = setTimeout(function() {
              that.pointsGroup.eachLayer(layer => {
                if (layer.entityId == e.entityId) {
                  layer.setLatLng([el.latitude, el.longitude])
                }
              })
              that.trackTime = el.createDate
              newLineWktStr += el.longitude + ' ' + el.latitude + ','
              that.getNewLine(newLineWktStr, index, e.entityId)
              if (el.isStopPlay) {
                that.playbacking = false
              }
            }, (i) * 1000)
            that.timeouts.push(task)
          })(el.playDurationTime, this)
        })
      })
      var arr = []
      this.pointsGroup.eachLayer(layer => {
        arr.push(layer)
      })
      this.trackMap.setViewPort(arr)
      this.trackMap.setZoom(this.trackMap.getZoom() - 1)
    },
    stopPlayback() {
      this.playbacking = false
      this.timeouts.forEach(e => {
        clearTimeout(e)
      })
      this.timeouts = []
    },
    startPlayback() {
      for (let j = 0; j < this.timelineList.length; j++) {
        this.timelineList[j].color = 'info'
        this.timelineList[j].status = 'normal'
      }
      this.playbacking = true
      this.trackMap.removeLayer(this.layersGroup)
      this.layersGroup = new Ai.LayerGroup() // 定义图层数组
      this.trackMap.addLayer(this.layersGroup)
      var lineWktStr = 'LINESTRING ( '
      this.trackData[0].traceList.forEach(e => {
        lineWktStr += e.longitude + ' ' + e.latitude + ','
      })
      lineWktStr = lineWktStr.substring(0, lineWktStr.length - 1)
      lineWktStr += ' )'
      var lineLayer = new Ai.Polyline(lineWktStr, {color: 'gray', opacity: 1.0})
      this.layersGroup.addLayer(lineLayer)
      this.trackMap.setViewPort([lineLayer])
      this.trackMap.setZoom(this.trackMap.getZoom() - 1)

      var point = Ai.Point([this.trackData[0].traceList[0].latitude, this.trackData[0].traceList[0].longitude], {
        icon: Ai.Icon({
          // 设置图标URL路径
          iconUrl: 'static/images/track.png',
          // 设置图标大小
          iconSize: [40, 55],
          // 设置点对象和图标的相对偏移量
          iconAnchor: [20, 25]
        }),
        draggable:true
      })
      var popup = Ai.Popup({
        maxWidth: 60,
        minWidth: 50,
        offset: [-3, -45],
        autoClose: false,
        autoPan: false,
        closeButton: false
      })
      popup.setLatLng(point.getLatLng())
      // 设置弹出框弹出内容
      popup.setContent('<div style="text-align: center;color: white;">' + this.trackData[0].entityName + '</div>')
      this.trackMap.removeLayer(this.pointsGroup)
      this.pointsGroup = new Ai.LayerGroup() // 定义图层数组
      this.trackMap.addLayer(this.pointsGroup)
      this.pointsGroup.addLayer(point)
      this.pointsGroup.addLayer(popup)
      popup.openOn(this.trackMap) // 需要先显示
      var lastOne = this.trackData[0].traceList[this.trackData[0].traceList.length - 1]
      var newLineWktStr = 'LINESTRING ( '
      this.trackData[0].traceList.forEach(e => {
        (function(i, that) {
          var task = setTimeout(function() {
            that.pointsGroup.eachLayer(layer => {
              layer.setLatLng([e.latitude, e.longitude])
            })
            that.trackTime = e.createDate
            newLineWktStr += e.longitude + ' ' + e.latitude + ','
            that.getNewLine(newLineWktStr, 1, that.trackData[0].entityId)
            if (e === lastOne) {
              that.playbacking = false
              that.timelineList[that.timelineList.length - 1].color = 'success'
              that.timelineList[that.timelineList.length - 1].status = 'normal'
            } else {
              for (let j = 0; j < that.timelineList.length; j++) {
                if (e.toolIndex > j) {
                  that.timelineList[j].color = 'success'
                } else {
                  that.timelineList[j].color = 'info'
                }
                if (e.toolIndex == j) {
                  that.timelineList[j].status = 'active'
                } else {
                  that.timelineList[j].status = 'normal'
                }
              }
            }
          }, (i) * 1000)
          that.timeouts.push(task)
        })(e.playDurationTime, this)
      })
    },
    getNewLine(newLineWktStr, colorIndex, entityId) {
      var color
      if (colorIndex < 8) {
        color = this.lineColors[colorIndex]
      } else {
        color = this.getRandomColor()
      }
      this.layersGroup.eachLayer(layer => {
        if (layer.entityId == entityId) {
          this.map.removeLayer(layer)
        }
      })
      newLineWktStr = newLineWktStr.substring(0, newLineWktStr.length - 1)
      newLineWktStr += ' )'
      var lineLayer = new Ai.Polyline(newLineWktStr, {color: color, opacity: 1.0})
      lineLayer.entityId = entityId
      this.layersGroup.addLayer(lineLayer)
    },
    getRandomColor() { // 获取随机颜色
      return '#' + Math.floor(Math.random() * 0xffffff).toString(16)
    }
  }
}
</script>
