<template>
  <view class="page-container environment-container">
    <!-- 页面头部 -->
    <view class="page-header">
      <view class="header-left">
        <text class="page-title">现场环境参数</text>
      </view>
      <view class="header-right">
        <view class="system-title">
          <view class="system-title-icon">
            <text class="icon">📋</text>
          </view>
          <text class="system-title-text">移动式检修车间系统</text>
        </view>
      </view>
    </view>
    
    <view class="page-content">
      <view class="content-wrapper">
      <view class="left-panel">
      <!-- 参数显示区域 -->
      <view class="parameters">
        <!-- 当前状态概览 -->
        <view class="status-overview">
          <view class="status-card">
            <view class="status-icon">🌡️</view>
            <view class="status-info">
              <text class="status-label">温度</text>
              <text class="status-value">{{ temperature }}°C</text>
            </view>
            <view class="status-indicator" :class="getTemperatureStatus()"></view>
          </view>
          
          <view class="status-card">
            <view class="status-icon">💧</view>
            <view class="status-info">
              <text class="status-label">湿度</text>
              <text class="status-value">{{ humidity }}%</text>
            </view>
            <view class="status-indicator" :class="getHumidityStatus()"></view>
          </view>
          
          <view class="status-card">
            <view class="status-icon">✨</view>
            <view class="status-info">
              <text class="status-label">洁净度</text>
              <text class="status-value">{{ cleanliness }}%</text>
            </view>
            <view class="status-indicator" :class="getCleanlinessStatus()"></view>
          </view>
        </view>
        
        <!-- 详细参数进度条 -->
        <view class="detailed-params">
          <view class="param-item">
            <view class="param-header">
              <text class="param-name">温度</text>
              <text class="param-current">{{ temperature }}°C</text>
            </view>
            <view class="param-progress">
              <view class="progress-bar">
                <view class="progress-fill temperature-fill" :style="{ width: temperaturePercent + '%' }"></view>
              </view>
              <text class="param-range">0°C - 100°C</text>
            </view>
          </view>
          
          <view class="param-item">
            <view class="param-header">
              <text class="param-name">湿度</text>
              <text class="param-current">{{ humidity }}%</text>
            </view>
            <view class="param-progress">
              <view class="progress-bar">
                <view class="progress-fill humidity-fill" :style="{ width: humidityPercent + '%' }"></view>
              </view>
              <text class="param-range">0% - 100%</text>
            </view>
          </view>
          
          <view class="param-item">
            <view class="param-header">
              <text class="param-name">洁净度</text>
              <text class="param-current">{{ cleanliness }}%</text>
            </view>
            <view class="param-progress">
              <view class="progress-bar">
                <view class="progress-fill cleanliness-fill" :style="{ width: cleanlinessPercent + '%' }"></view>
              </view>
              <text class="param-range">暂无数据</text>
            </view>
          </view>
        </view>
      </view>
      
      <!-- 设置面板 -->
      <view class="settings-panel">
        <view class="settings-header">
          <text class="settings-title">环境控制</text>
          <view class="settings-status">
            <view class="status-dot" :class="isConnected ? getOverallStatus() : 'status-disconnected'"></view>
            <text class="status-text">{{ getOverallStatusText() }}</text>
          </view>
        </view>
        
        <!-- MQTT连接状态 -->
        <view class="mqtt-status" v-if="lastUpdateTime">
          <text class="mqtt-label">最后更新:</text>
          <text class="mqtt-time">{{ lastUpdateTime }}</text>
        </view>
        
        <view class="settings-content">
          <view class="control-item">
            <text class="control-label">温度控制</text>
            <view class="control-value">{{ temperature }}°C</view>
          </view>
          <view class="control-item">
            <text class="control-label">湿度控制</text>
            <view class="control-value">{{ humidity }}%</view>
          </view>
        </view>
        
        <view class="settings-actions">
          <button class="settings-button" @click="openSettings">
            <text class="button-icon">⚙️</text>
            <text class="button-text">参数设定</text>
          </button>
        </view>
      </view>
    </view>
    
    <!-- 右侧监控画面 -->
    <view class="right-panel">
      <view class="camera-feed">
        <view class="camera-header">
          <text class="camera-title">实时监控</text>
          <view class="camera-status" :class="isConnected ? getOverallStatus() : 'status-disconnected'">
            <view class="status-indicator-dot"></view>
            <text class="status-text">{{ getOverallStatusText() }}</text>
          </view>
        </view>
        
        <view class="camera-container">
          <image class="camera-image" src="/static/inspection-room.jpg" mode="aspectFill"></image>
          <view class="camera-overlay">
            <view class="overlay-info">
              <text class="overlay-time">{{ getCurrentTime() }}</text>
              <text class="overlay-location">检修车间</text>
            </view>
            <view class="camera-controls">
              <button class="control-btn">
                <text class="control-icon">📷</text>
              </button>
              <button class="control-btn">
                <text class="control-icon">🔍</text>
              </button>
            </view>
          </view>
        </view>
      </view>
    </view>
    </view>
    </view>
  </view>
</template>

<script setup>
import { ref, defineEmits, onMounted, onUnmounted, nextTick } from 'vue';
import { getConnectionStatus } from '@/utils/sendMqtt';
import { DataParser } from '@/config/mqtt';

const emit = defineEmits(['openSettings']);

// 环境参数数据
const temperature = ref(0);
const humidity = ref(0);
const cleanliness = ref('-'); // 暂无洁净度数据

// MQTT连接状态
const isConnected = ref(false);
const lastUpdateTime = ref('');
const isPageLoaded = ref(false); // 页面加载状态

// 计算百分比值用于进度条显示 (0-100范围)
const temperaturePercent = ref(0); // 0°C对应0%
const humidityPercent = ref(0); // 0%对应0%
const cleanlinessPercent = ref(0); // 暂无数据

// MQTT数据处理
const handleDeviceData = (data) => {
  // 只有在页面加载完成后才处理数据
  if (!isPageLoaded.value) {
    console.log('页面尚未加载完成，忽略MQTT数据:', data);
    return;
  }
  
  console.log('收到设备数据:', data);
  
  // 更新最后更新时间
  lastUpdateTime.value = DataParser.formatTimestamp(data.timestamp);
  
  // 根据设备类型处理数据
  switch (data.Device) {
    case 'AC': // 空调设备
      if (data.Data && data.Data.BSQWD !== undefined) {
        temperature.value = parseFloat(data.Data.BSQWD);
        temperaturePercent.value = Math.max(0, Math.min(100, temperature.value)); // 0-100°C范围
        console.log('更新空调温度:', temperature.value);
      }
      break;
      
    case 'WSD': // 温湿度传感器
      if (data.Data) {
        // WD为温度，SD为湿度
        if (data.Data.WD !== undefined) {
          temperature.value = parseFloat(data.Data.WD);
          temperaturePercent.value = Math.max(0, Math.min(100, temperature.value)); // 0-100°C范围
          console.log('更新WSD温度(WD):', temperature.value);
        }
        if (data.Data.SD !== undefined) {
          humidity.value = parseFloat(data.Data.SD);
          humidityPercent.value = Math.max(0, Math.min(100, humidity.value)); // 0-100%范围
          console.log('更新WSD湿度(SD):', humidity.value);
        }
      }
      break;
      
    case 'PM': // PM2.5传感器
      if (data.Data && data.Data.PM25 !== undefined) {
        // 暂时不处理PM2.5数据，洁净度显示为"-"
        const pm25Value = parseFloat(data.Data.PM25);
        console.log('收到PM2.5数据:', pm25Value, '洁净度保持显示"-"');
      }
      break;
      
    default:
      console.log('未知设备类型:', data.Device);
  }
};

// 检查MQTT连接状态
const checkMqttStatus = () => {
  isConnected.value = getConnectionStatus();
  console.log('MQTT连接状态:', isConnected.value);
};

// 开始监听MQTT数据
const startMqttListener = () => {
  console.log('开始监听MQTT数据...');
  uni.$on('mqttData', handleDeviceData);
};

// 打开设置弹窗
const openSettings = () => {
  emit('openSettings');
};

// 获取参数状态
const getTemperatureStatus = () => {
  if (temperature.value < 20 || temperature.value > 30) return 'status-warning';
  return 'status-normal';
};

const getHumidityStatus = () => {
  if (humidity.value < 40 || humidity.value > 60) return 'status-warning';
  return 'status-normal';
};

const getCleanlinessStatus = () => {
  // 洁净度暂无数据，始终显示为正常状态
  return 'status-normal';
};

// 获取整体状态
const getOverallStatus = () => {
  const tempStatus = getTemperatureStatus();
  const humidityStatus = getHumidityStatus();
  const cleanlinessStatus = getCleanlinessStatus();
  
  if (tempStatus === 'status-warning' || humidityStatus === 'status-warning' || cleanlinessStatus === 'status-warning') {
    return 'status-warning';
  }
  return 'status-normal';
};

const getOverallStatusText = () => {
  if (!isConnected.value) {
    return '未连接';
  }
  return getOverallStatus() === 'status-normal' ? '正常' : '异常';
};

// 获取当前时间
const getCurrentTime = () => {
  const now = new Date();
  return now.toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 组件挂载时开始监听MQTT数据
onMounted(async () => {
  console.log('EnvironmentParams组件已挂载');
  
  // 检查MQTT连接状态
  checkMqttStatus();
  
  // 等待DOM更新完成
  await nextTick();
  
  // 等待页面完全渲染后再开始监听MQTT数据
  setTimeout(() => {
    console.log('页面加载完成，开始监听MQTT数据...');
    isPageLoaded.value = true; // 标记页面已加载完成
    startMqttListener();
  }, 1000); // 1秒后开始监听
});

// 组件卸载时断开连接
onUnmounted(() => {
  uni.$off('mqttData', handleDeviceData);
  closeMqtt();
});

// 移除模拟数据变化，使用真实MQTT数据
// setInterval(() => {
//   // 温度在22-28之间随机变化
//   temperature.value = Math.floor(Math.random() * 6) + 22;
//   temperaturePercent.value = Math.floor(Math.random() * 30) + 40;
//   
//   // 湿度在40-60之间随机变化
//   humidity.value = Math.floor(Math.random() * 20) + 40;
//   humidityPercent.value = Math.floor(Math.random() * 30) + 40;
//   
//   // 洁净度百分比随机变化
//   cleanlinessPercent.value = Math.floor(Math.random() * 30) + 40;
// }, 5000);
</script>

<style lang="scss">
@import '@/styles/common.scss';

.environment-container {
  // 继承通用页面容器样式
  display: flex;
  flex-direction: column;
  height: 100%;
}

.content-wrapper {
  display: flex;
  flex: 1;
  height: calc(100% - 120rpx);
  padding: 0;
  // margin: 0 30rpx;
  box-sizing: border-box;
}

.left-panel {
  flex: 3;
  display: flex;
  flex-direction: column;
  margin-right: 20rpx;
  height: 100%;
}

/* 参数显示区域 */
.parameters {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-bottom: 20rpx;
  overflow-y: auto;
}

/* 状态概览卡片 */
.status-overview {
  display: flex;
  gap: 12rpx;
  margin-bottom: 20rpx;
}

.status-card {
  flex: 1;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12rpx;
  padding: 16rpx;
  display: flex;
  align-items: center;
  gap: 12rpx;
  border: 1rpx solid #e8eaed;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.status-card:hover {
  transform: translateY(-2rpx);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.status-icon {
  font-size: 32rpx;
  width: 40rpx;
  text-align: center;
}

.status-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.status-label {
  font-size: 22rpx;
  color: #5f6368;
  font-weight: 500;
}

.status-value {
  font-size: 28rpx;
  color: #1a73e8;
  font-weight: 700;
}

.status-indicator {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.status-indicator.status-normal {
  background: linear-gradient(135deg, #34a853 0%, #2e7d32 100%);
  box-shadow: 0 0 8rpx rgba(52, 168, 83, 0.3);
}

.status-indicator.status-warning {
  background: linear-gradient(135deg, #ea4335 0%, #d32f2f 100%);
  box-shadow: 0 0 8rpx rgba(234, 67, 53, 0.3);
}

/* 详细参数进度条 */
.detailed-params {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.param-item {
  background: #ffffff;
  border-radius: 12rpx;
  padding: 20rpx;
  border: 1rpx solid #e8eaed;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.param-item:hover {
  transform: translateY(-1rpx);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
}

.param-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12rpx;
}

.param-name {
  font-size: 26rpx;
  font-weight: 600;
  color: #3c4043;
}

.param-current {
  font-size: 28rpx;
  font-weight: 700;
  color: #1a73e8;
}

.param-progress {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.progress-bar {
  height: 8rpx;
  background: #f1f3f4;
  border-radius: 4rpx;
  overflow: hidden;
  position: relative;
}

.progress-fill {
  height: 100%;
  border-radius: 4rpx;
  transition: width 0.5s ease;
  position: relative;
}

.progress-fill::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(90deg, transparent 0%, rgba(255, 255, 255, 0.3) 50%, transparent 100%);
  animation: shimmer 2s infinite;
}

@keyframes shimmer {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

.temperature-fill {
  background: linear-gradient(90deg, #ff6b35 0%, #f7931e 100%);
}

.humidity-fill {
  background: linear-gradient(90deg, #4285f4 0%, #34a853 100%);
}

.cleanliness-fill {
  background: linear-gradient(90deg, #9c27b0 0%, #673ab7 100%);
}

.param-range {
  font-size: 20rpx;
  color: #9aa0a6;
  text-align: right;
}

/* 右侧面板 */
.right-panel {
  flex: 2;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.camera-feed {
  flex: 1;
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12rpx;
  overflow: hidden;
  position: relative;
  height: 100%;
  border: 1rpx solid #e8eaed;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  display: flex;
  flex-direction: column;
}

.camera-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 20rpx;
  background: rgba(255, 255, 255, 0.95);
  border-bottom: 1rpx solid #e8eaed;
}

.camera-title {
  font-size: 28rpx;
  font-weight: 700;
  color: #3c4043;
}

.camera-status {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 6rpx 12rpx;
  border-radius: 20rpx;
  transition: all 0.3s ease;
}

.camera-status.status-normal {
  background: rgba(52, 168, 83, 0.1);
  border: 1rpx solid rgba(52, 168, 83, 0.2);
}

.camera-status.status-warning {
  background: rgba(234, 67, 53, 0.1);
  border: 1rpx solid rgba(234, 67, 53, 0.2);
}

.camera-status.status-disconnected {
  background: rgba(154, 160, 166, 0.1);
  border: 1rpx solid rgba(154, 160, 166, 0.2);
}

.status-indicator-dot {
  width: 8rpx;
  height: 8rpx;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.camera-status.status-normal .status-indicator-dot {
  background: #34a853;
  box-shadow: 0 0 6rpx rgba(52, 168, 83, 0.4);
}

.camera-status.status-warning .status-indicator-dot {
  background: #ea4335;
  box-shadow: 0 0 6rpx rgba(234, 67, 53, 0.4);
}

.camera-status.status-disconnected .status-indicator-dot {
  background: #9aa0a6;
  box-shadow: 0 0 6rpx rgba(154, 160, 166, 0.4);
}

.camera-container {
  flex: 1;
  position: relative;
  overflow: hidden;
}

.camera-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.camera-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(180deg, rgba(0, 0, 0, 0.1) 0%, transparent 30%, transparent 70%, rgba(0, 0, 0, 0.2) 100%);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 16rpx;
}

.overlay-info {
  display: flex;
  flex-direction: column;
  gap: 4rpx;
}

.overlay-time {
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.9);
  font-weight: 600;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.5);
}

.overlay-location {
  font-size: 20rpx;
  color: rgba(255, 255, 255, 0.7);
  font-weight: 500;
  text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.5);
}

.camera-controls {
  display: flex;
  gap: 12rpx;
  justify-content: flex-end;
}

.control-btn {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.9);
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

.control-btn:hover {
  transform: scale(1.1);
  background: rgba(255, 255, 255, 1);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.3);
}

.control-icon {
  font-size: 20rpx;
}

.settings-panel {
  background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
  border-radius: 12rpx;
  padding: 20rpx;
  border: 1rpx solid #e8eaed;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  // height: 200rpx;
}

.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 12rpx;
  border-bottom: 1rpx solid #e8eaed;
}

.settings-title {
  font-size: 28rpx;
  font-weight: 700;
  color: #3c4043;
}

.settings-status {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.status-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.status-dot.status-normal {
  background: linear-gradient(135deg, #34a853 0%, #2e7d32 100%);
  box-shadow: 0 0 8rpx rgba(52, 168, 83, 0.3);
}

.status-dot.status-warning {
  background: linear-gradient(135deg, #ea4335 0%, #d32f2f 100%);
  box-shadow: 0 0 8rpx rgba(234, 67, 53, 0.3);
}

.status-dot.status-disconnected {
  background: linear-gradient(135deg, #9aa0a6 0%, #5f6368 100%);
  box-shadow: 0 0 8rpx rgba(154, 160, 166, 0.3);
}

.status-text {
  font-size: 22rpx;
  font-weight: 600;
  color: #5f6368;
}

/* MQTT状态显示 */
.mqtt-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8rpx 0;
  border-bottom: 1rpx solid #e8eaed;
  margin-bottom: 12rpx;
}

.mqtt-label {
  font-size: 20rpx;
  color: #9aa0a6;
  font-weight: 500;
}

.mqtt-time {
  font-size: 20rpx;
  color: #1a73e8;
  font-weight: 600;
}

.settings-content {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.control-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8rpx 0;
}

.control-label {
  font-size: 24rpx;
  font-weight: 500;
  color: #5f6368;
}

.control-value {
  font-size: 26rpx;
  font-weight: 700;
  color: #1a73e8;
}

.settings-actions {
  display: flex;
  justify-content: center;
}

.settings-button {
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 12rpx 24rpx;
  background: linear-gradient(135deg, #1a73e8 0%, #1557b0 100%);
  border: none;
  color: white;
  font-size: 24rpx;
  font-weight: 600;
  border-radius: 8rpx;
  transition: all 0.3s ease;
  box-shadow: 0 2rpx 8rpx rgba(26, 115, 232, 0.3);
}

.settings-button:hover {
  transform: translateY(-1rpx);
  box-shadow: 0 4rpx 12rpx rgba(26, 115, 232, 0.4);
}

.button-icon {
  font-size: 20rpx;
}

.button-text {
  font-size: 24rpx;
}

// 响应式设计 - 平板设备适配
@media (min-width: 768px) and (max-width: 1024px) {
  .parameter-label {
    font-size: 32rpx;
  }
  
  .parameter-value {
    font-size: 36rpx;
  }
  
  .param-icon {
    width: 48rpx;
    height: 48rpx;
  }
  
  .parameter-row {
    height: 120rpx;
  }
  
  .settings-label {
    font-size: 36rpx;
  }
  
  .settings-value {
    font-size: 36rpx;
  }
}

// 响应式设计 - 手机设备适配
@media (max-width: 750rpx) {
  .parameter-label {
    font-size: 24rpx;
  }
  
  .parameter-value {
    font-size: 28rpx;
  }
  
  .param-icon {
    width: 32rpx;
    height: 32rpx;
  }
  
  .parameter-row {
    height: 80rpx;
  }
  
  .settings-label {
    font-size: 28rpx;
  }
  
  .settings-value {
    font-size: 28rpx;
  }
}

// 响应式设计 - 大屏设备适配
@media (min-width: 1200px) {
  .parameter-label {
    font-size: 36rpx;
  }
  
  .parameter-value {
    font-size: 40rpx;
  }
  
  .param-icon {
    width: 56rpx;
    height: 56rpx;
  }
  
  .parameter-row {
    height: 140rpx;
  }
  
  .settings-label {
    font-size: 40rpx;
  }
  
  .settings-value {
    font-size: 40rpx;
  }
}
</style>