<template>
  <view class="device-detail-container">
    <!-- 顶部紫色导航栏 -->
    <view class="header-nav">
      <view class="nav-left">
        <text class="back-icon" @click="goBack">←</text>
      </view>
      <text class="nav-title">设备详情</text>
      <view class="nav-right"></view>
    </view>
    
    <!-- 设备基本信息卡片 -->
    <view class="basic-info-card">
      <view class="device-main-info">
        <view class="device-name-section">
          <text class="device-name">{{ deviceDetail.deviceName || '未知设备' }}</text>
          <text class="device-id">设备编号: {{ deviceDetail.shortId || '无' }}</text>
        </view>
        <view class="device-status" :class="getDeviceStatusClass(deviceDetail.state)">
          <text class="status-dot"></text>
          <text>{{ getDeviceStatusText(deviceDetail.state) }}</text>
        </view>
      </view>
    </view>
    
    <!-- 设备详细信息卡片 -->
    <view class="detail-info-card">
      <view class="card-title">基础信息</view>
      <view class="info-list">
        <view class="info-item">
          <text class="item-label">产品Key</text>
          <text class="item-value">{{ deviceDetail.productKey || '无' }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">工位编号</text>
          <text class="item-value">{{ deviceDetail.seqName || '无' }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">所属站点</text>
          <text class="item-value">{{ deviceDetail.stationName || '未分配' }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">设备地址</text>
          <text class="item-value">{{ deviceDetail.address || '无' }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">参数配置</text>
          <text class="item-value">{{ deviceDetail.deviceConfigName || '未绑定' }}</text>
        </view>
      </view>
    </view>
    
    <!-- 设备运行状态卡片 -->
    <view class="status-card">
      <view class="card-title">实时状态</view>
      <view class="status-list">
        <view class="status-item">
          <text class="status-label">核心温度</text>
          <text class="status-value">{{ deviceDetail.temperatureChip ? deviceDetail.temperatureChip + '°C' : '未知' }}</text>
        </view>
        <view class="status-item">
          <text class="status-label">是否有水</text>
          <text class="status-value">{{ deviceDetail.hasWater === true ? '有水' : (deviceDetail.hasWater === false ? '无水' : '不支持') }}</text>
        </view>
        <view class="status-item">
          <text class="status-label">是否有泡沫</text>
          <text class="status-value">{{ deviceDetail.hasFoam === true ? '有' : (deviceDetail.hasFoam === false ? '无' : '不支持') }}</text>
        </view>
        <view class="status-item" v-if="deviceDetail.state === 'fault'">
          <text class="status-label">故障原因</text>
          <text class="status-value danger-text">{{ deviceDetail.faultReason || '未知故障' }}</text>
        </view>
        <view class="status-item">
          <text class="status-label">运行时长</text>
          <text class="status-value">{{ formatDuration(deviceDetail.runningTime) || '0小时' }}</text>
        </view>
      </view>
    </view>
    
    <!-- 设备操作按钮 -->
    <view class="action-section">
      <button 
        v-if="isOnline" 
        class="stop-btn"
        @click="handleStopDevice"
      >
        停止设备
      </button>
      <button 
        v-if="!isOnline" 
        class="start-btn"
        @click="handleStartDevice"
      >
        启动设备
      </button>
      <button class="refresh-btn" @click="refreshDeviceInfo">
        刷新信息
      </button>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-overlay" v-if="loading">
      <text class="loading-spinner">🔄</text>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-if="!loading && !deviceDetail.id">
      <text class="empty-icon">📱</text>
      <text class="empty-text">设备不存在</text>
      <button class="refresh-btn" @click="loadDeviceDetail">刷新</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { getDeviceDetail, stopDevice } from '../../api/device.js'
import { formatTime, showToast, storage } from '../../utils/index.js'

const deviceId = ref('')
const deviceDetail = ref({})
const loading = ref(true)

// 计算设备是否在线
const isOnline = computed(() => {
  const state = deviceDetail.value.state
  return state === 'init' || state === 'idle' || state === 'busy' || 
         state === 1 || state === '1' || state === 'ONLINE'
})

// 获取设备类型文本
const getDeviceTypeText = (type) => {
  if (!type) return '无'
  
  try {
    const dicts = storage.get('dicts')
    // 尝试不同的设备类型字典键名
    const possibleDictKeys = ['Device.type', 'WashDevice.type', 'Device.deviceType', 'DeviceType']
    
    for (const key of possibleDictKeys) {
      if (dicts && dicts[key]) {
        const deviceTypeDict = dicts[key]
        const dictItem = deviceTypeDict.find(item => item.value == type)
        if (dictItem) {
          return dictItem.name
        }
      }
    }
    
    return String(type)
  } catch (error) {
    console.error('获取设备类型文本失败:', error)
    return String(type)
  }
}

// 获取设备状态文本
const getDeviceStatusText = (state) => {
  // 添加调试信息
  console.log('设备状态值:', state, '类型:', typeof state)
  
  // 如果状态为空，直接返回离线
  if (state === null || state === undefined || state === '') {
    return '离线'
  }
  
  try {
    const dicts = storage.get('dicts')
    if (!dicts || !dicts['WashDevice.status']) {
      console.warn('字典数据未加载或不存在 WashDevice.status')
      // 降级处理：使用默认映射
      const statusMap = {
        'init': '初始化',
        'idle': '设备空闲',
        'busy': '设备忙碌',
        'sleep': '不在营业时间',
        'maintenance': '维护模式',
        'fault': '设备故障',
        0: '离线', 1: '在线', 2: '故障', 3: '维护中',
        '0': '离线', '1': '在线', '2': '故障', '3': '维护中',
        'ONLINE': '在线', 'OFFLINE': '离线', 'FAULT': '故障', 'MAINTENANCE': '维护中'
      }
      return statusMap[state] || statusMap[String(state)] || String(state)
    }
    
    const deviceStatusDict = dicts['WashDevice.status']
    const dictItem = deviceStatusDict.find(item => item.value == state)
    
    return dictItem ? dictItem.name : String(state)
  } catch (error) {
    console.error('获取设备状态文本失败:', error)
    return String(state)
  }
}

// 获取设备状态样式类
const getDeviceStatusClass = (state) => {
  if (!state) return ''
  
  const statusClassMap = {
    // 新状态值映射
    'init': 'status-online',      // 初始化 - 在线样式
    'idle': 'status-online',      // 设备空闲 - 在线样式
    'busy': 'status-online',      // 设备忙碌 - 在线样式
    'sleep': 'status-offline',    // 不在营业时间 - 离线样式
    'maintenance': 'status-maintenance',  // 维护模式 - 维护样式
    'fault': 'status-fault',      // 设备故障 - 故障样式
    // 旧状态值映射（兼容）
    0: 'status-offline',
    1: 'status-online',
    2: 'status-fault',
    3: 'status-maintenance',
    '0': 'status-offline',
    '1': 'status-online',
    '2': 'status-fault',
    '3': 'status-maintenance',
    'ONLINE': 'status-online',
    'OFFLINE': 'status-offline',
    'FAULT': 'status-fault',
    'MAINTENANCE': 'status-maintenance'
  }
  
  // 尝试直接匹配或类型转换后匹配
  return statusClassMap[state] || statusClassMap[String(state)] || ''
}

// 格式化运行时长
const formatDuration = (seconds) => {
  if (!seconds || isNaN(seconds)) return '0小时'
  
  const totalSeconds = parseInt(seconds)
  const hours = Math.floor(totalSeconds / 3600)
  const minutes = Math.floor((totalSeconds % 3600) / 60)
  
  if (hours > 0) {
    return `${hours}小时${minutes}分钟`
  } else {
    return `${minutes}分钟`
  }
}

// 加载设备详情
const loadDeviceDetail = async () => {
  if (!deviceId.value) {
    console.error('设备ID为空')
    showToast('设备ID不存在')
    loading.value = false
    return
  }
  
  loading.value = true
  try {
    const res = await getDeviceDetail(deviceId.value)
    console.log('设备详情响应:', res)
    
    if (res && res.code === 200) {
      deviceDetail.value = res.data || {}
      console.log('加载的设备详情:', deviceDetail.value)
    } else {
      showToast(res.msg || '获取设备详情失败')
    }
  } catch (error) {
    console.error('获取设备详情失败:', error)
    showToast('获取设备详情失败')
  } finally {
    loading.value = false
  }
}

// 停止设备
const handleStopDevice = async () => {
  try {
    await stopDevice(deviceDetail.value.shortId)
    showToast('设备已停止', 'success')
    // 刷新设备详情
    loadDeviceDetail()
  } catch (error) {
    console.error('停止设备失败:', error)
    showToast('停止设备失败')
  }
}

// 启动设备（预留功能）
const handleStartDevice = () => {
  showToast('启动设备功能开发中')
}

// 刷新设备信息
const refreshDeviceInfo = () => {
  loadDeviceDetail()
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 页面加载时获取设备ID并加载详情
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const receivedDeviceId = currentPage.options.id || ''
  
  console.log('设备详情页接收到的参数:', currentPage.options)
  console.log('设备ID:', receivedDeviceId)
  
  if (!receivedDeviceId) {
    console.error('未接收到设备ID')
    showToast('设备ID不存在，无法加载详情')
    loading.value = false
    return
  }
  
  deviceId.value = receivedDeviceId
  loadDeviceDetail()
})
</script>

<style scoped>
/* 容器 */
.device-detail-container {
  min-height: 100vh;
  background-color: #F8F9FA;
  padding-bottom: 120rpx;
}

/* 顶部紫色导航栏 */
.header-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding-top: calc(24rpx + var(--status-bar-height));
  padding-right: 30rpx;
  padding-bottom: 24rpx;
  padding-left: 30rpx;
  background: linear-gradient(135deg, #667EEA 0%, #764BA2 100%);
  box-shadow: 0 4rpx 16rpx rgba(102, 126, 234, 0.2);
  position: relative;
  z-index: 10;
}

.nav-left {
  width: 180rpx;
  display: flex;
  align-items: center;
}

.back-icon {
  font-size: 40rpx;
  color: #FFFFFF;
  font-weight: 600;
}

.nav-title {
  font-size: 34rpx;
  color: #FFFFFF;
  font-weight: 600;
  flex: 1;
  text-align: center;
  white-space: nowrap;
}

.nav-right {
  width: 180rpx;
}

.danger-text {
  color: #F5222D;
  font-weight: 600;
}

/* 设备基本信息卡片 */
.basic-info-card {
  margin: 20rpx 30rpx;
  padding: 24rpx 30rpx;
  background: #FFFFFF;
  border-radius: 20rpx;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.device-main-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.device-name-section {
  flex: 1;
}

.device-name {
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
  margin-bottom: 8rpx;
  display: block;
}

.device-id {
  font-size: 24rpx;
  color: #667EEA;
  font-weight: 600;
  display: block;
}

/* 设备状态 */
.device-status {
  display: flex;
  align-items: center;
  font-size: 24rpx;
  font-weight: 600;
  padding: 8rpx 24rpx;
  border-radius: 30rpx;
}

.status-dot {
  display: inline-block;
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  margin-right: 8rpx;
  background-color: currentColor;
}

/* 状态样式 */
.status-online {
  color: #52C41A;
  background: linear-gradient(135deg, #F6FFED 0%, #D9F7BE 100%);
}

.status-offline {
  color: #999999;
  background: linear-gradient(135deg, #F5F5F5 0%, #E0E0E0 100%);
}

.status-fault {
  color: #F5222D;
  background: linear-gradient(135deg, #FFF1F0 0%, #FFCCC7 100%);
}

.status-maintenance {
  color: #FAAD14;
  background: linear-gradient(135deg, #FFF7E6 0%, #FFE7BA 100%);
}

/* 详情信息卡片 */
.detail-info-card,
.status-card {
  margin: 20rpx 30rpx;
  background: #FFFFFF;
  border-radius: 20rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.04);
}

.card-title {
  padding: 24rpx 30rpx 20rpx;
  font-size: 28rpx;
  font-weight: 600;
  color: #1A1A1A;
  border-bottom: 1rpx solid #F0F0F0;
}

/* 信息列表 */
.info-list {
  padding: 20rpx 30rpx 24rpx;
}

.info-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #F8F9FA;
}

.info-item:last-child {
  border-bottom: none;
}

.item-label {
  font-size: 26rpx;
  color: #666666;
}

.item-value {
  font-size: 26rpx;
  color: #1A1A1A;
  font-weight: 500;
  text-align: right;
}

/* 状态列表 */
.status-list {
  padding: 20rpx 30rpx 24rpx;
}

.status-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16rpx 0;
  border-bottom: 1rpx solid #F8F9FA;
}

.status-item:last-child {
  border-bottom: none;
}

.status-label {
  font-size: 26rpx;
  color: #666666;
}

.status-value {
  font-size: 26rpx;
  color: #1A1A1A;
  font-weight: 500;
  text-align: right;
}

/* 操作按钮区域 */
.action-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 24rpx 30rpx;
  background: #FFFFFF;
  border-top: 1rpx solid #F0F0F0;
  box-shadow: 0 -4rpx 16rpx rgba(0, 0, 0, 0.06);
  z-index: 100;
  display: flex;
  gap: 20rpx;
}

.stop-btn {
  flex: 1;
  padding: 20rpx 0;
  background: linear-gradient(90deg, #F5222D 0%, #FF4D4F 100%);
  color: #FFFFFF;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 600;
  box-shadow: 0 6rpx 20rpx rgba(245, 34, 45, 0.35);
}

.start-btn {
  flex: 1;
  padding: 20rpx 0;
  background: linear-gradient(90deg, #52C41A 0%, #73D13D 100%);
  color: #FFFFFF;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 600;
  box-shadow: 0 6rpx 20rpx rgba(82, 196, 26, 0.35);
}

.refresh-btn {
  flex: 1;
  padding: 20rpx 0;
  background: linear-gradient(90deg, #667EEA 0%, #764BA2 100%);
  color: #FFFFFF;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 600;
  box-shadow: 0 6rpx 20rpx rgba(102, 126, 234, 0.35);
}

.stop-btn:active,
.start-btn:active,
.refresh-btn:active {
  transform: translateY(2rpx);
  opacity: 0.9;
}

/* 加载状态 */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(2px);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.loading-spinner {
  font-size: 64rpx;
  animation: spin 1s linear infinite;
  margin-bottom: 32rpx;
  color: #fff;
}

.loading-text {
  font-size: 28rpx;
  color: #fff;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
  color: #999999;
}

.empty-icon {
  font-size: 120rpx;
  margin-bottom: 32rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 28rpx;
  margin-bottom: 40rpx;
}
</style>