<template>
  <div class="screen-container">
    <div class="bg-hex"></div>
    <div class="scan-effect"></div>
    <ScreenHeader />
    <div class="screen-content">
      <!-- 1区：3个面板 -->
      <div class="panel-col">
        <EventStats />
        <SafetyCompliance />
        <PersonnelTrend />
      </div>
      <!-- 2区：2个面板 -->
      <div class="panel-col">
        <EnvMonitorStats />
        <EquipmentStats />
        <ChemicalsStats />
      </div>
      <!-- 3区：实时监控 -->
      <div class="center-col">
        <SecurityMonitor />
      </div>
      <!-- 4区：环境感知 + 预警 -->
      <div class="panel-col col-right">
        <LabEnvironment />
        <AlarmInfo />
      </div>
    </div>
    <!-- 报警弹窗 -->
    <AlarmWindow
      v-if="showAlarm"
      :alarm-data="alarmData"
      @close="showAlarm = false"
    />
  </div>
</template>

<script>
import mqtt from 'mqtt'
import ScreenHeader from '@/components/ScreenHeader.vue'
import EventStats from '@/components/EventStats.vue'
import SafetyCompliance from '@/components/SafetyCompliance.vue'
import PersonnelTrend from '@/components/PersonnelTrend.vue'
import EnvMonitorStats from '@/components/EnvMonitorStats.vue'
import EquipmentStats from '@/components/EquipmentStats.vue'
import ChemicalsStats from '@/components/ChemicalsStats.vue'
import SecurityMonitor from '@/components/SecurityMonitor.vue'
import LabEnvironment from '@/components/LabEnvironment.vue'
import AlarmInfo from '@/components/AlarmInfo.vue'
import AlarmWindow from '@/components/alarmWindow/index.vue'
import { getConfigByType } from '@/api/auth'
import { selectTriggerInfo } from '@/api/screen'
import { Decrypt } from '@/utils/crypto'

export default {
  name: 'Screen',
  components: {
    ScreenHeader,
    EventStats,
    SafetyCompliance,
    PersonnelTrend,
    EnvMonitorStats,
    EquipmentStats,
    ChemicalsStats,
    SecurityMonitor,
    LabEnvironment,
    AlarmInfo,
    AlarmWindow
  },
  data() {
    return {
      showAlarm: false,
      alarmData: {},
      mqttClient: null
    }
  },
  mounted() {
    this.initMqttConfig()
    this.selectTriggerInfo();
  },
  beforeDestroy() {
    if (this.mqttClient) {
      this.mqttClient.end(true)
      this.mqttClient = null
    }
  },
  methods: {
    async initMqttConfig() {
      try {
        const res = await getConfigByType({ category: 2, configType: 5 })
        if (res.code === 200 && res.data && res.data.configValue) {
          const cfg = JSON.parse(res.data.configValue)
          let urlText = window.location.href.split('://')[0]+'://';
          let outerNet = window.location.href.indexOf(cfg.ipIdentify) == -1;
          if(outerNet){//外网
            localStorage.setItem('mqttUrl', 'wss://'+Decrypt(cfg.mqttExtranetUrl))
            localStorage.setItem('mqttUser', Decrypt(cfg.mqttExtranetUser))
            localStorage.setItem('mqttPassword', Decrypt(cfg.mqttExtranetPassword))
            localStorage.setItem('fileBrowseEnvironment',urlText+Decrypt(cfg.fileBrowseEnvironmentExtranet))
            localStorage.setItem('fileBrowseEnvironmentExtranet',urlText+Decrypt(cfg.fileBrowseEnvironmentExtranet))
          }else{
            localStorage.setItem('mqttUrl', 'ws://'+Decrypt(cfg.mqttIntranetUrl))
            localStorage.setItem('mqttUser', Decrypt(cfg.mqttIntranetUser))
            localStorage.setItem('mqttPassword', Decrypt(cfg.mqttIntranetPassword))
            localStorage.setItem('fileBrowseEnvironment',urlText+Decrypt(cfg.fileBrowseEnvironment))
            localStorage.setItem('fileBrowseEnvironmentExtranet',urlText+Decrypt(cfg.fileBrowseEnvironmentExtranet))
          }
        }
      } catch (e) {
        // 配置获取失败不影响页面正常使用
      }
      this.initMqtt()
    },
    initMqtt() {
      let self = this;
      const url      = localStorage.getItem('mqttUrl')
      const username = localStorage.getItem('mqttUser')
      const password = localStorage.getItem('mqttPassword')
      if (!url) return

      try {
        this.mqttClient = mqtt.connect(url, { username, password, reconnectPeriod: 5000 })

        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) => {
          if (this.showAlarm) return
          try {
            const payload = JSON.parse(message.toString())
            if(payload){
              this.selectTriggerInfo();
            }
          } catch (e) {
            // 忽略
          }
        })

        this.mqttClient.on('error', () => {
          this.mqttClient.end(true)
        })
      } catch (e) {
        // MQTT 连接失败不影响页面正常使用
      }
    },

    async selectTriggerInfo() {
      const res = await selectTriggerInfo()
      if (res.code === 200 && res.data && res.data.length) {
        // res.data[0].bindingSensorList = res.data[0].bindingSensorList
        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
            }
          }
        }
        console.log('res.data[0].bindingSensorList',res.data[0].bindingSensorList);
        console.log('res.data[0].triggerUploadData',res.data[0].triggerUploadData);
        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" scoped>
.screen-container {
  width: 9600px;
  height: 2800px;
  position: relative;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  background: $bg-deep;
}

/* 六角形背景纹理 */
.bg-hex {
  position: absolute;
  inset: 0;
  pointer-events: none;
  z-index: 0;
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='60' height='52' viewBox='0 0 60 52'%3E%3Cpolygon points='30,2 58,17 58,47 30,52 2,47 2,17' fill='none' stroke='rgba(30,144,255,0.05)' stroke-width='1'/%3E%3C/svg%3E");
  background-size: 150px 130px;

  &::after {
    content: '';
    position: absolute;
    inset: 0;
    background: radial-gradient(ellipse at 50% 50%, transparent 25%, #030e1f 85%);
  }
}

/* 主内容区域：4列精确像素布局 */
.screen-content {
  flex: 1;
  min-height: 0;
  display: grid;
  grid-template-columns: 1892px 1414px 4282px 1892px;
  column-gap: 20px;
  padding: 20px 30px;
  position: relative;
  z-index: 2;
}

.panel-col {
  display: flex;
  flex-direction: column;
  gap: 18px;
  min-height: 0;
}

.center-col {
  display: flex;
  flex-direction: column;
  min-height: 0;
  position: relative;
}

/* 第1列：基本情况(956) + 安全分级(1017) + 人数走势(591) */
.panel-col:nth-child(1) {
  > :nth-child(1) { flex: 956; min-height: 0; }
  > :nth-child(2) { flex: 1017; min-height: 0; }
  > :nth-child(3) { flex: 591; min-height: 0; }
}

/* 第2列：设备统计(666) + 设备分类(1916) */
.panel-col:nth-child(2) {
  > :nth-child(1) { flex: 666; min-height: 0; }
  /*> :nth-child(2) { flex: 1916; min-height: 0; }*/
}

/* 第4列：环境感知(1807) + 风险预警(775) */
.col-right {
  > :first-child { flex: 1807; min-height: 0; }
  > :last-child { flex: 775; min-height: 0; }
}
</style>
