<template>
  <view class="environment-page">
    <!-- 固定头部 -->
    <view class="fixed-header">
      <text class="header-title">移动式检修车间</text>
    </view>
    
    <!-- 内容区域 -->
    <view class="tabbar-content">
      <!-- 顶部参数卡片 -->
      <view class="parameter-cards">
        <view class="card-item">
          <view class="card-icon temperature-icon">🌡️</view>
          <view class="card-content">
            <text class="card-value">{{ temperature }}°C</text>
            <text class="card-label">温度</text>
          </view>
          <view class="card-status" :class="temperature > 0 ? 'active' : 'inactive'"></view>
        </view>
        
        <view class="card-item">
          <view class="card-icon humidity-icon">💧</view>
          <view class="card-content">
            <text class="card-value">{{ humidity }}%</text>
            <text class="card-label">湿度</text>
          </view>
          <view class="card-status" :class="humidity > 0 ? 'active' : 'inactive'"></view>
        </view>
        
        <view class="card-item">
          <view class="card-icon cleanliness-icon">✨</view>
          <view class="card-content">
            <text class="card-value">{{ cleanliness > 0 ? cleanliness + '%' : '-%' }}</text>
            <text class="card-label">洁净度</text>
          </view>
          <view class="card-status" :class="cleanliness > 0 ? 'active' : 'inactive'"></view>
        </view>
      </view>

      <!-- 环境参数详情 -->
      <view class="parameter-details">
        <view class="parameter-item">
          <view class="parameter-header">
            <text class="parameter-label">温度</text>
            <text class="current-value">{{ temperature }}°C</text>
          </view>
          <view class="progress-container">
            <view class="progress-bar">
              <view class="progress-fill temperature-progress" :style="{ width: temperatureProgress + '%' }"></view>
            </view>
          </view>
          <view class="progress-info">
              <text class="range-value">{{ temperatureRange.min }}°C - {{ temperatureRange.max }}°C</text>
            </view>
        </view>
        
        <view class="parameter-item">
          <view class="parameter-header">
            <text class="parameter-label">湿度</text>
            <text class="current-value">{{ humidity }}%</text>
          </view>
          <view class="progress-container">
            <view class="progress-bar">
              <view class="progress-fill humidity-progress" :style="{ width: humidityProgress + '%' }"></view>
            </view>
          </view>
          <view class="progress-info">
              <text class="range-value">{{ humidityRange.min }}% - {{ humidityRange.max }}%</text>
            </view>
        </view>
        
        <view class="parameter-item">
          <view class="parameter-header">
            <text class="parameter-label">洁净度</text>
            <text class="current-value">{{ cleanliness > 0 ? cleanliness + '%' : '-%' }}</text>
          </view>
          <view class="progress-container">
            <view class="progress-bar">
              <view class="progress-fill cleanliness-progress" :style="{ width: cleanlinessProgress + '%' }"></view>
            </view>
          </view>
          <view class="progress-info">
              <text class="range-value">暂无数据</text>
            </view>
        </view>
      </view>
    
    <!-- 空调目标参数设置 -->
    <view class="air-conditioner-settings">
      <view class="settings-header">
        <text class="settings-title">空调目标参数设置</text>
      </view>
      <view class="temperature-control">
        <text class="control-label">目标温度</text>
        <view class="temperature-display">
          <button class="temp-btn decrease" @click="decreaseTemperature">-</button>
          <text class="temperature-value">{{ targetTemperature }}°C</text>
          <button class="temp-btn increase" @click="increaseTemperature">+</button>
        </view>
      </view>
    </view>
    
    <!-- 环境控制区域 -->
    <view class="environment-control">
      <view class="control-header">
        <text class="control-title">环境控制</text>
        <view class="status-indicator">
          <view class="status-dot"></view>
          <text class="status-text">异常</text>
        </view>
      </view>
      <view class="control-info">
        <text class="last-update">最后更新: {{ lastUpdate }}</text>
            <!-- <view class="connection-info">
              <text class="connection-status" :class="connectionStatus.isConnected ? 'connected' : 'disconnected'">
                {{ connectionStatus.isConnected ? 'MQTT已连接' : 'MQTT未连接' }}
              </text>
              <button v-if="!connectionStatus.isConnected" class="reconnect-btn" @click="manualReconnect">
                重连
              </button>
            </view> -->
        <text class="temperature-range">温度控制: {{ temperatureRange.min }}°C - {{ temperatureRange.max }}°C</text>
        <text class="humidity-range">湿度控制: {{ humidityRange.min }}% - {{ humidityRange.max }}%</text>
      </view>
      <button class="settings-button" @click="openSettingsModal">
        <text class="settings-icon">⚙️</text>
        <text class="settings-text">参数设定</text>
      </button>
    </view>
    
    <!-- 参数设定弹窗 -->
    <uni-popup ref="settingsPopup" type="center" :mask-click="false">
      <view class="settings-modal">
        <view class="modal-header">
          <text class="modal-title">参数设定</text>
          <text class="close-btn" @click="closeSettingsModal">✕</text>
        </view>
        
        <view class="modal-content">
          <!-- 温度设定 -->
          <view class="setting-item">
            <text class="setting-label">温度控制范围</text>
            <view class="range-inputs">
              <input 
                class="range-input" 
                type="number" 
                v-model="tempSettings.min" 
                placeholder="最小值"
              />
              <text class="range-separator">-</text>
              <input 
                class="range-input" 
                type="number" 
                v-model="tempSettings.max" 
                placeholder="最大值"
              />
              <text class="unit">°C</text>
            </view>
          </view>
          
          <!-- 湿度设定 -->
          <view class="setting-item">
            <text class="setting-label">湿度控制范围</text>
            <view class="range-inputs">
              <input 
                class="range-input" 
                type="number" 
                v-model="humiditySettings.min" 
                placeholder="最小值"
              />
              <text class="range-separator">-</text>
              <input 
                class="range-input" 
                type="number" 
                v-model="humiditySettings.max" 
                placeholder="最大值"
              />
              <text class="unit">%</text>
            </view>
          </view>
        </view>
        
        <view class="modal-actions">
          <button class="cancel-btn" @click="closeSettingsModal">取消</button>
          <button class="confirm-btn" @click="saveSettings">确定</button>
        </view>
      </view>
    </uni-popup>
    </view>
  </view>
</template>

<script>
import mqttDataManager from '@/utils/mqttDataManager.js'
import { manualReconnect } from '@/utils/sendMqtt.js'

export default {
  data() {
    return {
      temperature: 0,
      humidity: 0,
      cleanliness: 0,
      temperatureProgress: 0,
      humidityProgress: 0,
      cleanlinessProgress: 0,
      lastUpdate: '暂无数据',
      temperatureRange: {
        min: 0,
        max: 100
      },
      humidityRange: {
        min: 0,
        max: 100
      },
      tempSettings: {
        min: 25,
        max: 35
      },
      humiditySettings: {
        min: 0,
        max: 100
      },
      connectionStatus: {
        isConnected: false,
        lastUpdate: null
      },
      targetTemperature: 40
    }
  },
  onLoad() {
    console.log('环境参数页面加载')
    this.initMqttListener()
  },
  onUnload() {
    console.log('🔌 环境参数页面卸载，清理资源...')
    
    // 页面卸载时移除监听器
    if (this.dataUpdateHandler) {
      mqttDataManager.removeListener('dataUpdate', this.dataUpdateHandler)
      console.log('✅ 数据更新监听器已移除')
    }
    if (this.statusUpdateHandler) {
      mqttDataManager.removeListener('connectionStatus', this.statusUpdateHandler)
      console.log('✅ 状态更新监听器已移除')
    }
    
    // 清理调试定时器
    if (this.debugInterval) {
      clearInterval(this.debugInterval)
      console.log('✅ 调试定时器已清理')
    }
    
    console.log('✅ 环境参数页面资源清理完成')
  },
  methods: {
    // 初始化MQTT监听
    initMqttListener() {
      console.log('🔧 环境参数页面开始初始化MQTT监听...')
      
      // 监听数据更新
      this.dataUpdateHandler = (data) => {
        console.log('📨 环境参数页面收到MQTT数据:', data)
        this.updateEnvironmentData(data)
      }
      mqttDataManager.addListener('dataUpdate', this.dataUpdateHandler)
      
      // 监听连接状态
      this.statusUpdateHandler = (status) => {
        console.log('🔄 环境参数页面连接状态更新:', status)
        const wasConnected = this.connectionStatus.isConnected
        this.connectionStatus = status
        
        // 只在状态发生变化时显示提示（避免重复提示）
        if (wasConnected !== status.isConnected) {
          if (status.isConnected) {
            console.log('✅ MQTT连接状态: 已连接')
            // 不显示Toast，因为sendMqtt.js中已经显示了
          } else {
            console.log('❌ MQTT连接状态: 未连接')
            // 不显示Toast，因为sendMqtt.js中已经显示了
          }
        }
      }
      mqttDataManager.addListener('connectionStatus', this.statusUpdateHandler)
      
      // 获取初始数据
      const lastData = mqttDataManager.getLastData()
      console.log('📊 获取初始数据:', lastData)
      if (lastData.timestamp) {
        this.updateEnvironmentData(lastData)
      }
      
      // 获取初始连接状态
      this.connectionStatus = mqttDataManager.getConnectionStatus()
      console.log('🔍 初始连接状态:', this.connectionStatus)
      
      // 定期检查连接状态（用于调试）
      this.debugInterval = setInterval(() => {
        const currentStatus = mqttDataManager.getConnectionStatus()
        console.log('🔍 定期检查连接状态:', currentStatus)
      }, 10000) // 每10秒检查一次
      
      console.log('✅ 环境参数页面MQTT监听初始化完成')
    },
    
    // 更新环境数据
    updateEnvironmentData(data) {
      console.log('🌡️ 环境参数页面更新数据:', data)
      
      // 只处理WSD设备的数据
      if (data.deviceType === 'WSD') {
        if (data.temperature !== undefined) {
          this.temperature = parseFloat(data.temperature.toFixed(1))
          this.temperatureProgress = Math.min(Math.max(this.temperature, 0), 100)
          console.log('✅ 温度已更新:', this.temperature)
        }
        
        if (data.humidity !== undefined) {
          this.humidity = parseFloat(data.humidity.toFixed(1))
          this.humidityProgress = Math.min(Math.max(this.humidity, 0), 100)
          console.log('✅ 湿度已更新:', this.humidity)
        }
        
        this.lastUpdate = data.time || new Date().toLocaleString('zh-CN')
        
        console.log('✅ 环境数据更新完成:', {
          temperature: this.temperature,
          humidity: this.humidity,
          lastUpdate: this.lastUpdate
        })
      } else {
        console.log('⚠️ 非WSD设备数据，跳过更新:', data.deviceType)
      }
    },
    
    // 降低目标温度
    decreaseTemperature() {
      if (this.targetTemperature > 16) {
        this.targetTemperature--
        console.log('目标温度降低至:', this.targetTemperature + '°C')
        this.showTemperatureChangeToast()
      } else {
        uni.showToast({
          title: '温度不能低于16°C',
          icon: 'none'
        })
      }
    },
    
    // 提高目标温度
    increaseTemperature() {
      if (this.targetTemperature < 30) {
        this.targetTemperature++
        console.log('目标温度提高至:', this.targetTemperature + '°C')
        this.showTemperatureChangeToast()
      } else {
        uni.showToast({
          title: '温度不能高于30°C',
          icon: 'none'
        })
      }
    },
    
    // 显示温度变化提示
    showTemperatureChangeToast() {
      uni.showToast({
        title: `目标温度: ${this.targetTemperature}°C`,
        icon: 'success',
        duration: 1500
      })
    },
    
    // 手动重连MQTT
    manualReconnect() {
      console.log('🔄 用户手动触发MQTT重连')
      uni.showToast({
        title: '正在重连...',
        icon: 'loading',
        duration: 2000
      })
      
      // 调用sendMqtt.js中的手动重连函数
      manualReconnect()
    },
    openSettingsModal() {
      // 打开弹窗前，将当前设置复制到临时变量
      this.tempSettings = { ...this.temperatureRange }
      this.humiditySettings = { ...this.humidityRange }
      this.$refs.settingsPopup.open()
    },
    closeSettingsModal() {
      this.$refs.settingsPopup.close()
    },
    saveSettings() {
      // 保存设置
      this.temperatureRange = { ...this.tempSettings }
      this.humidityRange = { ...this.humiditySettings }
      
      // 更新最后更新时间
      this.lastUpdate = new Date().toLocaleString()
      
      // 关闭弹窗
      this.closeSettingsModal()
      
      // 显示保存成功提示
      uni.showToast({
        title: '参数设置已保存',
        icon: 'success'
      })
      
      console.log('保存的温度范围:', this.temperatureRange)
      console.log('保存的湿度范围:', this.humidityRange)
    }
  }
}
</script>

<style lang="scss" scoped>
.environment-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

/* 顶部参数卡片样式 */
.parameter-cards {
  display: flex;
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.card-item {
  flex: 1;
  background: white;
  border-radius: 12rpx;
  padding: 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
  min-height: 120rpx;
}

.card-icon {
  font-size: 40rpx;
  margin-bottom: 10rpx;
}

.card-content {
  text-align: center;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.card-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 5rpx;
}

.card-label {
  font-size: 24rpx;
  color: #666;
}

.card-status {
  position: absolute;
  top: 15rpx;
  right: 15rpx;
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
}

.card-status.active {
  background-color: #4caf50;
}

.card-status.inactive {
  background-color: #ccc;
}

.card-label {
  display: block;
  font-size: 28rpx;
  color: #666;
  margin-bottom: 10rpx;
}

.card-value {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.card-indicator {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
}

.temperature-indicator {
  background-color: #ff4444;
}

.humidity-indicator {
  background-color: #4488ff;
}

.cleanliness-indicator {
  background-color: #999;
}

.parameter-details {
  background: white;
  border-radius: 12rpx;
  padding: 25rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.parameter-item {
  margin-bottom: 30rpx;
}

.parameter-item:last-child {
  margin-bottom: 0;
}

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

.parameter-label {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.current-value {
  font-size: 28rpx;
  color: #4488ff;
  font-weight: bold;
}

.progress-container {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.progress-bar {
  flex: 1;
  height: 16rpx;
  background-color: #f0f0f0;
  border-radius: 8rpx;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  border-radius: 8rpx;
  transition: width 0.3s ease;
}

.temperature-progress {
  background: linear-gradient(90deg, #4488ff, #44ff88);
}

.humidity-progress {
  background: linear-gradient(90deg, #4488ff, #44ff88);
}

.cleanliness-progress {
  background: linear-gradient(90deg, #4488ff, #44ff88);
}

.progress-info {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  min-width: 200rpx;
}

.current-value {
  font-size: 28rpx;
  font-weight: bold;
  color: #4488ff;
  margin-bottom: 5rpx;
}

.range-value {
  font-size: 24rpx;
  color: #666;
}

/* 空调目标参数设置样式 */
.air-conditioner-settings {
  background: white;
  border-radius: 12rpx;
  padding: 25rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

.settings-header {
  margin-bottom: 25rpx;
}

.settings-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.temperature-control {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.control-label {
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
}

.temperature-display {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.temp-btn {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 36rpx;
  font-weight: bold;
  border: none;
  color: white;
}

.temp-btn.decrease {
  background-color: #ff4444;
}

.temp-btn.increase {
  background-color: #4caf50;
}

.temperature-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
  min-width: 120rpx;
  text-align: center;
}

.environment-control {
  background: white;
  border-radius: 12rpx;
  padding: 25rpx;
  box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.05);
}

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

.control-title {
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.status-indicator {
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.status-dot {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  background-color: #ffaa00;
}

.status-text {
  font-size: 28rpx;
  color: #ffaa00;
}

.control-info {
  display: flex;
  flex-direction: column;
  gap: 10rpx;
  margin-bottom: 30rpx;
}

.last-update {
  font-size: 28rpx;
  color: #4488ff;
}

.connection-status {
  font-size: 28rpx;
  font-weight: bold;
}

.connection-status.connected {
  color: #4caf50;
}

.connection-status.disconnected {
  color: #ff4444;
}

.connection-info {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.reconnect-btn {
  background-color: #ff4444;
  color: white;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
  border: none;
}

.temperature-range {
  font-size: 28rpx;
  color: #4488ff;
}

.humidity-range {
  font-size: 28rpx;
  color: #4488ff;
}

.settings-button {
  background-color: #3f51b5;
  color: white;
  padding: 20rpx 40rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  width: 100%;
}

.settings-icon {
  font-size: 24rpx;
}

.settings-text {
  font-size: 28rpx;
}

/* 弹窗样式 */
.settings-modal {
  background: white;
  border-radius: 20rpx;
  width: 600rpx;
  max-width: 90vw;
  overflow: hidden;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  background-color: #f8f8f8;
  border-bottom: 2rpx solid #e0e0e0;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  font-size: 32rpx;
  color: #666;
  padding: 10rpx;
}

.modal-content {
  padding: 30rpx;
}

.setting-item {
  margin-bottom: 40rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.setting-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  font-weight: bold;
}

.range-inputs {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.range-input {
  flex: 1;
  padding: 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 10rpx;
  font-size: 28rpx;
  text-align: center;
  background-color: #f8f8f8;
}

.range-separator {
  font-size: 28rpx;
  color: #666;
  font-weight: bold;
}

.unit {
  font-size: 24rpx;
  color: #666;
  min-width: 60rpx;
}

.modal-actions {
  display: flex;
  gap: 20rpx;
  padding: 30rpx;
  background-color: #f8f8f8;
}

.cancel-btn {
  flex: 1;
  background-color: #666;
  color: white;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
}

.confirm-btn {
  flex: 1;
  background-color: #3f51b5;
  color: white;
  padding: 20rpx;
  border-radius: 10rpx;
  font-size: 28rpx;
}
</style>