<template>
  <div id="app">
    <div class="viewport">
      <div class="screen" ref="screen">
        <router-view />
      </div>
    </div>
    <AlertModal ref="alertModal" />
  </div>
</template>

<script>
import AlertModal from '@/components/AlertModal.vue'
import mqtt from 'mqtt'
import { getMqttConfig, getTriggerInfo } from '@/api'
import { Decrypt } from '@/utils/decrypt'

export default {
  name: 'App',
  components: { AlertModal },
  data() {
    return { mqttClient: null }
  },
  computed: {
    token() { return this.$store.state.token }
  },
  watch: {
    token(val) {
      if (val) {
        this.initMqttConfig().then(() => this.connectMqtt())
      } else {
        if (this.mqttClient) { this.mqttClient.end(); this.mqttClient = null }
      }
    }
  },
  mounted() {
    this.fitScreen()
    window.addEventListener('resize', this.fitScreen)
    if (this.$store.state.token) {
      this.initMqttConfig().then(() => this.connectMqtt())
    }
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.fitScreen)
    if (this.mqttClient) this.mqttClient.end()
  },
  methods: {
    fitScreen() {
      const scr = this.$refs.screen
      if (!scr) return
      const sw = 1920, sh = 1080
      const vw = window.innerWidth, vh = window.innerHeight
      const sx = vw / sw, sy = vh / sh
      scr.style.transform = `translate(-50%, -50%) scale(${sx}, ${sy})`
    },
    async initMqttConfig() {
      try {
        const res = await getMqttConfig()
        const config = JSON.parse(res.data.configValue)
        let urlText = window.location.href.split('://')[0]+'://';
        let outerNet = window.location.href.indexOf(config.ipIdentify) == -1;
        if(outerNet){//外网
          localStorage.setItem('mqttUrl', 'wss://'+Decrypt(config.mqttExtranetUrl))
          localStorage.setItem('mqttUser', Decrypt(config.mqttExtranetUser))
          localStorage.setItem('mqttPassword', Decrypt(config.mqttExtranetPassword))
          localStorage.setItem('fileBrowseEnvironment',urlText+Decrypt(obj.fileBrowseEnvironmentExtranet))
          localStorage.setItem('fileBrowseEnvironmentExtranet',urlText+Decrypt(obj.fileBrowseEnvironmentExtranet))
        }else{
          localStorage.setItem('mqttUrl', 'ws://'+Decrypt(config.mqttIntranetUrl))
          localStorage.setItem('mqttUser', Decrypt(config.mqttIntranetUser))
          localStorage.setItem('mqttPassword', Decrypt(config.mqttIntranetPassword))
          localStorage.setItem('fileBrowseEnvironment',urlText+Decrypt(obj.fileBrowseEnvironment))
          localStorage.setItem('fileBrowseEnvironmentExtranet',urlText+Decrypt(obj.fileBrowseEnvironmentExtranet))
        }
      } catch (e) {
        console.error('获取MQTT配置失败:', e)
      }
    },
    connectMqtt() {
      const url = localStorage.getItem('mqttUrl')
      const username = localStorage.getItem('mqttUser')
      const password = localStorage.getItem('mqttPassword')
      if (!url) return
      if (!/^(ws|wss|mqtt|mqtts):\/\//.test(url)) {
        console.error('MQTT URL 格式错误，缺少协议头:', url)
        return
      }

      this.mqttClient = mqtt.connect(url, { username, password })

      this.mqttClient.on('connect', () => {
        // this.mqttClient.subscribe('#')
        this.mqttClient.subscribe('lab/risk/plan/change', (err) => {
          if (!err) {
            console.log("预案-订阅成功:lab/risk/plan/change");
          }else{
            // console.log("预案-连接错误:" + err);
          }
        });
      })

      this.mqttClient.on('message', async (topic, message) => {
        try {
          const payload = JSON.parse(message.toString())
          if (payload) {
            this.getTriggerInfo();
          }
        } catch (e) {
          console.error('MQTT消息处理失败:', e)
        }
      })

      this.mqttClient.on('error', (err) => {
        console.error('MQTT连接错误:', err)
      })
    },
    async getTriggerInfo() {
      const res = await getTriggerInfo()
      const list = res.data || []
      if (list.length > 0) {
        const e = list[0]
        const obj = JSON.parse(e.triggerUploadData)[0]
        const deviceValue = obj.deviceValue
        const unit = obj.unit
        this.$refs.alertModal.show({
          lab: e.subName + (e.roomNum ? `(${e.roomNum})` : ''),
          building: [e.schoolName, e.buildName, e.floorName].filter(Boolean).join(' · '),
          unit: e.deptName,
          param: e.eventName,
          value: deviceValue+''+(unit=='-'?'':unit),
          person: e.adminName,
          phone: e.adminPhone,
          time: e.eventStartTime ? e.eventStartTime.replace('T', ' ') : '',
          buildId:e.buildId,
          floorId:e.floorId,
          subId:e.subId,
        })
      }else{
        this.$refs.alertModal.close();
      }
    }
  }
}
</script>

<style lang="scss">
#app {
  width: 100%;
  height: 100%;
}
</style>
