<template>
  <div class="right-data-box1">
    <LDBTitleBox title="实时状态" align="right" />
    <div class="status-content" @mouseenter="pauseScroll" @mouseleave="resumeScroll">
      <!-- 设备状态行（固定不滚动） -->
      <el-row class="status-row fixed-row">
        <el-col :span="6" :offset="1">设备状态</el-col>
        <el-col :span="14" :offset="3">
          <el-row>
            <el-col v-for="item in statusItems" :key="item.label" :span="6">
              <span
                class="circle"
                :class="{ active: item.active }"
                :style="{ backgroundColor: item.active ? getCircleColor(item.label) : '#909399' }"
              ></span>
              <span class="status-label">{{ item.label }}</span>
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <!-- 滚动区域 -->
      <div class="scroll-container" :style="{ height: scrollContainerHeight }">
        <div
          class="scroll-content"
          :class="{ 'auto-scroll': statusList.length > visibleItemCount }"
          :style="scrollAnimationStyle"
          @mouseenter="pauseScroll"
          @mouseleave="resumeScroll"
        >
          <!-- 状态列表 -->
          <el-row
            v-for="(item, index) in displayStatusList"
            :key="`${item.key}-${index}`"
            class="status-row scroll-row"
          >
            <el-col :span="6" :offset="1">{{ item.label }}</el-col>
            <el-col :span="14" :offset="3">{{ item.value }}</el-col>
          </el-row>
        </div>
      </div>

      <!-- MQTT连接状态显示 -->
      <!-- <div class="mqtt-status" :class="connectionStatus">MQTT: {{ getConnectionStatusText }}</div> -->
    </div>
  </div>
</template>

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

// ==================== 组件定义 ====================
defineOptions({
  name: 'NowStatus',
})

// ==================== 数据定义 ====================
// 滚动相关状态
const scrollContainerHeight = ref('50px')
const scrollInterval = ref<ReturnType<typeof setInterval> | null>(null)
const isScrollingPaused = ref(false)
const scrollPosition = ref(0)
const scrollAnimationStyle = ref({})

// 状态列表
const statusList = ref<DeviceStatus[]>([
  { key: 'mode', label: '手动自动', value: '自动' },
  { key: 'program', label: '程序号', value: 'O0001' },
  { key: 'tool', label: '刀具号', value: 'T01' },
  { key: 'spindleSpeed', label: '主轴转速', value: '1000rpm' },
  { key: 'feedRate', label: '进给速度', value: '500mm/min' },
  { key: 'spindleOverride', label: '主轴转速倍率', value: '100%' },
  { key: 'feedOverride', label: '进给速度倍率', value: '100%' },
  { key: 'uptime', label: '开机时间', value: '08:30:15' },
  { key: 'coolant', label: '冷却液输出', value: '关' },
  { key: 'coolingGas', label: '冷却气输出', value: '关' },
])

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

// 设备状态指示器
const statusItems = ref([
  { label: '关机', active: false },
  { label: '待机', active: false },
  { label: '运行', active: false },
  { label: '报警', active: false },
])

// ==================== 计算属性 ====================
// 计算可见项目数量
const visibleItemCount = computed(() => {
  const containerHeight = parseInt(scrollContainerHeight.value)
  const itemHeight = 30
  return Math.floor(containerHeight / itemHeight)
})

// 计算显示的完整状态列表
const displayStatusList = computed(() => {
  if (statusList.value.length <= visibleItemCount.value) {
    return statusList.value
  }
  // 复制一份数据用于无缝滚动
  return [...statusList.value, ...statusList.value.slice(0, visibleItemCount.value)]
})

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

// ==================== 滚动控制 ====================
// 开始滚动
const startScroll = () => {
  if (statusList.value.length <= visibleItemCount.value) {
    return
  }

  stopScroll()

  scrollInterval.value = setInterval(() => {
    if (!isScrollingPaused.value) {
      scrollPosition.value += 0.5
      updateScrollAnimation()

      const itemHeight = 30
      const totalHeight = statusList.value.length * itemHeight
      if (scrollPosition.value >= totalHeight) {
        scrollPosition.value = 0
      }
    }
  }, 50)
}

// 停止滚动
const stopScroll = () => {
  if (scrollInterval.value) {
    clearInterval(scrollInterval.value)
    scrollInterval.value = null
  }
}

// 更新滚动动画样式
const updateScrollAnimation = () => {
  scrollAnimationStyle.value = {
    transform: `translateY(-${scrollPosition.value}px)`,
    transition: isScrollingPaused.value ? 'none' : 'transform 0.3s ease',
  }
}

// 暂停滚动（鼠标悬停时）
const pauseScroll = () => {
  if (statusList.value.length > visibleItemCount.value) {
    isScrollingPaused.value = true
  }
}

// 恢复滚动（鼠标离开时）
const resumeScroll = () => {
  if (statusList.value.length > visibleItemCount.value) {
    isScrollingPaused.value = false
  }
}

// ==================== 设备状态处理 ====================
// 获取状态指示器颜色
const getCircleColor = (label: string) => {
  const colorMap: Record<string, string> = {
    关机: 'grey',
    待机: 'orange',
    运行: 'green',
    报警: 'red',
  }
  return colorMap[label] || 'grey'
}

// 更新设备状态指示器
const updateStatusIndicator = (statusCode: string) => {
  // 重置所有状态
  statusItems.value.forEach((item) => {
    item.active = false
  })

  // 状态映射
  const statusMap: Record<string, number> = {
    '-1': 0, // 关机 -> 第一个圆圈
    '0': 1, // 待机 -> 第二个圆圈
    '1': 2, // 运行 -> 第三个圆圈
    '2': 3, // 报警 -> 第四个圆圈
  }

  const statusIndex = statusMap[statusCode]
  if (statusIndex !== undefined) {
    statusItems.value[statusIndex].active = true
  }
}

// 格式化时间
const formatTime = (timeString: string): string => {
  try {
    const date = new Date(timeString)
    if (isNaN(date.getTime())) return timeString

    const hours = String(date.getHours()).padStart(2, '0')
    const minutes = String(date.getMinutes()).padStart(2, '0')
    const seconds = String(date.getSeconds()).padStart(2, '0')

    return `${hours}:${minutes}:${seconds}`
  } catch (error) {
    return timeString
  }
}

// ==================== MQTT处理 ====================
// 初始化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_box1_' + 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', () => {
      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: any) => {
        if (err) {
          console.error('订阅主题失败:', err)
          connectionStatus.value = 'subscribe_error'
        } else {
          connectionStatus.value = 'subscribed'
        }
      })
    })

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

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

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

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

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

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

// 处理MQTT消息
const handleMqttMessage = (topic: string, message: any) => {
  try {
    // 安全地转换消息为字符串
    let messageString
    if (typeof message === 'object' && message !== null) {
      // 处理Buffer或其他对象类型
      if (typeof message.toString === 'function') {
        messageString = message.toString()
      } else {
        messageString = JSON.stringify(message)
      }
    } 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('NowStatus 处理MQTT消息错误:', error)
  }
}

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

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

// 更新设备显示
const updateDeviceDisplay = (deviceInfo: any) => {
  // 更新设备状态
  updateDeviceStatus(deviceInfo.StatusCode)

  // 更新状态列表
  updateStatusList(deviceInfo)
}

// 更新设备状态
const updateDeviceStatus = (statusCode: string) => {
  // 更新状态指示器
  updateStatusIndicator(statusCode)
}

// 更新状态列表时重新计算滚动
const updateStatusList = (deviceInfo: any) => {
  // 处理冷却液状态
  const coolantStatus = deviceInfo.Coolant === '1' ? '开' : '关'

  // 处理冷却气状态
  const coolingGasStatus = deviceInfo.CoolingGas === '1' ? '开' : '关'

  statusList.value = [
    {
      key: 'mode',
      label: '手动自动',
      value: deviceInfo.WorkMode || '自动',
    },
    {
      key: 'program',
      label: '程序号',
      value: deviceInfo.Program || 'O0001',
    },
    {
      key: 'tool',
      label: '刀具号',
      value: deviceInfo.ToolCurr || 'T01',
    },
    {
      key: 'spindleSpeed',
      label: '主轴转速',
      value: `${deviceInfo.Speed || '0'}rpm`,
    },
    {
      key: 'feedRate',
      label: '进给速度',
      value: `${deviceInfo.Feed || '0'}mm/min`,
    },
    {
      key: 'spindleOverride',
      label: '主轴转速倍率',
      value: `${Math.round((deviceInfo.SpeedRate || 0) * 100)}%`,
    },
    {
      key: 'feedOverride',
      label: '进给速度倍率',
      value: `${Math.round((deviceInfo.FeedRate || 0) * 100)}%`,
    },
    {
      key: 'uptime',
      label: '开机时间',
      value: deviceInfo.BootTime ? formatTime(deviceInfo.BootTime) : '08:30:15',
    },
    {
      key: 'coolant',
      label: '冷却液输出',
      value: coolantStatus,
    },
    {
      key: 'coolingGas',
      label: '冷却气输出',
      value: coolingGasStatus,
    },
  ]

  // 更新后重新开始滚动
  nextTick(() => {
    stopScroll()
    scrollPosition.value = 0
    updateScrollAnimation()
    startScroll()
  })
}

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

// ==================== 生命周期 ====================
// 组件挂载时开始滚动
onMounted(() => {
  initMqtt()
  nextTick(() => {
    // 确保DOM已经渲染完成
    setTimeout(() => {
      startScroll()
    }, 100)
  })
})

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

<style scoped>
/* MQTT状态显示样式 */
.mqtt-status {
  position: absolute;
  bottom: 30px;
  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: #67c23a;
}

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

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

.mqtt-status.reconnecting {
  color: #409eff;
}

.status-content {
  height: 100%;
  position: relative;
  overflow: hidden;
}

/* 固定行样式 */
.fixed-row {
  position: relative;
  z-index: 2;
  background: rgba(0, 0, 0, 0.3);
  margin-bottom: 5px;
}

/* 滚动容器 */
.scroll-container {
  position: relative;
  overflow: hidden;
  height: v-bind(scrollContainerHeight);
}

/* 滚动内容 */
.scroll-content {
  position: absolute;
  width: 100%;
  top: 0;
  left: 0;
  transition: transform 0.3s ease;
}

.auto-scroll.scroll-content {
  animation: scroll-animation 15s linear infinite;
}

.auto-scroll.scroll-content:hover {
  animation-play-state: paused;
}

@keyframes scroll-animation {
  0% {
    transform: translateY(0);
  }

  100% {
    transform: translateY(-50%);
  }
}

/* 滚动行样式 */
.scroll-row {
  height: 30px;
  display: flex;
  align-items: center;
  transition: background-color 0.3s;
}

.scroll-row:hover {
  background-color: rgba(0, 112, 192, 0.2);
}

.circle {
  border-radius: 50%;
  width: 15px;
  height: 15px;
  display: inline-block;
  background-color: grey;
  transition: background-color 0.3s ease;
}

.circle.active {
  box-shadow: 0 0 8px currentColor;
}

.status-label {
  font-size: 12px;
  margin-left: 5px;
}

.status-row {
  font-size: 16px;
  padding: 5px 0;
  color: #fff;
  font-weight: 300;
}
</style>
<script lang="ts">
export default {
  name: 'NowStatus',
}
</script>
