<template>
  <view class="device-detail-container">
    <NavBar title="设备详情" @back="goBack" />

    <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" :style="getDeviceStatusStyle(deviceDetail.state)">
          <text class="status-dot"></text>
          <text>{{ getDeviceStatusText(deviceDetail.state) }}</text>
        </view>
      </view>
    </view>

    <view class="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="info-card">
      <view class="card-title">实时状态</view>
      <view class="info-list">
        <view class="info-item">
          <text class="item-label">核心温度</text>
          <text class="item-value">{{ deviceDetail.temperatureChip ? deviceDetail.temperatureChip + '°C' : '未知' }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">是否有水</text>
          <text class="item-value">{{ fmtDictName('yes_no', deviceDetail.hasWater) }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">是否有泡沫</text>
          <text class="item-value">{{ fmtDictName('yes_no', deviceDetail.hasFoam) }}</text>
        </view>
        <view class="info-item" v-if="isFault">
          <text class="item-label">故障原因</text>
          <text class="item-value item-value-danger">{{ deviceDetail.faultReason || '未知故障' }}</text>
        </view>
        <view class="info-item">
          <text class="item-label">运行时长</text>
          <text class="item-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">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载中...</text>
    </view>

    <view class="empty-state" v-if="!loading && !deviceDetail.id">
      <AppIcon name="smartphone" size="48" color="#BFBFBF" />
      <text class="empty-text">设备不存在</text>
      <button class="empty-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, fmtDictName, getDictColor } from '../../utils/index.js'
import dictUtil, { loadDicts } from '../../utils/dict.js'

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

const isOnline = computed(() => {
  const state = deviceDetail.value.state
  if (state === null || state === undefined) return false
  return state == dictUtil.getDictValue('WashDevice.status', '在线')
})

const isFault = computed(() => {
  const state = deviceDetail.value.state
  if (state === null || state === undefined) return false
  return state == dictUtil.getDictValue('WashDevice.status', '故障')
})

const getDeviceStatusText = (state) => fmtDictName('WashDevice.status', state)

const getDeviceStatusStyle = (state) => {
  const color = getDictColor('WashDevice.status', state)
  if (color) {
    return { color: color, backgroundColor: `${color}1A` }
  }
  return {}
}

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}分钟`
  return `${minutes}分钟`
}

const loadDeviceDetail = async () => {
  if (!deviceId.value) {
    showToast('设备ID不存在')
    loading.value = false
    return
  }
  loading.value = true
  try {
    const res = await getDeviceDetail(deviceId.value)
    if (res && res.code === 200) {
      deviceDetail.value = res.data || {}
    } else {
      showToast(res.msg || '获取设备详情失败')
    }
  } catch (error) {
    showToast('获取设备详情失败')
  } finally {
    loading.value = false
  }
}

const handleStopDevice = () => {
  uni.showModal({
    title: '停止设备',
    content: `确定要停止设备「${deviceDetail.value.deviceName || deviceDetail.value.shortId}」吗？此操作将中断当前运行。`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await stopDevice(deviceDetail.value.shortId)
          showToast('设备已停止', 'success')
          loadDeviceDetail()
        } catch (error) {
          showToast('停止设备失败')
        }
      }
    }
  })
}

const handleStartDevice = () => {
  showToast('启动设备功能开发中')
}

const refreshDeviceInfo = () => {
  loadDeviceDetail()
}

const goBack = () => {
  uni.navigateBack()
}

onMounted(async () => {
  await loadDicts()
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  const receivedDeviceId = currentPage.options.id || ''
  if (!receivedDeviceId) {
    showToast('设备ID不存在，无法加载详情')
    loading.value = false
    return
  }
  deviceId.value = receivedDeviceId
  loadDeviceDetail()
})
</script>

<style scoped>
.device-detail-container {
  min-height: 100vh;
  background-color: #F5F7FA;
  padding-bottom: 160rpx;
}

/* ===== Basic Info Card ===== */
.basic-info-card {
  margin: 20rpx 28rpx;
  padding: 28rpx 28rpx;
  background: #FFFFFF;
  border-radius: 24rpx;
}

.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;
  display: block;
  margin-bottom: 10rpx;
}

.device-id {
  font-size: 24rpx;
  color: #999999;
}

.device-status {
  display: flex;
  align-items: center;
  font-size: 22rpx;
  font-weight: 600;
  padding: 8rpx 20rpx;
  border-radius: 100px;
  flex-shrink: 0;
}

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

/* ===== Info Cards ===== */
.info-card {
  margin: 0 28rpx 20rpx;
  background: #FFFFFF;
  border-radius: 24rpx;
  overflow: hidden;
}

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

.info-list {
  padding: 8rpx 28rpx 16rpx;
}

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

.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;
}

.item-value-danger {
  color: #F44336;
}

/* ===== Action Section ===== */
.action-section {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 20rpx 28rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background: #FFFFFF;
  border-top: 1px solid #F0F0F0;
  box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.04);
  z-index: 100;
  display: flex;
  gap: 20rpx;
}

.stop-btn {
  flex: 1;
  padding: 22rpx 0;
  background: #C6171E;
  color: #FFFFFF;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 600;
  transition: background 0.25s, transform 0.15s;
}

.stop-btn:active {
  background: #A81212;
  transform: scale(0.97);
}

.start-btn {
  flex: 1;
  padding: 22rpx 0;
  background: #52C41A;
  color: #FFFFFF;
  border: none;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 600;
  transition: background 0.25s, transform 0.15s;
}

.start-btn:active {
  opacity: 0.85;
  transform: scale(0.97);
}

.refresh-btn {
  flex: 1;
  padding: 22rpx 0;
  background: #FFFFFF;
  color: #1A1A1A;
  border: 1px solid #E0E0E0;
  border-radius: 16rpx;
  font-size: 28rpx;
  font-weight: 500;
  transition: border-color 0.25s, color 0.25s;
}

.refresh-btn:active {
  border-color: #C6171E;
  color: #C6171E;
}

/* ===== Loading ===== */
.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 999;
}

.loading-spinner {
  width: 64rpx;
  height: 64rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
  border-top-color: #FFFFFF;
  border-radius: 50%;
  animation: spin 0.8s linear infinite;
  margin-bottom: 24rpx;
}

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

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

/* ===== Empty ===== */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
  margin: 24rpx 0 32rpx;
}

.empty-refresh-btn {
  padding: 16rpx 48rpx;
  background: #C6171E;
  color: #FFFFFF;
  border: none;
  border-radius: 44rpx;
  font-size: 28rpx;
  font-weight: 500;
}
</style>
