<template>
  <div class="andon-box">
    <LDBTitleBox title="Andon信息" align="right" />
    <div class="andon-content-container">
      <el-checkbox-group v-model="checkedButtons" class="checkbox-button-grid">
        <el-checkbox-button v-for="button in checkboxButtons" :key="button.label" :label="button.label"
          :class="getButtonClass(button.label)" />
      </el-checkbox-group>

      <el-row>
        <!-- 横屏模式：显示呼叫和复位 -->
        <template v-if="mode === 'landscape'">
          <el-col :span="12">
            <div class="status-item" @click="handleStatusClick('call')">
              <div class="status-content">
                <img src="/PNG/call.png" alt="" class="status-icon" />
                <span class="status-text" style="color: #f56c6c">呼叫</span>
              </div>
            </div>
          </el-col>
          <el-col :span="12">
            <div class="status-item" @click="handleStatusClick('reset')">
              <div class="status-content">
                <img src="/PNG/reset.png" alt="" class="status-icon" />
                <span class="status-text" style="color: #67c23a">复位</span>
              </div>
            </div>
          </el-col>
        </template>

        <!-- 竖屏模式：显示响应 -->
        <template v-else-if="mode === 'portrait'">
          <el-col :span="24">
            <div class="status-item" @click="handleStatusClick('response')">
              <div class="status-content">
                <img src="/PNG/response.png" alt="" class="status-icon" />
                <span class="status-text" style="color: #e6a23c">响应</span>
              </div>
            </div>
          </el-col>
        </template>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import type { AlarmInfo } from '@/types'
import { ElCheckboxGroup, ElCheckboxButton, ElMessage } from 'element-plus'
import mqtt from 'mqtt'

// 定义 props
interface Props {
  mode?: 'landscape' | 'portrait'
}
const props = withDefaults(defineProps<Props>(), {
  mode: 'landscape', // 默认横屏模式
})

// 添加按钮状态跟踪
const buttonStates = ref<Record<string, 'normal' | 'called' | 'responded'>>({})

const checkboxButtons = ref([
  { label: '设备报警' },
  { label: '刀具报警' },
  { label: '质量呼叫' },
  { label: '物料呼叫' },
  { label: '工艺呼叫' },
  { label: '其它呼叫' }
])

const checkedButtons = ref<string[]>([])

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

// 添加接收消息的响应式数据
const receivedMessages = ref<any[]>([])

// 主题配置
const deviceCode = 'A7B3CF61-4458-4092-8AEF-0DDA29E1D884'
const ANDON_TOPIC = `SCADAMain/${deviceCode}`
const CHECKBOX_SYNC_TOPIC = `SCADAMain/${deviceCode}/checkboxSync`
const BUTTON_STATE_SYNC_TOPIC = `SCADAMain/${deviceCode}/buttonStateSync` // 新增按钮状态同步主题

// 状态类型对应的TagID映射
const statusTagMap = {
  call: '6F624533-96D0-4343-91C0-3619A3A45B6F',
  response: '809879B3-DA87-4276-879D-498DC699A9EE',
  reset: 'DAA998AC-4A5A-4593-A2E7-2B9F32B28ADA',
}

// 获取按钮的CSS类
const getButtonClass = (label: string) => {
  const state = buttonStates.value[label] || 'normal'
  return [`button-state-${state}`]
}

// 计算属性来显示接收到的消息
const displayMessages = computed(() => {
  return receivedMessages.value.map((msg) => ({
    type: getStatusDisplayByTag(msg.TagID),
    value: msg.TagValue,
    time: msg.timestamp,
  }))
})

// 监听checkbox状态变化（用于调试）
watch(
  checkedButtons,
  (newVal) => {
    console.log('checkbox状态变化:', newVal)
  },
  { deep: true },
)

// 初始化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: 'andon_' + 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.subscribe(ANDON_TOPIC, { qos: 1 }, (error) => {
        if (error) {
          console.error('订阅ANDON主题失败:', error)
        } else {
          console.log('成功订阅ANDON主题:', ANDON_TOPIC)
        }
      })

      // 订阅checkbox同步主题
      mqttClient.value.subscribe(CHECKBOX_SYNC_TOPIC, { qos: 1 }, (error) => {
        if (error) {
          console.error('订阅checkbox同步主题失败:', error)
        } else {
          console.log('成功订阅checkbox同步主题:', CHECKBOX_SYNC_TOPIC)
        }
      })

      // 订阅按钮状态同步主题
      mqttClient.value.subscribe(BUTTON_STATE_SYNC_TOPIC, { qos: 1 }, (error) => {
        if (error) {
          console.error('订阅按钮状态同步主题失败:', error)
        } else {
          console.log('成功订阅按钮状态同步主题:', BUTTON_STATE_SYNC_TOPIC)
        }
      })
    })

    // 消息接收事件
    mqttClient.value.on('message', (topic, message) => {
      const messageStr = message.toString()
      if (topic === ANDON_TOPIC) {
        handleReceivedMessage(messageStr)
      } else if (topic === CHECKBOX_SYNC_TOPIC) {
        handleCheckboxSyncMessage(messageStr)
      } else if (topic === BUTTON_STATE_SYNC_TOPIC) {
        handleButtonStateSyncMessage(messageStr) // 处理按钮状态同步消息
      }
    })

    // 其他事件处理保持不变...
    mqttClient.value.on('error', (error) => {
      console.error('Andon MQTT连接错误:', error)
      connectionStatus.value = 'error'
    })

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

    mqttClient.value.on('offline', () => {
      console.log('Andon MQTT客户端离线')
      connectionStatus.value = 'offline'
    })

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

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

// 处理接收到的消息
const handleReceivedMessage = (message: string) => {
  try {
    if (message.startsWith('DT|C_B_TagIDTrigger|')) {
      const jsonStr = message.replace('DT|C_B_TagIDTrigger|', '')
      const messageData = JSON.parse(jsonStr)

      // 严格过滤：只处理我们关心的TagID
      const validTagIDs = Object.values(statusTagMap)
      if (!validTagIDs.includes(messageData.TagID)) {
        return // 直接返回，不处理
      }

      // 只处理来自其他设备的消息
      if (messageData.DeviceCode !== deviceCode) {
        receivedMessages.value.unshift({
          ...messageData,
          timestamp: new Date().toLocaleTimeString(),
        })

        // 限制消息数量
        if (receivedMessages.value.length > 10) {
          receivedMessages.value = receivedMessages.value.slice(0, 10)
        }

        const statusDisplay = getStatusDisplayByTag(messageData.TagID)
        if (statusDisplay !== '未知状态') {
          ElMessage.info(`收到${statusDisplay}通知`)
        }
      }
    }
  } catch (error) {
    console.error('解析MQTT消息失败:', error)
  }
}

// 处理checkbox同步消息
const handleCheckboxSyncMessage = (message: string) => {
  try {
    console.log('开始处理checkbox同步消息:', message)

    const syncData = JSON.parse(message)

    if (syncData.action === 'update') {
      console.log('更新checkbox状态:', syncData.checkedButtons)
      checkedButtons.value = [...syncData.checkedButtons]
      // ElMessage.success(`已同步选择: ${syncData.checkedButtons.join('、')}`)
    } else if (syncData.action === 'clear') {
      console.log('清空checkbox状态')
      checkedButtons.value = []
      // 清空按钮状态
      buttonStates.value = {}
      // ElMessage.info('已清空所有选择')
    }
  } catch (error) {
    console.error('解析checkbox同步消息失败:', error)
    ElMessage.error('同步checkbox状态失败')
  }
}

// 处理按钮状态同步消息
const handleButtonStateSyncMessage = (message: string) => {
  try {
    console.log('开始处理按钮状态同步消息:', message)

    const syncData = JSON.parse(message)

    if (syncData.action === 'updateState') {
      console.log('更新按钮状态:', syncData.buttonStates)
      // 更新本地按钮状态
      buttonStates.value = { ...syncData.buttonStates }
      ElMessage.success(`已同步按钮状态`)
    } else if (syncData.action === 'clearState') {
      console.log('清空按钮状态')
      buttonStates.value = {}
      ElMessage.info('已复位按钮状态')
    }
  } catch (error) {
    console.error('解析按钮状态同步消息失败:', error)
    ElMessage.error('同步按钮状态失败')
  }
}

// 发送checkbox状态同步消息
const sendCheckboxSyncMessage = (action: 'update' | 'clear') => {
  if (!checkMqttConnection()) {
    console.warn('MQTT连接未就绪，无法发送checkbox同步消息')
    return false
  }

  const syncData = {
    DeviceCode: deviceCode,
    action: action,
    checkedButtons: checkedButtons.value,
    timestamp: new Date().toISOString(),
  }

  try {
    mqttClient.value.publish(CHECKBOX_SYNC_TOPIC, JSON.stringify(syncData), { qos: 1 }, (error) => {
      if (error) {
        console.error('发送checkbox同步消息失败:', error)
        ElMessage.error('同步状态失败')
      } else {
        console.log('checkbox同步消息发送成功:', syncData)
      }
    })
    return true
  } catch (error) {
    console.error('发送checkbox同步消息异常:', error)
    ElMessage.error('同步状态异常')
    return false
  }
}

// 发送按钮状态同步消息
const sendButtonStateSyncMessage = (action: 'updateState' | 'clearState') => {
  if (!checkMqttConnection()) {
    console.warn('MQTT连接未就绪，无法发送按钮状态同步消息')
    return false
  }

  const syncData = {
    DeviceCode: deviceCode,
    action: action,
    buttonStates: buttonStates.value,
    timestamp: new Date().toISOString(),
  }

  try {
    mqttClient.value.publish(BUTTON_STATE_SYNC_TOPIC, JSON.stringify(syncData), { qos: 1 }, (error) => {
      if (error) {
        console.error('发送按钮状态同步消息失败:', error)
        ElMessage.error('同步按钮状态失败')
      } else {
        console.log('按钮状态同步消息发送成功:', syncData)
      }
    })
    return true
  } catch (error) {
    console.error('发送按钮状态同步消息异常:', error)
    ElMessage.error('同步按钮状态异常')
    return false
  }
}

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

// 发送单个MQTT消息
const sendSingleMqttMessage = (
  tagID: string,
  tagValue: string,
  actionName: string,
): Promise<boolean> => {
  return new Promise((resolve) => {
    if (!checkMqttConnection()) {
      resolve(false)
      return
    }

    const messageData = {
      DeviceCode: deviceCode,
      TagID: tagID,
      TagValue: tagValue,
    }

    const mqttMessage = `DT|C_B_TagIDTrigger|${JSON.stringify(messageData)}`

    try {
      mqttClient.value.publish(ANDON_TOPIC, mqttMessage, { qos: 1 }, (error) => {
        if (error) {
          console.error(`发送${actionName}指令失败:`, error)
          resolve(false)
        } else {
          console.log(`${actionName}指令发送成功: ${tagID}=${tagValue}`)
          resolve(true)
        }
      })
    } catch (error) {
      console.error(`发送${actionName}指令异常:`, error)
      resolve(false)
    }
  })
}

// 处理状态区域点击
const handleStatusClick = async (statusType: 'call' | 'response' | 'reset') => {
  // 检查是否有选中的Andon类型
  if (checkedButtons.value.length === 0) {
    ElMessage.warning('请先选择Andon类型')
    return
  }

  const selectedTypes = checkedButtons.value.join('、')
  const actionName = getStatusDisplayName(statusType)

  try {
    let successCount = 0

    // 根据不同的状态类型发送相应的消息组合
    if (statusType === 'reset') {
      // 复位：设置复位=1，呼叫=0，响应=0
      const promises = [
        sendSingleMqttMessage(statusTagMap.reset, '1', `${selectedTypes}复位`),
        sendSingleMqttMessage(statusTagMap.call, '0', `${selectedTypes}呼叫复位`),
        sendSingleMqttMessage(statusTagMap.response, '0', `${selectedTypes}响应复位`),
      ]

      const results = await Promise.all(promises)
      successCount = results.filter((result) => result).length

      // 复位成功后，发送清空checkbox的同步消息
      if (successCount > 0) {
        sendCheckboxSyncMessage('clear')
        // 发送清空按钮状态的同步消息
        sendButtonStateSyncMessage('clearState')
        // 重置按钮状态
        buttonStates.value = {}
      }
    } else if (statusType === 'call') {
      // 呼叫：设置呼叫=1，响应=0，复位=0
      const promises = [
        sendSingleMqttMessage(statusTagMap.call, '1', `${selectedTypes}呼叫`),
        sendSingleMqttMessage(statusTagMap.response, '0', `${selectedTypes}响应复位`),
        sendSingleMqttMessage(statusTagMap.reset, '0', `${selectedTypes}复位复位`),
      ]

      const results = await Promise.all(promises)
      successCount = results.filter((result) => result).length

      // 呼叫成功后，发送更新checkbox状态的同步消息
      if (successCount > 0) {
        sendCheckboxSyncMessage('update')
        // 更新按钮状态为已呼叫（红色）
        checkedButtons.value.forEach(label => {
          buttonStates.value[label] = 'called'
        })
        // 发送按钮状态同步消息
        sendButtonStateSyncMessage('updateState')
      }
    } else if (statusType === 'response') {
      // 响应：设置响应=1，复位=0
      const promises = [
        sendSingleMqttMessage(statusTagMap.response, '1', `${selectedTypes}响应`),
        sendSingleMqttMessage(statusTagMap.reset, '0', `${selectedTypes}复位复位`),
      ]

      const results = await Promise.all(promises)
      successCount = results.filter((result) => result).length

      // 响应成功后，发送更新checkbox状态的同步消息
      if (successCount > 0) {
        sendCheckboxSyncMessage('update')
        // 更新按钮状态为已响应（黄色）
        checkedButtons.value.forEach(label => {
          buttonStates.value[label] = 'responded'
        })
        // 发送按钮状态同步消息
        sendButtonStateSyncMessage('updateState')
      }
    }

    if (successCount > 0) {
      // ElMessage.success(`${selectedTypes}${actionName}指令发送成功`)

      console.log(`发送${actionName}消息完成:`, {
        selectedTypes: checkedButtons.value,
        statusType: statusType,
        successCount: successCount,
      })
    } else {
      ElMessage.error(`${selectedTypes}${actionName}指令发送失败`)
    }
  } catch (error) {
    console.error(`发送${actionName}消息失败:`, error)
    ElMessage.error(`${selectedTypes}${actionName}指令发送失败`)
  }
}

// 获取状态显示名称
const getStatusDisplayName = (statusType: string) => {
  const nameMap = {
    call: '呼叫',
    response: '响应',
    reset: '复位',
  }
  return nameMap[statusType as keyof typeof nameMap] || statusType
}

// 根据TagID获取状态显示名称
const getStatusDisplayByTag = (tagID: string) => {
  const tagMap = {
    [statusTagMap.call]: '呼叫',
    [statusTagMap.response]: '响应',
    [statusTagMap.reset]: '复位',
  }
  return tagMap[tagID] || '未知状态'
}

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

// 生命周期
onMounted(() => {
  initMqtt()
})

onUnmounted(() => {
  disconnectMqtt()
})
</script>

<style scoped>
.andon-list-container {
  flex: 1;
  overflow: hidden;
  position: relative;
  height: 120px;
  background: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
}

.andon-header-time,
.andon-header-content {
  font-size: 14px;
  color: #70d4ed;
  padding-bottom: 5px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
}

.andon-loading {
  color: #ffffff;
  font-size: 14px;
  text-align: center;
}

.andon-content-container {
  display: flex;
  padding: 0 10px 10px 10px;
}

.checkbox-button-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 10px;
  padding: 10px 0;
}

:deep(.el-checkbox-button) {
  width: 90%;
}

:deep(.el-checkbox-button__inner) {
  width: 100%;
  height: 32px;
  font-size: 12px;
  background-color: rgba(255, 255, 255, 0.1);
  border: none;
  border-radius: 4px;
  color: #38b3f1;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

:deep(.el-checkbox-button.is-checked .el-checkbox-button__inner) {
  background-color: rgba(56, 179, 241, 0.5);
  color: #fff;
  box-shadow: none;
}

/* 正常状态 */
.button-state-normal:deep(.el-checkbox-button__inner) {
  background-color: rgba(255, 255, 255, 0.1);
  color: #38b3f1;
}

/* 呼叫状态 - 红色 */
.button-state-called:deep(.el-checkbox-button__inner) {
  background-color: rgba(245, 108, 108, 0.7) !important;
  color: #fff;
}

/* 响应状态 - 黄色 */
.button-state-responded:deep(.el-checkbox-button__inner) {
  background-color: rgba(230, 162, 60, 0.7) !important;
  color: #fff;
}

.status-item {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 4px;
  padding: 5px;
}

.status-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.status-item:hover {
  background-color: rgba(255, 255, 255, 0.1);
  transform: scale(1.05);
}

.status-icon {
  width: 50px;
  height: 50px;
}

.status-text {
  text-align: center;
  margin-top: 5px;
}

/* 横屏模式下呼叫按钮占满宽度 */
.andon-box[data-mode='landscape'] .status-item {
  height: 80px;
}

/* 竖屏模式下响应和复位按钮并排显示 */
.andon-box[data-mode='portrait'] .status-item {
  height: 70px;
}
</style>
<script lang="ts">
export default {
  name: 'Andon',
}
</script>
