<template>
  <div class="dashboard-container">
    <panel-group ref="panelgroup"/>
    <el-row>
      <!--井盖布防撤防统计-->
      <el-col v-if="hasPerm('/well/countByBfzt')" :span="10">
        <el-card shadow="never">
          <well-count-by-bfzt/>
        </el-card>
      </el-col>
      <!--井类型统计-->
      <el-col v-if="hasPerm('/statics/wellStaticsByType')" :span="14">
        <el-card shadow="never">
          <well-count-by-type/>
        </el-card>
      </el-col>
      <!--设备数量统计-->
      <el-col v-if="hasPerm('/statics/deviceStaticsByType')" :span="14">
        <el-card shadow="never">
          <device-count/>
        </el-card>
      </el-col>
      <!--设备在线情况统计-->
      <el-col v-if="hasPerm('/statics/deviceStaticsByStatus')" :span="10">
        <el-card shadow="never">
          <device-count-by-online/>
        </el-card>
      </el-col>
      <!--7日报警次数统计-->
      <el-col v-if="hasPerm('/statics/alarmsByDay')" :span="10">
        <el-card shadow="never">
          <alarm-by-days/>
        </el-card>
      </el-col>
      <!--工单数量统计-->
      <el-col v-if="hasPerm('/statics/jobsByDept')" :span="14">
        <el-card shadow="never">
          <job-by-status/>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import PanelGroup from './components/PanelGroup'
import WellCountByBfzt from './components/WellCountByBfzt'
import WellCountByType from './components/WellCountByType'
import DeviceCount from './components/DeviceCount'
import DeviceCountByOnline from './components/DeviceCountByOnline'
import AlarmByDays from './components/AlarmByDays'
import JobByStatus from './components/JobByStatus'
import ResetPwd from '../system/user/resetPwd'

export default {
  name: 'Dashboard',
  components: {
    ResetPwd,
    JobByStatus,
    AlarmByDays,
    PanelGroup,
    WellCountByBfzt,
    WellCountByType,
    DeviceCount,
    DeviceCountByOnline
  },
  data() {
    return {
      // wsPath: 'ws://139.198.17.115:20004/smartwell/websocket/'
      wsPath: 'wss://yjaqjk.bda.gov.cn/smartwell/websocket/',
      // wsPath: 'wss://smartlog.work/smartwell/websocket/',
      showSetPwd: this.$store.getters.resetPwd,
      socket: null, // websocket对象
      ws_timeout_timer: null, // 超时计时器
      ws_live_timer: null, // 在线计时器
      clock: 30000 // 时间
    }
  },
  computed: {
    ...mapGetters([
      'name',
      'roleNames',
      'roleTips',
      'wellTypes',
      'deviceTypes',
      'communications',
      'area'
    ])
  },
  mounted() {
    if (this.socket == null) {
      this.webSocket()
    }
  },
  activated() {
    this.$refs.panelgroup.refreshData()
    if (this.socket == null) {
      this.webSocket()
    }
  },
  methods: {
    webSocket() {
      console.log('websocket')
      const that = this
      if (typeof (WebSocket) === 'undefined') {
        this.$notify({
          title: '提示',
          message: '当前浏览器无法接收实时报警信息，请使用谷歌浏览器或360浏览器极速模式！',
          type: 'warning',
          duration: 0
        })
      } else {
        // 获取token保存到vuex中的用户信息，此处仅适用于本项目，注意删除或修改
        // 实例化socket，这里我把用户名传给了后台，使后台能判断要把消息发给哪个用户，其实也可以后台直接获取用户IP来判断并推送
        const socketUrl = this.wsPath + this.$store.getters.id
        console.log(socketUrl)
        this.socket = new WebSocket(socketUrl)
        // 监听socket打开
        this.socket.onopen = function() {
          console.log('浏览器WebSocket已打开')
          // 加入心跳监测
          that.startHeartBeat()
          console.log(new Date())
        }
        // 监听socket消息接收
        this.socket.onmessage = function(msg) {
          // 转换为json对象
          const data = JSON.parse(msg.data)
          console.log(data)
          if (data.type === 'alarm') {
            that.$refs.panelgroup.refreshData()
            that.$notify({
              title: '新报警来了',
              // 这里也可以把返回信息加入到message中显示
              message: data.message,
              type: 'warning',
              onClick: () => {
                that.$router.push({
                  path: '/overview',
                  query: { refresh: true }
                })
              }
            })
            that.playAudio()
          } else if (data.type === 'overtimeGet') {
            that.$notify({
              title: '有新超时未接收工单',
              // 这里也可以把返回信息加入到message中显示
              message: data.message,
              type: 'warning',
              onClick: () => {
                that.$router.push({
                  path: '/listOvertimeGetJob',
                  query: { refresh: true }
                })
              }
            })
          } else if (data.type === 'overtimeHandle') {
            that.$notify({
              title: '有新超时未处理工单',
              // 这里也可以把返回信息加入到message中显示
              message: data.message,
              type: 'warning',
              onClick: () => {
                that.$router.push({
                  path: '/listOvertimeHandleJob',
                  query: { refresh: true }
                })
              }
            })
          }
          clearTimeout(this.ws_live_timer)
          clearTimeout(this.ws_timeout_timer)
          this.startHeartBeat()
        }
        // 监听socket错误
        this.socket.onerror = function() {
          that.$notify({
            title: '服务器错误',
            message: '无法接收实时报警信息,请检查服务器后重新刷新页面',
            type: 'error',
            duration: 0
          })
        }
        // 监听socket关闭
        this.socket.onclose = function(e) {
          console.log('WebSocket已关闭')
          console.log(e)
          console.log(new Date())
          that.socket = null
        }
      }
    },
    startHeartBeat() {
      const that = this
      const socket = this.socket
      this.ws_live_timer = setTimeout(function() {
        console.log('心跳发送')
        socket.send('heartbeat')
        // 倒计时，时间超了断开连接
        that.ws_timeout_timer = setTimeout(function() {
          socket.close()
        }, that.clock)
      }, that.clock)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
  }
  &-text {
    font-size: 30px;
    line-height: 46px;
  }
}
</style>
