<template>
  <div class="orientation-container">
    <div class="top-container">
      <div class="person-info">
        <div>全部<span class="number">{{ personStatistics.all }}</span>人</div>
        <div>
          <div class="normal"></div>
          正常<span class="number">{{ personStatistics.normal }}</span>人
        </div>
        <div>
          <div class="off-line"></div>
          离线<span class="number">{{ personStatistics.offLine }}</span>人
        </div>
        <div>
          <div class="out-line"></div>
          违规<span class="number">{{ personStatistics.outLine }}</span>人
        </div>
        <div>
          <div class="sos"></div>
          SOS<span class="number">{{ personStatistics.sos }}</span>人
        </div>
        <div class="time">当前时间：{{ nowDate | dateFormat }}</div>
      </div>
      <div class="right-content">
        <t-button
          color="success"
          icon="map-marker-outline"
          @click="
            () => {
              trackModal = true;
            }
          "
        >轨迹</t-button
        >
        <div>悬浮窗<t-switch rounded></t-switch></div>
      </div>
    </div>
    <div id="div1" style="height: 100%"></div>
    <div class="label">
      <div class="item">
        <div :class="mapShow.sos?'':'cancel'" @click="showOrHide(layer.personLayer,'sos',['4','5'])">
          <div class="sos"></div>
          <div>SOS</div>
        </div>
        <div :class="mapShow.offLine?'':'cancel'" @click="showOrHide(layer.personLayer,'offLine',['1'])">
          <div class="offline"></div>
          <div>离线</div>
        </div>
        <div :class="mapShow.outLine?'':'cancel'" @click="showOrHide(layer.personLayer,'outLine',['2','3'])">
          <div class="outline"></div>
          <div>违规</div>
        </div>
        <div :class="mapShow.normal?'':'cancel'" @click="showOrHide(layer.personLayer,'normal',['0'])">
          <div class="normal"></div>
          <div>正常</div>
        </div>
      </div>
      <div class="item">
        <div :class="mapShow.fenji?'':'cancel'" @click="showOrHide(layer.equipmentLayer,'fenji',['002'])">
          <div class="fenji"></div>
          <div>风机</div>
        </div>
        <div :class="mapShow.shengyazhan?'':'cancel'" @click="showOrHide(layer.equipmentLayer,'shengyazhan',['003'])">
          <div class="shengyazhan"></div>
          <div>升压站</div>
        </div>
        <div :class="mapShow.chuanbo?'':'cancel'" @click="showOrHide(layer.equipmentLayer,'chuanbo',['001'])">
          <div class="chuanbo"></div>
          <div>船舶</div>
        </div>
      </div>
      <div class="item">
        <div :class="mapShow.zyqy?'':'cancel'" @click="showOrHide(layer.areaLayer,'zyqy',['2'])">
          <div class="zyqy"></div>
          <div>作业区域</div>
        </div>
        <div :class="mapShow.dzwl?'':'cancel'" @click="showOrHide(layer.areaLayer,'dzwl',['3'])">
          <div class="dzwl"></div>
          <div>电子围栏</div>
        </div>
      </div>
    </div>

    <t-modal
      :visibled.sync="trackModal"
      :footer-visibled="false"
      :mask-closable="false"
      :width="1200"
      title="历史轨迹"
    >
      <div class="track-modal-container">
        <div class="track-modal-left">
          <t-input
            v-model="trackSearch"
            icon="search-outline"
            icon-placement="right"
            placeholder="请输入姓名或终端编号"
            style="width: 200px"
          ></t-input>
          <div>
            <div>张三</div>
            <div>张三</div>
            <div>张三</div>
            <div>张三</div>
          </div>
        </div>
        <div class="track-modal-right">
          <div style="display: flex">
            <t-button-group>
              <t-button
                v-for="(item, index) in trackTimeList"
                :class="
                  index == trackQueryCondition.currentIndex ? 'active' : ''
                "
                :key="index"
                @click="changeTrackTime(index)"
              >{{ item }}</t-button
              >
            </t-button-group>
            <t-date-picker
              v-show="trackQueryCondition.currentIndex === 3"
              v-model="rangeDate"
              style="width: 250px"
              type="dateRange"
              placeholder="请选择时间"
              @date-change="onChangeDate"
            ></t-date-picker>
            <div style="display: flex">
              <div>速度</div>
              <t-select>
                <t-option>1x</t-option>
                <t-option>2x</t-option>
              </t-select>
            </div>
            <t-button color="success" icon="video-outline">回放</t-button>
            <t-button color="secondary" icon="upload-outline" @click="toExport"
            >导出至Excel</t-button
            >
          </div>
          <div id="track-map" style="height: 94%"></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>张三</t-option>
            <t-option>李四</t-option>
          </t-select>
        </t-form-item>
      </t-form>
      <div slot="footer">
        <t-button @click="cancel">取消</t-button>
        <t-button class="submit-button" @click="appoint()">指派</t-button>
      </div>
    </t-modal>
  </div>
</template>

<script>
import './orientation.scss'
import services from '../../conf/services'
import EventBus from '../../bus'
import { GIS_CENTER, GIS_ZOOM, GIS_SEA_LAYER_URL, GIS_SEA_URL } from '@/constants'
export default {
  filters: {
    dateFormat(value) {
      var year = value.getFullYear()
      var month =
        value.getMonth() >= 10 ? value.getMonth() : '0' + value.getMonth()
      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 {
      map: null,
      pointsarr: null,
      personStatistics: {
        all: 0,
        offLine: 0,
        outLine: 0,
        sos: 0,
        normal: 0
      },
      polylinearr:
        '122.0352 32.4444,122.0372 32.4444,122.0400 32.4366,122.2922 32.4233',
      popup: null,
      shadow: false,
      dataList: [
        {
          name: '王小明',
          number: 'ZDBH0001',
          type: '落水告警',
          Longitude: '32.4233',
          latitude: '122.2922',
          alarmTime: '2020.7.10 08:21:43',
          newMarkerTime: '2020.7.10 08:21:43',
          rescuePerson: '海事局A',
          rescueTime: '2020.7.3 11:22:16',
          rescueDuration: '10小时39分钟'
        },
        {
          name: '王小明1',
          number: 'ZDBH0002',
          type: '正常',
          Longitude: '32.333',
          latitude: '122.0822',
          alarmTime: '2020.7.10 08:21:43',
          newMarkerTime: '2020.7.10 08:21:43',
          rescuePerson: '海事局A',
          rescueTime: '2020.7.3 11:22:16',
          rescueDuration: '10小时39分钟'
        },
        {
          name: '王小明2',
          number: 'ZDBH0003',
          type: '正常',
          Longitude: '32.4444',
          latitude: '122.0352',
          alarmTime: '2020.7.10 08:21:43',
          newMarkerTime: '2020.7.10 08:21:43',
          rescuePerson: '海事局A',
          rescueTime: '2020.7.3 11:22:16',
          rescueDuration: '10小时39分钟'
        },
        {
          name: '王小明3',
          number: 'ZDBH0004',
          type: '离线',
          Longitude: '32.555',
          latitude: '121.0752',
          alarmTime: '2020.7.10 08:21:43',
          newMarkerTime: '2020.7.10 08:21:43',
          rescuePerson: '海事局A',
          rescueTime: '2020.7.3 11:22:16',
          rescueDuration: '10小时39分钟'
        },
        {
          name: '王小明4',
          number: 'ZDBH0005',
          type: '落水告警',
          Longitude: '32.466',
          latitude: '122.04322',
          alarmTime: '2020.7.10 08:21:43',
          newMarkerTime: '2020.7.10 08:21:43',
          rescuePerson: '海事局A',
          rescueTime: '2020.7.3 11:22:16',
          rescueDuration: '10小时39分钟'
        }
      ],
      nowDate: new Date(),
      modal: false,
      trackModal: false,
      trackSearch: '',
      trackTimeList: ['-10min', '-1h', '本日', '自定义'],
      trackQueryCondition: {
        currentIndex: 0
      },
      trackMap: null,
      rangeDate: '',
      rescueModal: false,
      formValidate: {
        rescue: ''
      },
      ruleValidate: {
        rescue: [
          {
            required: true,
            message: '救援人员不能为空',
            trigger: 'blur'
          }
        ]
      },
      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
      },
      fitBounds: []
    }
  },
  mounted() {
    this.getGisToken().then(() => {
      this.initMap()
      this.initTrackMap()
    })
    setInterval(() => {
      this.nowDate = new Date()
    }, 1000)
    EventBus.$on('person', (msg) => {
      this.changeLocation(msg)
    })
  },
  methods: {
    async getGisToken() {
      await this.$test
        .post(services.mapTag.GET_TOKEN, '')
        .then((res) => {
          this.$store.commit('setGisToken', res.data.result.ak)
        })
        .catch((res) => {
          // 请求失败处理...
        })
    },
    changeLocation(msg) {
      var obj = JSON.parse(msg.body)
      this.layer.personLayer.eachLayer((e) => {
        if (e.getAttributes().deviceId == obj.deviceId) {
          e.setLatLng([obj.latitude, obj.longitude])
          this.popupContent(obj, e)
        }
      })
    },
    popupContent(e, point) {
      console.log(e, point)
      var icon, tips
      var callHelp = ''
      var other = ''
      var attributes = point.getAttributes()
      if (e.locationStatus == '0') {
        icon = '/static/images/normalworker.png'
        tips = '<div class="normal">正常</div>'
        if (attributes.locationStatus !== e.locationStatus) {
          if (attributes.locationStatus == '1') {
            this.personStatistics.normal++
            this.personStatistics.offLine--
          } else if (attributes.locationStatus == '2' || attributes.locationStatus == '3') {
            this.personStatistics.normal++
            this.personStatistics.outLine--
          } else if (attributes.locationStatus == '4' || attributes.locationStatus == '5') {
            this.personStatistics.normal++
            this.personStatistics.sos--
          }
        }
      } else if (e.locationStatus == '1') {
        icon = '/static/images/offlineworker.png'
        tips = '<div class="offline">离线</div>'
        if (attributes.locationStatus !== e.locationStatus) {
          if (attributes.locationStatus == '0') {
            this.personStatistics.offLine++
            this.personStatistics.normal--
          } else if (attributes.locationStatus == '2' || attributes.locationStatus == '3') {
            this.personStatistics.offLine++
            this.personStatistics.outLine--
          } else if (attributes.locationStatus == '4' || attributes.locationStatus == '5') {
            this.personStatistics.offLine++
            this.personStatistics.sos--
          }
        }
      } else if (e.locationStatus == '2' || e.locationStatus == '3') {
        icon = '/static/images/outlineworker.png'
        tips = '<div class="outline">违规</div>'
        if (e.locationStatus == '2') {
          other = '<div class="row outline">' +
                  '<div>定点停留超时</div>' +
                  '<div>' + e.fixedLong + '</div>' +
                  '</div>'
        } else {
          other = '<div class="row outline">' +
                  '<div>进入时间</div>' +
                  '<div>' + e.inDate + '</div>' +
                  '</div>'
        }
        if (attributes.locationStatus !== e.locationStatus) {
          if (attributes.locationStatus == '0') {
            this.personStatistics.outLine++
            this.personStatistics.normal--
          } else if (attributes.locationStatus == '1') {
            this.personStatistics.outLine++
            this.personStatistics.offLine--
          } else if (attributes.locationStatus == '4' || attributes.locationStatus == '5') {
            this.personStatistics.outLine++
            this.personStatistics.sos--
          }
        }
      } else if (e.locationStatus == '4' || e.locationStatus == '5') {
        icon = '/static/images/sosworker.png'
        other = '<div class="row sos">' +
                  '<div>求救时间</div>' +
                  '<div>' + e.alarmDate + '</div>' +
                  '</div>' + '<div class="row sos">' +
                  '<div>求救时长</div>' +
                  '<div>' + e.alarmLong + '</div>' +
                  '</div>'
        tips = '<div class="sos">SOS</div>'
        callHelp = '<div style="display:flex;">' +
                  '<button class="point-out" onClick="window.Vue.rescueModal=true"><i style="font-size: 20px;" class="aidicon aidicon-user-outline"></i>指派</button>' +
                  '<button class="close-confirm" onClick="window.Vue.close()"><i style="font-size: 20px;" class="aidicon aidicon-close"></i>关闭</button>' +
                  '</div>'
        if (attributes.locationStatus !== e.locationStatus) {
          if (attributes.locationStatus == '0') {
            this.personStatistics.sos++
            this.personStatistics.normal--
          } else if (attributes.locationStatus == '1') {
            this.personStatistics.sos++
            this.personStatistics.offLine--
          } else if (attributes.locationStatus == '2' || attributes.locationStatus == '3') {
            this.personStatistics.sos++
            this.personStatistics.outLine--
          }
        }
      }
      point.setIcon(Ai.Icon({
        // 设置图标URL路径
        iconUrl: icon,
        // 设置图标大小
        iconSize: [20, 20],
        // 设置点对象和图标的相对偏移量
        iconAnchor: [0, 0]
      }))
      point.setAttributes(e)
      point.on('click', (pointE) => {
        var content =
                  '<div class="tips-item"><div class="top"><div class="user-pic"><t-icon icon="user-outline"></t-icon></div><div>' + e.userName + '</div>' + tips + '</div><div class="middle"><div class="row">' +
                  '<div>终端编号</div>' +
                  '<div>' + e.deviceNo + '</div>' +
                  '</div>' +
                  '<div class="row">' +
                  '<div>经度</div>' +
                  '<div>' + e.longitude + '</div>' +
                  '</div>' +
                  '<div class="row">' +
                  '<div>纬度</div>' +
                  '<div>' + e.latitude + '</div>' +
                  '</div>' + other +
                  '<div class="row">' +
                  '<div>最新定位时间</div>' +
                  '<div>' + e.newDate + '</div>' +
                  '</div></div></div>' + callHelp +
                  '</div></div>'
        Ai.Popup({
          minWidth: 300,
          offset: [0, -10],
          autoClose: true
        })
        // 设置弹出框弹出位置
          .setLatLng(point.getLatLng())
        // 设置弹出框弹出内容
          .setContent(content)
          .openOn(this.map)
      })
    },
    initMap() {
      if (this.map != null && this.map != '') {
        this.map.remove()
      }
      this.map = new Ai.Map('div1', {
        ak: this.$store.getters.getGisToken,
        center: GIS_CENTER,
        zoom: GIS_ZOOM
      })
      var maplayer
      maplayer = Ai.TileLayer(GIS_SEA_LAYER_URL)
      var la = Ai.WMTSLayer(
        GIS_SEA_URL,
        { opacity: 0.5 }
      )
      this.map.addLayer(maplayer)
      this.map.addLayer(la)

      Ai.Scale({ position: 'bottomright' }).addTo(this.map)
      Ai.Zoom({ type: 'small' }).addTo(this.map)
      // this.polyline()
      this.polygon()
      this.loadEquipment()
      this.loadPerson()
    },
    polyline() {
      var polylineLayer = new Ai.FeatureGroup()
      // 线绘制
      var lineWktStr = 'LINESTRING ( ' + this.polylinearr + ')'
      var polyline = new Ai.Polyline(lineWktStr, {
        color: 'green',
        opacity: 1.0
      })
      // this.polylinearr.arr(polyline);
      polylineLayer.addLayer(polyline)
      this.map.addLayer(polylineLayer)
    },
    polygon() { // 加载地图围栏
      var params = new FormData()
      this.$test
        .post(services.mapTag.GET_ALL_MAP_TAG, params)
        .then((res) => {
          // 请求成功处理...
          res.data.dataList.forEach((e) => {
            if (e.MAP_TAG_TYPE === '3') { // 电子围栏
              var polygon = Ai.Polygon(e.MAP_TAG_SHAPE, {
                color: '#A74B5C',
                opacity: 1.0,
                weight: 0
              })
              polygon.setAttributes(e)
              this.layer.areaLayer.addLayer(polygon)
              // this.fitBounds.push(polygon)
            } else if (e.MAP_TAG_TYPE === '2') { // 作业区域
              var polygon = Ai.Polygon(e.MAP_TAG_SHAPE, {
                color: '#438D65',
                opacity: 1.0,
                weight: 0
              })
              polygon.setAttributes(e)
              this.layer.areaLayer.addLayer(polygon)
              // this.fitBounds.push(polygon)
            }
          })
          this.map.addLayer(this.layer.areaLayer)
          // console.log(this.fitBounds)
          // this.map.fitBoundsForLayers(this.fitBounds)
        })
        .catch((res) => {
          // 请求失败处理...
        })
    },
    showSlip() {
      this.visible = true
    },
    loadEquipment() { // 加载地图设备
      var params = new FormData()
      this.$test
        .post(services.equipment.GET_ALL_EQUIPMENT, params)
        .then((res) => {
          // 请求成功处理...
          console.log(res.data)
          res.data.dataList.forEach((e) => {
            var icon = ''
            if (e.FACILITY_TYPE === '001') { // 船舶
              icon = '/static/images/船舶.png'
            } else if (e.FACILITY_TYPE === '002') { // 风机
              icon = '/static/images/风机.png'
            } else if (e.FACILITY_TYPE === '003') { // 升压站
              icon = '/static/images/升压站画面.png'
            }
            var point = Ai.Point([e.LATITUDE, e.LONGITUDE], {
              icon: Ai.Icon({
                // 设置图标URL路径
                iconUrl: icon,
                // 设置图标大小
                iconSize: [20, 20],
                // 设置点对象和图标的相对偏移量
                iconAnchor: [0, 0]
              })
            })
            point.setAttributes(e)
            this.layer.equipmentLayer.addLayer(point)
          })
          this.map.addLayer(this.layer.equipmentLayer)
        })
        .catch((res) => {
          // 请求失败处理...
        })
    },
    loadPerson() { // 加载地图人员
      this.personStatistics = {
        all: 0,
        offLine: 0,
        outLine: 0,
        sos: 0,
        normal: 0
      }
      var params = new FormData()
      this.$test
        .post(services.organization.PERSON_LOCATION, params)
        .then((res) => {
          this.personStatistics.all = res.data.dataList.length
          var layer
          res.data.dataList.forEach((e) => {
            var icon, tips
            var callHelp = ''
            if (e.locationStatus === '0') {
              icon = '/static/images/normalworker.png'
              layer = this.layer.normalLayer
              tips = '<div class="normal">正常</div>'
              this.personStatistics.normal++
            } else if (e.locationStatus === '1') {
              icon = '/static/images/offlineworker.png'
              layer = this.layer.offLineLayer
              tips = '<div class="offline">离线</div>'
              this.personStatistics.offLine++
            } else if (e.locationStatus === '2' || e.locationStatus === '3') {
              icon = '/static/images/outlineworker.png'
              layer = this.layer.outLineLayer
              tips = '<div class="outline">违规</div>'
              this.personStatistics.outLine++
            } else if (e.locationStatus === '4' || e.locationStatus === '5') {
              icon = '/static/images/sosworker.png'
              layer = this.layer.sosLayer
              tips = '<div class="sos">SOS</div>'
              callHelp = '<div style="display:flex;">' +
                  '<button class="point-out" onClick="window.Vue.rescueModal=true"><i style="font-size: 20px;" class="aidicon aidicon-user-outline"></i>指派</button>' +
                  '<button class="close-confirm" onClick="window.Vue.close()"><i style="font-size: 20px;" class="aidicon aidicon-close"></i>关闭</button>' +
                  '</div>'
              this.personStatistics.sos++
            }
            var point = Ai.Point([e.latitude, e.longitude], {
              icon: Ai.Icon({
                // 设置图标URL路径
                iconUrl: icon,
                // 设置图标大小
                iconSize: [20, 20],
                // 设置点对象和图标的相对偏移量
                iconAnchor: [0, 0]
              })
            })
            point.setAttributes(e)
            point.on('click', (pointE) => {
              var content =
                  '<div class="tips-item"><div class="top"><div class="user-pic"><t-icon icon="user-outline"></t-icon></div><div>' + e.userName + '</div>' + tips + '</div><div class="middle"><div class="row">' +
                  '<div>终端编号</div>' +
                  '<div>' + e.deviceNo + '</div>' +
                  '</div>' +
                  '<div class="row">' +
                  '<div>经度</div>' +
                  '<div>' + e.longitude + '</div>' +
                  '</div>' +
                  '<div class="row">' +
                  '<div>纬度</div>' +
                  '<div>' + e.latitude + '</div>' +
                  '</div>' +
                  '<div class="row">' +
                  '<div>最新定位时间</div>' +
                  '<div>' + e.newDate + '</div>' +
                  '</div></div></div>' + callHelp +
                  '</div></div>'
              Ai.Popup({
                minWidth: 300,
                offset: [0, -10],
                autoClose: true
              })
                // 设置弹出框弹出位置
                .setLatLng(point.getLatLng())
                // 设置弹出框弹出内容
                .setContent(content)
                .openOn(this.map)
            })
            // layer.addLayer(point)
            this.layer.personLayer.addLayer(point)
          })
          // this.map.addLayer(this.layer.sosLayer)
          // this.map.addLayer(this.layer.outLineLayer)
          // this.map.addLayer(this.layer.offLineLayer)
          // this.map.addLayer(this.layer.normalLayer)
          this.map.addLayer(this.layer.personLayer)
        })
        .catch((res) => {
          // 请求失败处理...
        })
    },
    showOrHide(layer, type, arr) {
      layer.eachLayer((e) => {
        if (arr.indexOf(e.getAttributes().locationStatus) != -1 || arr.indexOf(e.getAttributes().FACILITY_TYPE) != -1 || arr.indexOf(e.getAttributes().MAP_TAG_TYPE) != -1) {
          if (this.map.hasLayer(e)) {
            this.map.removeLayer(e)
            this.mapShow[type] = false
          } else {
            this.map.addLayer(e)
            this.mapShow[type] = true
          }
        }
      })
      // if (this.map.hasLayer(layer)) {
      //   this.map.removeLayer(layer)
      //   this.mapShow[type] = false
      // } else {
      //   this.map.addLayer(layer)
      //   this.mapShow[type] = true
      // }
    },
    changeTrackTime(index) {
      this.trackQueryCondition.currentIndex = index
    },
    initTrackMap() {
      if (this.trackMap != null && this.trackMap != '') {
        this.trackMap.remove()
      }
      this.trackMap = new Ai.Map('track-map', {
        ak: this.$store.getters.getGisToken,
        center: [39.915599, 122.406568]
      })
      var maplayer = null
      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)
    },
    onChangeDate() {},
    toExport() {},
    close(item) {
      this.$Confirm.confirm({
        title: '确认要关闭张三落水报警吗？',
        content: '关闭后将不再进行报警显示',
        ok: () => {
          console.log('点击了确定')
        },
        cancel: () => {
          console.log('点击了取消')
        }
      })
    },
    cancel() {
      this.rescueModal = false
    }
  }
}
</script>
