<template>
  <div class="control-button-container">
    <!-- Control Actions Group -->
    <div class="button-group">
      <el-button class="tech-button" @click="handleOpenDoor">
        <el-icon class="button-icon"><Unlock /></el-icon>
        <span>开门</span>
      </el-button>
      <el-button class="tech-button" @click="handleCloseDoor">
        <el-icon class="button-icon"><Lock /></el-icon>
        <span>关门</span>
      </el-button>
      <el-button class="tech-button" @click="openWater">
        <el-icon class="button-icon"><VideoPlay /></el-icon>
        <span>开冷却液</span>
      </el-button>
      <el-button class="tech-button" @click="closeWater">
        <el-icon class="button-icon"><VideoPause /></el-icon>
        <span>关冷却液</span>
      </el-button>
      <el-button class="tech-button" @click="toolToPosition">
        <el-icon class="button-icon"><Aim /></el-icon>
        <span>换刀到位置</span>
      </el-button>
    </div>

    <!-- Divider -->
    <div class="group-divider"></div>

    <!-- Management Actions Group -->
    <div class="button-group">
      <el-button class="tech-button" @click="handleWatchPaper">
        <el-icon class="button-icon"><Document /></el-icon>
        <span>查看图纸</span>
      </el-button>
      <el-button class="tech-button" @click="handleBeiqiFutian">
        <el-icon class="button-icon"><Monitor /></el-icon>
        <span>智能生产管理</span>
      </el-button>
      <el-button class="tech-button" @click="handleDachai">
        <el-icon class="button-icon"><Tools /></el-icon>
        <span>设备运维保养</span>
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import mqtt from 'mqtt'
import { ElMessage } from 'element-plus'
import {
  Unlock,
  Lock,
  VideoPlay,
  VideoPause,
  Aim,
  Document,
  Monitor,
  Tools,
} from '@element-plus/icons-vue'

// 定义组件事件
const emit = defineEmits<{
  'open-door': []
  'close-door': []
  'open-water': []
  'close-water': []
  'watch-paper': []
  logout: []
}>()

const router = useRouter()

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

// 主题配置
const DOOR_TOPIC = window.dt_Config.mqttTopic

// 开门消息配置
const OPEN_DOOR_MESSAGE =
  'DT|C_B_TagIDTrigger|{"DeviceCode":"A7B3CF61-4458-4092-8AEF-0DDA29E1D884","TagID":"84A9E451-EDDE-401E-99F2-6408BE691A22","TagValue":"1"}'

// 关门消息配置
const CLOSE_DOOR_MESSAGE =
  'DT|C_B_TagIDTrigger|{"DeviceCode":"A7B3CF61-4458-4092-8AEF-0DDA29E1D884","TagID":"4536D6A3-B2B6-4B67-A00E-97F48165D551","TagValue":"1"}'

// 开冷却液消息配置
const OPEN_WATER_MESSAGE =
  'DT|C_B_TagIDTrigger|{"DeviceCode":"A7B3CF61-4458-4092-8AEF-0DDA29E1D884","TagID":"783BC6F6-86F1-4F35-ABAB-8EF7F631FEBC","TagValue":"1"}'

// 关闭冷却液消息配置
const CLOSE_WATER_MESSAGE =
  'DT|C_B_TagIDTrigger|{"DeviceCode":"A7B3CF61-4458-4092-8AEF-0DDA29E1D884","TagID":"783BC6F6-86F1-4F35-ABAB-8EF7F631FEBC","TagValue":"0"}'

const TOOL_TO_POSITION_MESSAGE =
  'DT|C_B_TagIDTrigger|{"DeviceCode":"A7B3CF61-4458-4092-8AEF-0DDA29E1D884","TagID":"1D0393CD-1C64-468A-8FD9-5A75FBEADC52","TagValue":"1"}'

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

  const connection = {
    host: mqttIp,
    port: mqttPort,
    endpoint: '/mqtt',
    clean: true,
    connectTimeout: 30000,
    reconnectPeriod: 10000,
    clientId: 'control_button_' + 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
    })

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

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

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

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

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

// 检查MQTT连接状态
const checkMqttConnection = () => {
  if (!mqttClient.value || !mqttClient.value.connected) {
    ElMessage.warning('MQTT连接未就绪，请等待连接建立')
    return false
  }
  return true
}

// 发送MQTT消息
const sendMqttMessage = (message: string, actionName: string) => {
  if (!checkMqttConnection()) {
    return false
  }

  try {
    mqttClient.value.publish(DOOR_TOPIC, message, { qos: 1 }, (error) => {
      if (error) {
        console.error(`发送${actionName}指令失败:`, error)
        ElMessage.error(`${actionName}指令发送失败`)
      } else {
        console.log(`${actionName}指令发送成功`)
        ElMessage.success(`${actionName}指令已发送`)
      }
    })
    return true
  } catch (error) {
    console.error(`发送${actionName}指令异常:`, error)
    ElMessage.error(`发送${actionName}指令时发生错误`)
    return false
  }
}

// 开门方法
const handleOpenDoor = () => {
  const success = sendMqttMessage(OPEN_DOOR_MESSAGE, '开门')
  if (success) {
    emit('open-door')
  }
}

// 关门方法
const handleCloseDoor = () => {
  const success = sendMqttMessage(CLOSE_DOOR_MESSAGE, '关门')
  if (success) {
    emit('close-door')
  }
}

// 开冷却液方法
const openWater = () => {
  const success = sendMqttMessage(OPEN_WATER_MESSAGE, '开冷却液')
  if (success) {
    emit('open-water')
  }
}

// 关冷却液方法
const closeWater = () => {
  const success = sendMqttMessage(CLOSE_WATER_MESSAGE, '关冷却液')
  if (success) {
    emit('close-water')
  }
}

// 换刀到位置方法
const toolToPosition = () => {
  const success = sendMqttMessage(TOOL_TO_POSITION_MESSAGE, '换刀到位置')
  if (success) {
    // 可以添加额外的事件发射
  }
}

// 查看图纸方法
const handleWatchPaper = () => {
  emit('watch-paper')
}

// 北汽福田管理软件跳转
const handleBeiqiFutian = () => {
  window.open('http://124.220.15.242:10068/', '_blank')
}

// 大柴管理软件跳转
const handleDachai = () => {
  window.open('http://124.220.15.242:8251/', '_blank')
}

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

// 初始化MQTT连接
initMqtt()

// 暴露清理方法
defineExpose({
  disconnectMqtt,
})
</script>

<style scoped>
.control-button-container {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  gap: 8px;
  width: 100%;
  box-sizing: border-box;
  padding: 0 4px;
  flex-wrap: wrap;
}

.button-group {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  gap: 8px;
  flex-wrap: wrap;
}

.group-divider {
  width: 1px;
  height: 28px;
  background: linear-gradient(180deg, transparent 0%, rgba(0, 240, 255, 0.5) 50%, transparent 100%);
  margin: 0 8px;
  flex-shrink: 0;
}

.tech-button {
  background: linear-gradient(135deg, rgba(8, 27, 43, 0.85) 0%, rgba(13, 38, 59, 0.95) 100%);
  border: 1px solid rgba(0, 240, 255, 0.3);
  color: #00f0ff;
  border-radius: 4px;
  height: 38px;
  padding: 0 8px;
  font-family: 'Microsoft YaHei', sans-serif;
  font-weight: 500;
  letter-spacing: 0.5px;
  box-shadow: 0 0 10px rgba(0, 240, 255, 0.1), inset 0 0 15px rgba(0, 240, 255, 0.05);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  text-shadow: 0 0 2px rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0;
}

/* 按钮内部图标 */
.button-icon {
  margin-right: 6px;
  font-size: 16px;
  filter: drop-shadow(0 0 2px rgba(0, 240, 255, 0.5));
}

.tech-button span {
  font-size: 13px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 悬停效果 */
.tech-button:hover {
  background: linear-gradient(135deg, rgba(13, 50, 80, 0.95) 0%, rgba(8, 27, 43, 0.9) 100%);
  border-color: #00f0ff;
  color: #ffffff;
  box-shadow: 0 0 15px rgba(0, 240, 255, 0.4), inset 0 0 20px rgba(0, 240, 255, 0.1);
  transform: translateY(-1px);
  text-shadow: 0 0 4px rgba(0, 240, 255, 0.6);
}

.tech-button:hover .button-icon {
  animation: pulse 1.5s infinite;
  color: #fff;
}

/* 点击效果 */
.tech-button:active {
  transform: translateY(1px);
  box-shadow: 0 0 5px rgba(0, 240, 255, 0.2);
}

/* 装饰角标（可选，增加科技感） */
.tech-button::after {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  width: 6px;
  height: 6px;
  background: linear-gradient(45deg, transparent 50%, rgba(0, 240, 255, 0.6) 50%);
}

@keyframes pulse {
  0% { transform: scale(1); opacity: 1; }
  50% { transform: scale(1.1); opacity: 0.8; }
  100% { transform: scale(1); opacity: 1; }
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .tech-button span {
    font-size: 12px;
  }
}

@media (max-width: 1200px) {
  .button-group {
    gap: 8px;
  }
  .tech-button {
    height: 34px;
    padding: 0 4px;
  }
  .button-icon {
    font-size: 14px;
    margin-right: 4px;
  }
}

@media (max-width: 1024px) {
  .control-button-container {
    flex-wrap: wrap;
    justify-content: center;
  }
  .group-divider {
    display: none;
  }
}

@media (max-width: 768px) {
  .button-group {
    flex-wrap: wrap;
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .tech-button {
    font-size: 12px;
  }
}
</style>

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