<template>
  <div id="app">
    <div class="viewport">
      <div class="screen" ref="screen">
        <router-view />
      </div>
    </div>
    <AlarmWindow
        v-if="showAlarm"
        :alarm-data="alarmData"
        @close="showAlarm = false"
    />
  </div>
</template>

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

export default {
  name: 'App',
  components: { AlarmWindow },
  data() {
    return {
      showAlarm: false,
      alarmData:null,
      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.getTriggerInfo();
      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(config.fileBrowseEnvironmentExtranet))
          localStorage.setItem('fileBrowseEnvironmentExtranet',urlText+Decrypt(config.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(config.fileBrowseEnvironment))
          localStorage.setItem('fileBrowseEnvironmentExtranet',urlText+Decrypt(config.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()
      if (res.code === 200 && res.data && res.data.length) {
        res.data[0].triggerUploadData = JSON.parse(res.data[0].triggerUploadData)
        for(let i=0;i<res.data[0].bindingSensorList.length;i++){
          for(let o=0;o<res.data[0].triggerUploadData.length;o++){
            if(res.data[0].bindingSensorList[i].code == res.data[0].triggerUploadData[o].code){
              res.data[0].triggerUploadData[o].max = res.data[0].bindingSensorList[i].max
              res.data[0].triggerUploadData[o].min = res.data[0].bindingSensorList[i].min
            }
          }
        }
        this.$set(this,'alarmData', res.data[0]);
        this.$set(this,'showAlarm',true);
      }else{
        this.$set(this,'showAlarm',false);
        this.$set(this,'alarmData', {});
      }
    }
  }
}
</script>

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