<template>
  <div class="right-data-box2">
    <LDBTitleBox title="实时数据显示" align="right" />
    <div class="joint-info-container">
      <el-row class="joint-header">
        <el-col :span="8" style="text-align: center">关节</el-col>
        <el-col :span="8" style="text-align: center">位置</el-col>
        <el-col :span="8" style="text-align: center">负载</el-col>
      </el-row>
      <el-row
        v-for="(item, index) in jointData"
        :key="index"
        class="joint-row"
        :class="{
          'joint-row-even': index % 2 === 0,
          'joint-row-odd': index % 2 === 1,
        }"
      >
        <el-col :span="8" style="text-align: center">{{ item.joint }}</el-col>
        <el-col :span="8" style="text-align: center">{{ item.position }}</el-col>
        <el-col :span="8" style="text-align: center">{{ item.load }}</el-col>
      </el-row>
    </div>
    <!-- MQTT连接状态显示 -->
    <div class="mqtt-status" :class="connectionStatus">MQTT: {{ getConnectionStatusText }}</div>
  </div>
</template>

<script setup lang="ts">
import type { JointData } from '@/types'
import { ref, onMounted, onUnmounted, computed } from 'vue'
import mqtt from 'mqtt'

interface Props {}

defineProps<Props>()

// MQTT相关状态
const mqttClient = ref(null)
const connectionStatus = ref('disconnected')
const mqttReconnectCount = ref(0)
const maxReconnectAttempts = 5

const jointData = ref<JointData[]>([
  { joint: 'X', position: '0', load: '0' },
  { joint: 'Y', position: '0', load: '0' },
  { joint: 'Z', position: '0', load: '0' },
])

// 计算属性：连接状态文本
const getConnectionStatusText = computed(() => {
  const statusMap = {
    disconnected: '未连接',
    connected: '已连接',
    error: '连接错误',
    closed: '连接关闭',
    offline: '离线',
    ended: '连接结束',
    reconnecting: '重连中',
    subscribed: '已订阅',
    subscribe_error: '订阅错误',
    init_error: '初始化错误',
  }
  return statusMap[connectionStatus.value] || '未知状态'
})

// 初始化MQTT连接
const initMqtt = () => {
  const mqttIp = window.dt_Config?.mqttIp || 'localhost'
  const mqttPort = window.dt_Config?.mqttPort || '8083'

  const connection = {
    host: mqttIp,
    port: mqttPort,
    endpoint: '/mqtt',
    clean: true,
    connectTimeout: 30000,
    reconnectPeriod: 10000,
    clientId: 'right_data_box2_' + Math.random().toString(16).substr(2, 8),
    keepalive: 60,
    resubscribe: true,
  }

  try {
    const connectUrl = `ws://${connection.host}:${connection.port}${connection.endpoint}`
    const options = {
      clean: connection.clean,
      connectTimeout: connection.connectTimeout,
      clientId: connection.clientId,
      reconnectPeriod: connection.reconnectPeriod,
      keepalive: connection.keepalive,
      resubscribe: connection.resubscribe,
    }

    mqttClient.value = mqtt.connect(connectUrl, options)

    // 连接成功事件
    mqttClient.value.on('connect', () => {
      console.log('AxisPositions MQTT连接成功')
      connectionStatus.value = 'connected'
      mqttReconnectCount.value = 0

      const mqttTopic = localStorage.getItem('mqttTopic') || window.dt_Config?.mqttTopic
      if (!mqttTopic) {
        console.error('MQTT主题未配置')
        return
      }

      // 订阅主题
      mqttClient.value.subscribe(mqttTopic, { qos: 0 }, (err) => {
        if (err) {
          console.error('订阅主题失败:', err)
          connectionStatus.value = 'subscribe_error'
        } else {
          console.log('AxisPositions 订阅主题成功:', mqttTopic)
          connectionStatus.value = 'subscribed'
        }
      })
    })

    // 连接错误事件
    mqttClient.value.on('error', (error) => {
      console.error('AxisPositions MQTT连接错误:', error)
      connectionStatus.value = 'error'
    })

    // 连接关闭事件
    mqttClient.value.on('close', () => {
      console.log('AxisPositions MQTT连接关闭')
      connectionStatus.value = 'closed'
    })

    // 连接离线事件
    mqttClient.value.on('offline', () => {
      console.log('AxisPositions MQTT客户端离线')
      connectionStatus.value = 'offline'
    })

    // 连接结束事件
    mqttClient.value.on('end', () => {
      console.log('AxisPositions MQTT连接结束')
      connectionStatus.value = 'ended'
    })

    // 消息接收事件
    mqttClient.value.on('message', (topic, message) => {
      handleMqttMessage(topic, message)
    })

    // 重连事件
    mqttClient.value.on('reconnect', () => {
      console.log('AxisPositions MQTT正在重连...')
      connectionStatus.value = 'reconnecting'
      mqttReconnectCount.value++
    })
  } catch (error) {
    console.error('AxisPositions MQTT初始化错误:', error)
    connectionStatus.value = 'init_error'
    // 延迟重试
    setTimeout(() => {
      if (mqttReconnectCount.value < maxReconnectAttempts) {
        initMqtt()
      }
    }, 5000)
  }
}

// 处理MQTT消息
const handleMqttMessage = (topic, message) => {
  try {
    // 安全地转换消息为字符串
    let messageString
    if (Buffer.isBuffer(message)) {
      messageString = message.toString()
    } else if (typeof message === 'string') {
      messageString = message
    } else {
      messageString = String(message)
    }

    // 检查消息是否为空
    if (!messageString || messageString.trim() === '') {
      return
    }

    // 解析消息格式
    const parts = messageString.split('|')

    if (parts.length >= 3) {
      const messageType = parts[0]
      const command = parts[1]
      const dataString = parts[2]

      // 处理设备状态消息
      if (messageType === 'MES' && command === 'C_B_DeviceInfo') {
        processDeviceInfoMessage(dataString)
      }
    }
  } catch (error) {
    console.error('AxisPositions 处理MQTT消息错误:', error)
  }
}

// 处理设备信息消息
const processDeviceInfoMessage = (dataString: string) => {
  try {
    const data = JSON.parse(dataString)

    if (Array.isArray(data) && data.length > 0) {
      const deviceInfo = data[0]
      updateJointData(deviceInfo)
    }
  } catch (error) {
    console.error('AxisPositions 解析设备信息JSON失败:', error)
  }
}

// 更新关节数据
const updateJointData = (deviceInfo: any) => {
  if (deviceInfo.Axis && Array.isArray(deviceInfo.Axis)) {
    // 更新现有的关节数据
    const updatedJointData = deviceInfo.Axis.map((axis, index) => {
      // 保留现有的关节名称，如果没有则使用默认名称
      const jointName = axis.AxisName || jointData.value[index]?.joint || `轴${index + 1}`

      return {
        joint: jointName,
        position: formatAxisValue(axis.AxisValue) || '0',
        load: formatAxisValue(axis.AxisLoad) || '0',
      }
    })

    // 如果接收到的数据比现有数据少，保持原有数据不变
    if (updatedJointData.length >= jointData.value.length) {
      jointData.value = updatedJointData
    } else {
      // 只更新有数据的部分
      updatedJointData.forEach((newData, index) => {
        if (jointData.value[index]) {
          jointData.value[index].position = newData.position
          jointData.value[index].load = newData.load
        }
      })
    }

    console.log('AxisPositions 关节数据已更新:', jointData.value)
  }
}

// 格式化轴数据值
const formatAxisValue = (value: any): string => {
  if (value === null || value === undefined) {
    return '0'
  }

  const numValue = parseFloat(value)
  if (isNaN(numValue)) {
    return '0'
  }

  // 根据数值大小决定显示精度
  if (Math.abs(numValue) < 0.001) {
    return '0'
  } else if (Math.abs(numValue) < 1) {
    return numValue.toFixed(4)
  } else if (Math.abs(numValue) < 10) {
    return numValue.toFixed(3)
  } else if (Math.abs(numValue) < 100) {
    return numValue.toFixed(2)
  } else {
    return numValue.toFixed(1)
  }
}

// 安全断开MQTT连接
const disconnectMqtt = () => {
  if (mqttClient.value) {
    try {
      mqttClient.value.removeAllListeners()
      mqttClient.value.end(true, () => {
        console.log('AxisPositions MQTT连接已安全断开')
        mqttClient.value = null
      })
    } catch (error) {
      console.error('AxisPositions 断开MQTT连接时出错:', error)
      mqttClient.value = null
    }
  }
}

// 组件挂载时初始化MQTT
onMounted(() => {
  initMqtt()
})

// 组件卸载时清理资源
onUnmounted(() => {
  disconnectMqtt()
})
</script>

<script lang="ts">
export default {
  name: 'AxisPositions',
}
</script>

<style scoped>
.right-data-box2 {
  position: absolute;
  width: 392px;
  height: 200px;
  box-shadow: inset 0 0 30px rgb(24, 78, 135);
  right: 9px;
  top: 422px;
}

.joint-info-container {
  margin-top: 10px;
  width: 95%;
  margin-left: 15px;
}

.joint-header {
  font-size: 17px;
  font-weight: bold;
}

.joint-row {
  font-size: 17px;
  padding: 5px 0;
}

.joint-row-even {
  background-color: rgba(255, 255, 255, 0.1);
}

.joint-row-odd {
  background-color: rgba(255, 255, 255, 0.05);
}

/* MQTT状态显示样式 */
.mqtt-status {
  position: absolute;
  bottom: 5px;
  right: 10px;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 3px;
  background-color: rgba(0, 0, 0, 0.5);
}

.mqtt-status.connected,
.mqtt-status.subscribed {
  color: #4caf50;
}

.mqtt-status.disconnected,
.mqtt-status.closed,
.mqtt-status.offline,
.mqtt-status.ended {
  color: #ff9800;
}

.mqtt-status.error,
.mqtt-status.subscribe_error,
.mqtt-status.init_error {
  color: #f44336;
}

.mqtt-status.reconnecting {
  color: #2196f3;
}
</style>
