import Storage from 'store'
import { initData } from '@/api/data'
import { getMQTTCilentId } from '@/utils/mqtt'
import * as mqtt from 'mqtt'

export default {
  data() {
    return {
      dataVersion: '',
      messageTimer: null,
      msgConfig: {
        num: 0,
        total: 0,
        msg: null,
      },
      isPlay: Storage.get('isPlay'),
      message_close_time: 0,
      mqttClient: null,
    }
  },
  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
    },
  },
  mounted() {
    this.init()
    if (!this.isPlay) {
      this.$confirm('是否打开报警提示音？', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning',
      })
        .then(() => {
          Storage.set('isPlay', true)
          this.$message({
            type: 'success',
            message: '已打开提示音',
          })
        })
        .catch(() => {
          Storage.set('isPlay', false)
          this.$message({
            type: 'info',
            message: '未打开提示音',
          })
        })
    }
  },
  beforeDestroy() {
    this.mqttClient.end()
  },
  methods: {
    async init() {
      try {
        let res = await initData('System/Configure/GetConfigure', { value: 'message_close_time' })
        if (res.code === 20000) {
          if (res.data === +res.data) this.message_close_time = res.data * 1000
        }
      } catch (error) {
        console.log(error)
      }
      this.startMQTT()

      // if (!this.messageTimer) {
      //   this.messageTimer = setInterval(() => {
      //     this.getNewMessage()
      //   }, 3000)
      // }
      // this.$once('hook:beforeDestroy', () => {
      //   clearInterval(this.messageTimer)
      //   this.messageTimer = null
      // })
    },
    //开始MQTT接收
    startMQTT() {
      // 连接选项
      const options = {
        clean: true, // true: 清除会话, false: 保留会话
        keepalive: 60,
        connectTimeout: 4000, // 超时时间
        // 认证信息
        clientId: getMQTTCilentId('message'),
        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', function () {
        //订阅主题
        console.log('消息MQTT正在连接')
        _this.mqttClient.subscribe('Message/New')
      })
      this.mqttClient.on('message', (topic, message) => {
        if (topic == 'Online') {
          console.log('消息MQTT收到消息：', topic, message.toString())
        } else if ((topic = 'Message/New')) {
          this.receiveNewMessage(JSON.parse(message.toString()))
          //console.log(JSON.parse(message.toString()))
        }
      })
    },
    playMusic() {
      if (this.isPlay) {
        this.$refs.audio.currentTime = 0
        this.$refs.audio.play()
      }
    },
    receiveNewMessage(newMessage) {
      this.msgConfig.num = newMessage.Total
      if (newMessage.NewMessage) {
        this.$notify({
          title: '报警消息',
          type: 'warning',
          duration: this.message_close_time,
          offset: 100,
          showClose: true,
          message: newMessage.NewMessage.Content,
          onClick: () => {
            this.handleClickAlarm(newMessage.NewMessage)
          },
        })
        this.playMusic()
      }
    },
    // getNewMessage() {
    //   const param = {
    //     dataVersion: this.dataVersion
    //   }
    //   getNewMessage(param)
    //     .then(res => {
    //       const newMessages = res.data.newMessage
    //       this.msgConfig.num = res.data.total
    //       this.msgConfig.msgs = newMessages
    //       this.dataVersion = res.data.dataVersion
    //       newMessages.forEach(data => {
    //         // 测试数据
    //         // data.type = 'overmanAlarm'
    //         // data.personId = '391674535990009856'
    //         this.$notify({
    //           title: '报警消息',
    //           type: 'warning',
    //           duration: this.message_close_time,
    //           offset: 100,
    //           showClose: true,
    //           message: data.content,
    //           onClick: () => {
    //             this.handleClickAlarm(data)
    //           }
    //         })
    //         this.playMusic()
    //       })
    //     })
    //     .catch(err => {
    //       console.log(err)
    //     })
    // },
    handleClickAlarm(data) {
      // console.log(data)
      const { type, personId } = data
      switch (type) {
        case 'oneKeyAlarm':
        case 'crossInAlarm':
        case 'crossOutAlarm':
          this.$router.push({ path: '/positioning/map' })
          break
        case 'overmanAlarm':
        case 'undermanAlarm':
          this.$router.push({ path: '/positioning/track', query: { type, personId } })
          break
        default:
          break
      }
    },
  },
}
