<template>
  <div id="body"
    :style="{ 'width': `${style.width}px`, 'height': `${style.height}px`, 'transform': `${style.transform}` }"
    class="background">
    <el-row style="z-index: 999">
      <div style="height: 80px; width: 100%">
        <!-- <img style="position: absolute;top: 0;left: 0;width: 100%;height: 80px;" src="@/assets/titleImg.png" alt=""> -->
        <div id="htmlTitleImg">
          <div style="display: flex">
            <div style="line-height: 80px;margin: 0 100px 0 590px;font-size: 43px;">数字孪生机床智能可视化监控</div>
            <div class="center-head">
              {{ year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second }}
            </div>
          </div>
        </div>
      </div>
    </el-row>
    <el-row>
      <div style="position: relative;height: 1080px;">
        <!--WEBGL渲染位置-->
        <div style="height: 100%; width: 100%;position: fixed;z-index: auto;top: 0px;left: 0px">
          <d-m-t ref="dmtCom" containerHeight="1080px" containerWidth="100%" style="z-index: 999;" />
        </div>
        <!-- 滚动列表 -->
        <div class="scroll-list">
          <div class="scroll-content">
            <div class="data-box" :key="item.Name" v-for="item in DeviceData_Config">
              <div style="width: 100%; height: 20px;">
                <div class="indicatorText" :style="{ 'background-color': getMachineStatusBGC(item.Status) }">
                  <span>{{ item.Name }}_{{ getMachineStatusText(item.Status) }}</span>
                </div>
              </div>
              <div class="item-list">
                <div class="item-list-item">
                  <div class="item-list-item-name">设备模式：</div>
                  <div class="item-list-item-value"  style="width: 70px;">{{ item.CurMode }}</div>
                  <div class="item-list-item-name" style="margin-left: 5px; width: 65px;">程序号：</div>
                  <div class="item-list-item-value">{{ item.Program }}</div>
                </div>
                <div class="item-list-item">
                  <div class="item-list-item-name">报警代码：</div> 
                  <div class="item-list-item-value"  style="width: 70px;">{{ item.AlarmNO }}</div>
                  <div class="item-list-item-name" style="margin-left: 5px; width: 65px;">转速：</div>
                  <div class="item-list-item-value item-list-item-name-red">{{ item.Speed }}</div>
                </div>
              </div>
              <table class="ZB">
                <tr>
                  <td style="width: 14%;">名称</td>
                  <td style="width: 17%;">值</td>
                </tr>
                <tr v-for="(ZBItem, index) in item.Axis" :key="index">
                  <td>{{ ZBItem.AxisName }}</td>
                  <td>{{ ZBItem.AxisValue }}</td>
                </tr>
              </table>
            </div>
          </div>
        </div>
      </div>
    </el-row>
  </div>
</template>

<script>
import { mqttIp, mqttPort } from '@/utils/request'
import mqtt from 'mqtt'
import DMT from '@/components/DMT/index'

export default {
  components: {
    DMT
  },
  name: 'MingLuo',
  data: function () {
    return {
      year: '',
      month: '',
      day: '',
      hour: '',
      minute: '',
      second: '',
      style: {
        width: '1920',
        height: '1080',
        transform: 'scaleY(1) scaleX(1) translate(-50%, -50%)'
      },
      DeviceData_Config: window.DeviceData_Config,
      mqttData: {
        关节位置: {
          J1: { 位置R1: 0, 位置R2: 0 },
          J2: { 位置R1: 0, 位置R2: 0 },
          J3: { 位置R1: 0, 位置R2: 0 },
          J4: { 位置R1: 0, 位置R2: 0 },
          J5: { 位置R1: 0, 位置R2: 0 },
          J6: { 位置R1: 0, 位置R2: 0 },
          J7: { 位置R1: 0, 位置R2: 0 }
        },
        关节ATI: {
          J1: { ATI力R1: 0, ATI力R2: 0 },
          J2: { ATI力R1: 0, ATI力R2: 0 },
          J3: { ATI力R1: 0, ATI力R2: 0 },
          J4: { ATI力R1: 0, ATI力R2: 0 },
          J5: { ATI力R1: 0, ATI力R2: 0 },
          J6: { ATI力R1: 0, ATI力R2: 0 }
        }
      }
    }
  },
  mounted() {
    const scope = this
    this.initMqtt()
    this.getNowTime()
    this.timer_2 = setInterval(this.getNowTime, 1000)

    scope.setScale()
    window.addEventListener('resize', () => {
      scope.setScale()
    })
  },
  beforeDestroy() {
    clearInterval(this.timer_2)
  },
  methods: {
    getNowTime() {
      const date = new Date()
      this.year = date.getFullYear()
      this.month = this.zeroFill(date.getMonth() + 1)
      this.day = this.zeroFill(date.getDate())
      this.hour = this.zeroFill(date.getHours())
      this.minute = this.zeroFill(date.getMinutes())
      this.second = this.zeroFill(date.getSeconds())
    },
    zeroFill(i) {
      if (i >= 0 && i <= 9) {
        return '0' + i
      } else {
        return i
      }
    },
    getScale() {
      const w = window.innerWidth / this.style.width
      const h = window.innerHeight / this.style.height
      return { x: w, y: h }
    },
    setScale() {
      const scale = this.getScale()
      this.style.transform = 'scaleY(' + scale.y + ') scaleX(' + scale.x + ') translate(-50%, -50%)'
    },
    //机台状态    0：离线 灰 ，10：停止 黄，15：暂停 黄，20：运行 绿，30：报警 红，大于等于60：禁用 灰
    getMachineStatusBGC(code) {
      code = parseInt(code)
      if (code === 0) {
        return '#868686' // 离线-灰色
      } else if (code === 10) {
        return '#FFC107' // 停止-黄色
      } else if (code === 15) {
        return '#FFC107' // 暂停-黄色
      } else if (code === 20) {
        return '#4CAF50' // 运行-绿色
      } else if (code === 30) {
        return '#F44336' // 报警-红色
      } else if (code >= 60) {
        return '#868686' // 禁用-灰色
      } else {
        return '#3c73ba' // 默认颜色
      }
    },
    getMachineStatusText(code) {
      code = parseInt(code)
      if (code === 0) {
        return '离线'
      } else if (code === 10) {
        return '停止'
      } else if (code === 15) {
        return '暂停'
      } else if (code === 20) {
        return '运行'
      } else if (code === 30) {
        return '报警'
      } else if (code >= 60) {
        return '禁用'
      } else {
        return '未知'
      }
    },
    initMqtt() {
      const scope = this
      const connection = {
        host: mqttIp,
        port: mqttPort,
        endpoint: '/mqtt',
        clean: true,
        connectTimeout: 4000,
        reconnectPeriod: 4000,
        clientId: 'mqttjs_3be2c321' + new Date().getTime(),
        username: 'DT_WEB1',
        password: ''
      }
      const subscription = {
        topic: window.dt_Config.mqttTopic,
        qos: 0
      }
      const { host, port, endpoint, ...options } = connection
      const connectUrl = `ws://${host}:${port}${endpoint}`
      try {
        this.mqttClient = mqtt.connect(connectUrl, options)
      } catch (error) {
        console.log('MQTT connect error', error)
      }

      this.mqttClient.on('connect', () => {
        this.$message.success('加载完成，连接MQTT服务器成功！')
        console.log('MQTT Connection succeeded!')
        const { topic, qos } = subscription
        this.mqttClient.subscribe(topic, { qos }, (error, res) => {
          if (error) {
            console.log('Subscribe to topics error', error)
          }
        })
      })
      this.mqttClient.on('error', error => {
        console.log('MQTT Connection failed', error)
        try {
          scope.$message.error('MQTT服务器连接失败')
          if (scope.IsAllowConnect) {
            scope.$message.warning('重新连接MQTT服务器')
            console.log('重新连接MQTT服务器')
            setTimeout(function () {
              scope.initMqtt()
            }, 5000)
          }
        } catch (exception) {
          const error = exception.toString()
          scope.$message.error('MQTT服务器出现错误,关闭连接' + error)
        }
      })
      this.mqttClient.on('message', (topic, message) => {
        try {
          scope.websocketonmessage({ data: message.toString() })
        } catch (exception) {
          console.log(exception.toString())
        }
      })
    },
    websocketonmessage(msg) {
      this.msg = msg
      try {
        var arrays_signal = msg.data.split('|')
        if (arrays_signal.length < 3) {
          console.error('消息格式不正确:', msg.data)
          return
        }
        var interFaceType = arrays_signal[0]
        var dataType = arrays_signal[1]
        var m_data = arrays_signal[2]

        // 调试输出原始数据
        console.log('收到原始数据:', m_data)

        switch (interFaceType) {
          case 'MES':
            switch (dataType) {
              case 'C_B_DeviceInfo': {
                {
                  try {
                    // 尝试清理数据中的特殊字符
                    m_data = m_data.trim()
                    const deviceInfoArray = JSON.parse(m_data)
                    console.log('接收到设备信息', deviceInfoArray)

                    // 处理每个设备信息
                    deviceInfoArray.forEach(deviceInfo => {
                      // 查找本地配置中对应的设备
                      const deviceIndex = this.DeviceData_Config.findIndex(item => item.Id === deviceInfo.Id)

                      // 如果找到对应设备，更新其属性
                      if (deviceIndex !== -1) {
                        const localDevice = this.DeviceData_Config[deviceIndex]

                        // 更新基本属性（仅更新本地已定义的属性）
                        const fieldsToUpdate = [
                          'Name', 'Status', 'Program', 'Speed', 'MachName', 'AlarmNO', 'CurMode'
                        ]

                        fieldsToUpdate.forEach(field => {
                          if (field in localDevice && field in deviceInfo) {
                            localDevice[field] = deviceInfo[field]
                          }
                        })

                        // 更新轴信息
                        if (localDevice.Axis && deviceInfo.Axis) {
                          deviceInfo.Axis.forEach(axisInfo => {
                            const localAxisIndex = localDevice.Axis.findIndex(
                              axis => axis.AxisName === axisInfo.AxisName
                            )
                            if (localAxisIndex !== -1) {
                              localDevice.Axis[localAxisIndex].AxisValue = axisInfo.AxisValue
                            }
                          })
                        }

                        // 设置更新后的设备
                        this.$set(this.DeviceData_Config, deviceIndex, localDevice)
                      }
                    })
                  } catch (error) {
                    console.error('解析或更新设备信息时出错:', error)
                    console.error('原始数据:', m_data)
                  }
                }
                break
              }
            }
            break
        }
      } catch (error) {
        console.error('处理 MQTT 消息时出错:', error)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
* {
  font-family: "Microsoft YaHei", sans-serif;
}

HTML {
  overflow: auto;
}

body {
  margin: 0;
  padding: 0;
  width: 1920px;
  height: 1080px;
  overflow: hidden;
  position: relative;
  font-family: MiSans Bold, serif;
}

// 晶体管字体
@font-face {
  font-family: electronicFont;
  src: url('../assets/font/DS-DIGI.TTF');
}


::-webkit-scrollbar {
  width: 5px;
  height: 5px;
}

::-webkit-scrollbar-track {
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
  background-color: rgb(14, 50, 97);
  border-radius: 2px;
}

::-webkit-scrollbar-thumb {
  border-radius: 5px;
  -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, .3);
  background-color: rgb(10, 35, 82);
}

::-webkit-scrollbar-button {
  display: none;
}

::-webkit-scrollbar-corner {
  background: #dedede;
}

#body {
  z-index: 100;
  transform-origin: 0 0;
  position: fixed;
  left: 50%;
  top: 50%;
  transition: 0.3s;
}

.background {
  width: 1920px;
  height: 1080px;
  background-color: rgba(72, 116, 203);
  color: white;
  background-size: 100%;
  z-index: 99999;
}

.scroll-list {
  width: 100%;
  padding: 15px;
  position: relative;
  top: 760px;
  box-sizing: border-box;
  overflow: hidden;
  white-space: nowrap;
}

.scroll-content {
  display: inline-flex;
  // animation: scroll 70s linear infinite;
  // min-width: 100%;
  width: 100%;
  will-change: transform;
  justify-content: space-evenly;
}

@keyframes scroll {
  0% {
    transform: translateX(0);
  }

  100% {
    transform: translateX(calc(-50%));
  }
}

.data-box {
  position: relative;
  width: 320px;
  margin-bottom: 20px;
  margin-right: 20px;
  display: inline-block;
  flex-shrink: 0;
  vertical-align: top;
  border: 1px solid #fff;
  background-color: rgba(72, 116, 203, .5);
  white-space: normal;

  .item-list {
    margin-top: 10px;
    margin-left: 10px;
    font-size: 14px;
    color: #fff;

    .item-list-item {
      display: flex;
      height: 30px;
      line-height: 30px;
      width: 100%;
      justify-content: flex-start;
      align-items: center;

      .item-list-item-name {
        width: 75px;
        font-weight: 700;
        text-align: right;
        flex-shrink: 0;
      }

      .item-list-item-value {
        width: 90px;
        text-align: left;
        flex-shrink: 0;
      }

      .item-list-item-value.item-list-item-name-red {
        background-color: rgba(4, 45, 133, .8);
        font-family: electronicFont;
        width: 82px;
        color: #ff0000;
        font-size: 25px;
        padding: 0 5px;
        text-align: left;
        overflow: hidden;
        flex-shrink: 0;
      }
    }

  }

  .ZB {
    color: #fff;
    border-collapse: collapse;

    td {
      border: 1px solid #000;
      text-align: center;
      font-size: 13px;
    }
  }
}

.boxBorder {
  position: absolute;
  padding: 10px;
  border-style: solid;
  border-color: rgb(71, 209, 226);
}

.borderLeft1 {
  border-width: 2px 0 0 2px;
  top: -2px;
  left: -2px;
}

.borderLeft2 {
  border-width: 2px 2px 0 0;
  top: -2px;
  right: -2px;
}

.borderRight1 {
  border-width: 0 0 2px 2px;
  bottom: -2px;
  left: -2px;
}

.borderRight2 {
  border-width: 0 2px 2px 0;
  bottom: -2px;
  right: -2px;
}

.indicatorText {
  font-weight: 700;
  width: 100%;
  color: #fff !important;
  font-size: 18px;
  height: 30px;
  text-align: center;
}

.data-title-left {
  float: left;
  width: 15px;
  height: 13px;
  font-family: "Microsoft YaHei", sans-serif;
  background-color: #036be9;
  margin: 6px 10px 0 20px;
}

#htmlTitleImg {
  display: flex;
  justify-content: center;
  font-family: "Microsoft YaHei", sans-serif;
  position: fixed;
  top: 0;
  left: 0;
  font-size: 45px;
  text-align: center;
  height: 80px;
  line-height: 60px;
  letter-spacing: 15px;
  // margin-left: 80px;
  width: 100%;
  background: url('/src/assets/titleImg.png') no-repeat center center;
  background-size: 100% 100%;
  border-bottom: 2px solid #fff;
}

.center-head {
  width: 300px;
  height: 80px;
  position: relative;
  left: 60px;
  font-size: 30px;
  line-height: 80px;
  top: 0px;
  display: flex;
  text-align: center;
  letter-spacing: 0px;
}
</style>
