<template>
  <view class="environment-page">
    <!-- 固定头部 -->
    <view class="fixed-header">
      <text class="header-title">移动式检修车间</text>
    </view>
    
    <!-- 内容区域 -->
    <view class="tabbar-content">
      <!-- 环境参数详情 -->
      <view class="parameter-details">
        <!-- 温度卡片 -->
        <EnvironmentCard 
          type="temperature"
          :value="temperature"
          :connection-status="wdisConnected"
          :progress="temperatureProgress"
          :is-out-of-range="temperature > tempSettings.max || temperature < tempSettings.min"
          :is-abnormal="isTempAbnormal"
          @click="navigateToParameterRecord"
        />
        
        <!-- 湿度卡片 -->
        <EnvironmentCard 
          type="humidity"
          :value="humidity"
          :connection-status="sdisConnected"
          :progress="humidityProgress"
          :is-out-of-range="humidity > humiditySettings.max || humidity < humiditySettings.min"
          :is-abnormal="isHumidityAbnormal"
          @click="navigateToParameterRecord"
        />
        
        <!-- 洁净度卡片 -->
        <EnvironmentCard 
          type="cleanliness"
          :value="cleanliness"
          :connection-status="pmisConnected"
          :progress="cleanlinessProgress"
          :is-out-of-range="false"
          :is-abnormal="isCleanlinessAbnormal"
          @click="navigateToParameterRecord"
        />
      </view>
      
    <!-- 空调设置 -->
    <view class="air-conditioner-settings">
      <view class="ac-header">
        <view class="ac-title-container">
          <view class="ac-icon">❄️</view>
          <text class="ac-title">空调设置</text>
        </view>
        <view class="ac-status-indicator">
          <view class="status-dot active"></view>
          <text class="status-label">{{ acStatusList[acStatus] }}</text>
        </view>
      </view>

      <!-- 空调开关控制卡片 -->
      <view class="ac-control-card power-card">
        <view class="control-header">
          <view class="control-icon-container">
            <text class="control-label">设备控制</text>
          </view>
        </view>
        <view class="ac-power-controls">
          <button 
            class="ac-power-btn" 
            :class="getAcButtonClass()" 
            @click="toggleAirConditioner" 
            :disabled="!canOperateAc() || acControlLoading || !isGatewayOnline"
          >
            {{ getAcButtonText() }}
          </button>
        </view>
      </view>
      
      <!-- 温度控制卡片 -->
      <view class="ac-control-card temperature-card">
        <view class="control-header">
          <view class="control-icon-container">
            <text class="control-label">目标温度</text>
          </view>
        </view>
        <view class="ac-temp-control">
          <button class="ac-btn decrease temperature-decrease" @click="decreaseTemperature" :disabled="!isGatewayOnline">
            <text class="btn-icon">−</text>
          </button>
          <view class="ac-temp-display">
            <input 
              class="ac-temp-input" 
              v-model="tempInputValue" 
              type="number" 
              :placeholder="targetTemperature.toString()"
              @input="onTemperatureInput"
              @blur="onTemperatureBlur"
              @focus="onTemperatureFocus"
              :disabled="!isGatewayOnline"
            />
            <text class="ac-temp-unit">°C</text>
          </view>
          <button class="ac-btn increase temperature-increase" @click="increaseTemperature" :disabled="!isGatewayOnline">
            <text class="btn-icon">+</text>
          </button>
        </view>
        <view class="ac-temp-validation" v-if="tempValidationMessage">
          <text class="validation-text" :class="tempValidationClass">{{ tempValidationMessage }}</text>
        </view>
      </view>
      
      <!-- 湿度控制卡片 -->
      <view class="ac-control-card humidity-card">
        <view class="control-header">
          <view class="control-icon-container">
            <text class="control-label">目标湿度</text>
          </view>
        </view>
        <view class="ac-temp-control">
          <button class="ac-btn decrease humidity-decrease" @click="decreaseHumidity" :disabled="!isGatewayOnline">
            <text class="btn-icon">−</text>
          </button>
          <view class="ac-temp-display">
            <input 
              class="ac-temp-input" 
              v-model="humidityInputValue" 
              type="number" 
              :placeholder="targetHumidity.toString()"
              @input="onHumidityInput"
              @blur="onHumidityBlur"
              @focus="onHumidityFocus"
              :disabled="!isGatewayOnline"
            />
            <text class="ac-temp-unit">%</text>
          </view>
          <button class="ac-btn increase humidity-increase" @click="increaseHumidity" :disabled="!isGatewayOnline">
            <text class="btn-icon">+</text>
          </button>
        </view>
        <view class="ac-temp-validation" v-if="humidityValidationMessage">
          <text class="validation-text" :class="humidityValidationClass">{{ humidityValidationMessage }}</text>
        </view>
      </view>
    </view>
    
    <!-- 环境控制区域 -->
    <view class="environment-control">
      <view class="env-header">
        <text class="env-title">环境控制</text>
      </view>
      
      <view class="env-info">
        <view class="control-ranges">
          <view class="range-item">
            <view class="range-header">
              <text class="range-label">温度控制范围</text>
              <view class="range-status" :class="getTemperatureStatus().class">
              <text class="status-text">{{ temperatureRange.min }}°C - {{ temperatureRange.max }}°C</text>
              </view>
            </view>
          </view>
          <view class="range-item">
            <view class="range-header">
              <text class="range-label">湿度控制范围</text>
              <view class="range-status" :class="getHumidityStatus().class">
                <text class="status-text">{{ humidityRange.min }}% - {{ humidityRange.max }}%</text>
              </view>
            </view>
          </view>
        </view>
      </view>
      
      <button class="settings-button" @click="openSettingsModal" :disabled="!isGatewayOnline">
        <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" :disabled="!isGatewayOnline">取消</button>
          <button class="confirm-btn" @click="saveSettings" :disabled="!isGatewayOnline">确定</button>
        </view>
      </view>
    </uni-popup>
    </view>
  </view>
</template>

<script>
import mqttDataManager from '@/utils/mqttDataManager.js'
import { manualReconnect, sendMqttData } from '@/utils/sendMqtt.js'
import { thDataApi, alertApi, eventApi, wsdApi, statusApi } from '@/utils/api.js'
import EnvironmentCard from '@/components/EnvironmentCard.vue'

export default {
  components: {
    EnvironmentCard
  },
  data() {
    return {
      temperature: 0,
      humidity: 0,
      cleanliness: 0,
      temperatureProgress: 0,
      humidityProgress: 0,
      cleanlinessProgress: 0,
      isTempAbnormal: false,
      isHumidityAbnormal: false,
      isCleanlinessAbnormal: false,
      lastUpdate: '暂无数据',
      temperatureRange: {
        min: 0,
        max: 0
      },
      humidityRange: {
        min: 0,
        max: 0
      },
      tempSettings: {
        min: 0,
        max: 0
      },
      humiditySettings: {
        min: 0,
        max: 0
      },
      // 连接状态（用于控制卡片状态小圆点颜色） 0未连接 1连接成功 2异常
      wdisConnected: 0,
      sdisConnected: 0,
      pmisConnected: 0,
      isGatewayOnline: false, // 网关是否在线 禁用按钮
      connectionStatus: {
        isConnected: false,
        lastUpdate: null
      },
      targetTemperature: 0,
      targetHumidity: 0, // 空调设定湿度
      // 温度输入相关
      tempInputValue: '',
      tempValidationMessage: '',
      tempValidationClass: '',
      isTempInputFocused: false,
      // 湿度输入相关
      humidityInputValue: '',
      humidityValidationMessage: '',
      humidityValidationClass: '',
      isHumidityInputFocused: false,
      // 报警相关数据
      acFaultStatus: 0, // 空调故障状态，1表示故障
      // 系统启动事件相关
      hasCreatedStartupEvent: false, // 是否已创建启动事件
      acStatus: 4,
      // 0待机1启动中2运行中3关机中,  没有就默认连接中
      acStatusList: ['待机', '启动中', '运行中', '关机中', '连接中'],
      // 空调控制相关
      acControlLoading: false, // 空调控制按钮加载状态
      // 数据获取定时器
      // 上一次数据记录，用于检测变动
      previousData: {
        temperature: null,
        humidity: null,
        pm25: null
      },
      dataFetchInterval: null,
      // 是否已经提示过设备离线
      hasShownOfflineAlert: false
    }
  },
  onLoad() {
    console.log('环境参数页面加载')
    
    // // 从本地存储读取是否已创建启动事件的状态
    // const hasCreatedStartupEvent = uni.getStorageSync('hasCreatedStartupEvent')
    // if (hasCreatedStartupEvent) {
    //   this.hasCreatedStartupEvent = true
    //   console.log('📱 从本地存储读取到启动事件状态: 已创建')
    // }
    
    this.initMqttListener();
  },
  onShow() {
    this.init();
    // 页面显示时重新启动定时器（如果之前被停止了）
    if (!this.dataFetchInterval) {
      this.startDataFetching();
    }
  },
  onHide() {
    // 页面隐藏时停止定时器
    this.stopDataFetching();
  },
  onUnload() {
    // 页面卸载时移除监听器
    if (this.dataUpdateHandler) {
      mqttDataManager.removeListener('dataUpdate', this.dataUpdateHandler)
    }
    if (this.statusUpdateHandler) {
      mqttDataManager.removeListener('connectionStatus', this.statusUpdateHandler)
    }
    
    // 清理调试定时器
    if (this.debugInterval) {
      clearInterval(this.debugInterval)
    }
    
    // 停止数据获取定时器
    this.stopDataFetching()
  },
  computed: {
    // // 判断网关是否在线
    // isGatewayOnline() {
    //   // 如果温湿度传感器或PM传感器任何一个在线，则认为网关在线
    //   return this.wdisConnected === 1 || this.pmisConnected === 1
    // }
  },
  methods: {
    async init() {
      try {
          const isOnline = await this.checkConnectionStatus();
          this.isGatewayOnline = isOnline;
          if (isOnline) {
            // // 获取最新空调温度
            this.getLatestAirConditionerTemperature()
            // 获取最新温湿度数据
            this.getLatestEnvironmentData()
            // 首次进入系统时创建启动事件
            // this.createStartupEventIfNeeded()
            // 获取温湿度区间设置
            this.loadWsdSettings()
          }
        
      } catch (error) {
        
      }
    },
    
    // 检查连接状态，返回是否在线
    async checkConnectionStatus() {
      try {
        // 1. 首先调用statusApi.getStatus接口判断网关设备是否在线
        const res = await statusApi.getStatus();
        if (res.connected) {
          // 2. 如果网关在线，调用statusApi.getConnectionStatus判断空调、PM等设备是否在线
          const connectRes = await statusApi.getConnectionStatus();
          // 3. 更新各设备连接状态
          // 温湿度传感器状态 (1:连接成功, 0:未连接, 2:异常)
          this.wdisConnected = Number(connectRes?.pm25 || 0)
          this.sdisConnected = Number(connectRes?.pm25 || 0)
          
          // // PM2.5传感器状态
          this.pmisConnected = Number(connectRes?.pm25 || 0)
          // // 空调状态
          // const acStatus = connectRes.ac || 0
          // 设备在线，重置离线提示状态
          this.hasShownOfflineAlert = false
          return true
        } else {
          console.log('⚠️ 网关设备离线，所有设备状态设为离线')
          // 网关离线，所有设备都设为离线状态
          this.wdisConnected = 0
          this.sdisConnected = 0
          this.pmisConnected = 0
          
          // 如果还没有提示过离线，则显示弹窗并停止定时器
          if (!this.hasShownOfflineAlert) {
            // this.hasShownOfflineAlert = true
            const currentTime = this.formatDateTime(new Date());
            const alert = {
              content: "网管设备不在线",
              category: "设备检查",
              alertTime: currentTime,
              level: "警告",
              action: "设备检查",
              actionTime: currentTime,
              deviceId: "AC_001"
            }
            this.logAlert(alert)
            // 弹窗提示网关设备不在线
            uni.showToast({
              title: '网管设备不在线！',
              icon: 'none',
              duration: 3000
            })
            // 停止数据获取定时器
            this.stopDataFetching()
            
            console.log('🛑 设备离线，已停止数据获取定时器')
          }
          
          return false
        }
      } catch (error) {
        console.error('❌ 检查连接状态失败:', error)
        // 出错时默认设为离线状态
        this.wdisConnected = 0
        this.sdisConnected = 0
        this.pmisConnected = 0
        
        // 如果还没有提示过离线，则显示弹窗并停止定时器
        if (!this.hasShownOfflineAlert) {
          this.hasShownOfflineAlert = true
          
          // 停止数据获取定时器
          this.stopDataFetching()
          
          console.log('🛑 连接检查失败，已停止数据获取定时器')
        }
        
        return false
      }
    },

    navigateToParameterRecord() {
      try {
        uni.switchTab({ url: '/pages/parameter/index' })
      } catch (e) {
        uni.showToast({ title: '页面跳转失败', icon: 'none' })
      }
    },

    // 获取温度控制状态
    getTemperatureStatus() {
      return { text: '无数据', class: 'no-data' }
    },
    
    // 获取湿度控制状态
    getHumidityStatus() {
      if (this.humidity === 0) {
        return { text: '无数据', class: 'no-data' }
      } else if (this.humidity >= this.humidityRange.min && this.humidity <= this.humidityRange.max) {
        return { text: '正常', class: 'normal' }
      } else if (this.humidity < this.humidityRange.min) {
        return { text: '偏低', class: 'low' }
      } else {
        return { text: '偏高', class: 'high' }
      }
    },
    
    // 加载温湿度区间设置
    async loadWsdSettings(retryCount = 0, maxRetries = 5) {
      try {
        const response = await wsdApi.getById(1) // 获取ID为1的默认设置
        
        if (response && response.id) {
          // 更新温度和湿度控制范围
          this.temperatureRange = {
            min: response.minTemperature || 0,
            max: response.maxTemperature || 0
          }
          this.humidityRange = {
            min: response.minHumidity || 0,
            max: response.maxHumidity || 0
          }
          
          // 同时更新设置弹窗中的临时变量
          this.tempSettings = { ...this.temperatureRange }
          this.humiditySettings = { ...this.humidityRange }
        } else {
          throw new Error('响应数据格式不正确')
        }
      } catch (error) {
        if (retryCount < maxRetries) {
          // 计算重试延迟时间，递增延迟
          const delay = Math.min(1000 * Math.pow(2, retryCount), 10000) // 最大延迟10秒
          setTimeout(() => {
            this.loadWsdSettings(retryCount + 1, maxRetries)
          }, delay)
        } else {
          // 使用默认值
          this.temperatureRange = { min: 0, max: 0 }
          this.humidityRange = { min: 0, max: 0 }
          this.tempSettings = { ...this.temperatureRange }
          this.humiditySettings = { ...this.humidityRange }
        }
      }
    },
    
    // 获取最新空调温湿度参数
    async getLatestAirConditionerTemperature(retryCount = 0, maxRetries = 3) {
      try {
        const res = await thDataApi.getLatest();
        if (res.status === 'success') {
          // 从接口获取温度和湿度设定值
          this.targetTemperature = res.temperature || 0;
          this.targetHumidity = res.humidity || 0;
        } else {
          throw new Error('响应状态不正确')
        }
      } catch (error) {
        if (retryCount < maxRetries) {
          const delay = 2000 * (retryCount + 1) // 递增延迟: 2s, 4s, 6s
          setTimeout(() => {
            this.getLatestAirConditionerTemperature(retryCount + 1, maxRetries)
          }, delay)
        } else {
          // 接口失败时使用默认值
          this.targetTemperature = 0;
          this.targetHumidity = 0;
        }
      }
    },
    // 获取最新环境数据（温湿度、PM2.5）
    async getLatestEnvironmentData(isRetry = false) {
      try {
        if (!isRetry) {
          console.log('📊 开始获取最新环境数据...')
        }
        const res = await wsdApi.getLatest();
        if (res && res.status === 'success') {
          // 直接更新页面数据，不再依赖MQTT数据格式
          const temperature = res.wd;
          const humidity = res.sd;
          const pm25 = res.pm;
          
          // 更新温度数据
          if (temperature !== undefined && temperature !== 0) {
            this.temperature = parseFloat(temperature.toFixed(1))
            this.temperatureProgress = Math.min(Math.max(this.temperature, 0), 100)
          }
          
          // 更新湿度数据
          if (humidity !== undefined && humidity !== 0) {
            this.humidity = parseFloat(humidity.toFixed(1))
            this.humidityProgress = Math.min(Math.max(this.humidity, 0), 100)
          }
          
          // 更新PM2.5数据
          if (pm25 !== undefined && pm25 !== 0) {
            this.cleanliness = parseFloat(pm25.toFixed(1))
            this.cleanlinessProgress = Math.min(Math.max(this.cleanliness, 0), 100)
          }
          
          // 更新最后更新时间
          this.lastUpdate = new Date().toLocaleString('zh-CN')
          
          // 检查报警条件
          this.checkAlertsFromApiData({
            temperature: this.temperature,
            humidity: this.humidity,
            pm25: this.cleanliness
          })
        }
      } catch (error) {
        console.error('❌ 获取环境数据失败:', error)
        // 如果是首次调用失败，进行重试
        if (!isRetry) {
          setTimeout(() => {
            this.getLatestEnvironmentData(true)
          }, 2000)
        }
        // 不显示错误提示，避免频繁弹窗
      }
    },
    
    // 启动定时获取环境数据
    startDataFetching() {
      // 清除已存在的定时器
      if (this.dataFetchInterval) {
        clearInterval(this.dataFetchInterval)
      }
      
      // 重置离线提示状态，允许重新检测
      this.hasShownOfflineAlert = false
      
      // 定义数据获取函数
      const fetchData = async () => {
        try {
          const isOnline = await this.checkConnectionStatus();
          if (isOnline) {
            this.getLatestEnvironmentData()
          } else {
            console.log('⚠️ 定时检查：设备离线，跳过数据更新')
          }
        } catch (error) {
          console.error('❌ 定时检查状态失败:', error)
          // 容错处理：即使状态检查失败，也尝试获取数据
          // this.getLatestEnvironmentData()
        }
      }
      
      // 立即执行一次数据获取
      // fetchData();
      
      // 每5秒执行一次数据获取
      this.dataFetchInterval = setInterval(fetchData, 5000)
    },
    
    // 停止定时获取环境数据
    stopDataFetching() {
      if (this.dataFetchInterval) {
        clearInterval(this.dataFetchInterval)
        this.dataFetchInterval = null
      }
    },
    
    // 初始化MQTT监听
    initMqttListener() {
      // 监听数据更新
      this.dataUpdateHandler = (data) => {
        this.updateEnvironmentData(data)
      }
      mqttDataManager.addListener('dataUpdate', this.dataUpdateHandler)
      
      // 监听连接状态
      this.statusUpdateHandler = (status) => {
        const wasConnected = this.connectionStatus.isConnected
        this.connectionStatus = status
      }
      mqttDataManager.addListener('connectionStatus', this.statusUpdateHandler)
      
      // 获取初始数据
      const lastData = mqttDataManager.getLastData()
      if (lastData.timestamp) {
        this.updateEnvironmentData(lastData)
      }
      
      // 获取初始连接状态
      this.connectionStatus = mqttDataManager.getConnectionStatus()
      
      // 定期检查连接状态（用于调试）
      this.debugInterval = setInterval(() => {
        const currentStatus = mqttDataManager.getConnectionStatus()
      }, 10000) // 每10秒检查一次
    },
    // 更新环境数据（仅处理MQTT的空调数据）
    updateEnvironmentData(data) {
      // 只处理空调AC数据，温湿度和PM25数据改为从接口获取
      if (data.deviceType === 'AC') {
        // 处理空调AC数据
        if (data.faultStatus !== undefined) {
          this.acFaultStatus = data.faultStatus // 空调故障
        }
        if (data.rawData && data.rawData.status !== undefined) {
          this.acStatus = data.rawData.status
        }
        if (data.rawData && data.rawData.ctrlword !== undefined) {
          this.acCtrlword = data.rawData.ctrlword
        }
        
        // 只对空调数据进行报警检查
        this.checkAlerts(data)
      } else {
        console.log('⚠️ 非AC设备数据，跳过MQTT处理:', data.deviceType)
        // WSD和PM25数据现在从接口获取，不再通过MQTT处理
      }
    },
    
    // 格式化日期时间为指定格式
    formatDateTime(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      const seconds = String(date.getSeconds()).padStart(2, '0')
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    
    // 检查MQTT空调数据的报警条件
    checkAlerts(mqttData) {
      const currentTime = this.formatDateTime(new Date())
      // 只处理空调AC设备的数据
      if (mqttData.deviceType === 'AC') {
        // 空调故障报警：acFaultStatus为1
        if (this.acFaultStatus === 1) {
          const alert = {
            content: "空调报警",
            category: "空调故障",
            alertTime: currentTime,
            level: "高危",
            action: "手动调节空调温度",
            actionTime: currentTime,
            deviceId: "AC_001"
          }
          this.logAlert(alert)
        }
      }
      // 注意：WSD和PM25数据的报警检查现在在checkAlertsFromApiData方法中处理
    },
    
    // 检查从接口获取的数据的报警条件
    checkAlertsFromApiData(apiData) {
      const { temperature, humidity, pm25 } = apiData
      const currentTime = this.formatDateTime(new Date())
      
      // 检查各个数据是否有变动，分别处理对应的报警逻辑
      const temperatureChanged = this.previousData.temperature !== temperature;
      const humidityChanged = this.previousData.humidity !== humidity;
      const pm25Changed = this.previousData.pm25 !== pm25;
      
      // 只有温度有变化时才检查温度相关报警
      if (temperatureChanged) {
        // 1. 温度报警：使用环境控制设置的区间
        if (temperature !== undefined && temperature !== 0 && this.temperatureRange.min !== 0 && this.temperatureRange.max !== 0) {
          if (temperature < this.temperatureRange.min || temperature > this.temperatureRange.max) {
            const alert = {
              content: `当前温度${temperature}°C超出控制范围${this.temperatureRange.min}°C-${this.temperatureRange.max}°C`,
              category: "温度超出范围",
              alertTime: currentTime,
              level: "中危",
              action: "检查温度",
              actionTime: currentTime,
              deviceId: "WSD_001"
            }
            this.wdisConnected = 2;
            this.logAlert(alert)
          }
        }
        
        // 3. 温度偏差报警：|温湿度计温度 - 空调设定温度| / 空调设定温度 > 30%
        if (temperature !== undefined && temperature !== 0 && this.targetTemperature !== 0) {
          const temperatureDiff = Math.abs(temperature - this.targetTemperature)
          const deviationPercent = (temperatureDiff / this.targetTemperature) * 100
          
          if (deviationPercent > 30) {
            const alert = {
              content: `当前温度${temperature}°C与设定${this.targetTemperature}°C偏差${deviationPercent.toFixed(1)}%`,
              category: "温度偏差过大",
              alertTime: currentTime,
              level: "中危",
              action: "调整空调设定温度",
              actionTime: currentTime,
              deviceId: "AC_001"
            }
            this.wdisConnected = 2;
            this.logAlert(alert)
          }
        }
      } else {
        console.log('📊 温度数据无变化，跳过温度报警检查')
      }
      
      // 只有湿度有变化时才检查湿度相关报警
      if (humidityChanged) {
        // 2. 湿度报警：使用环境控制设置的区间
        if (humidity !== undefined && humidity !== 0 && this.humidityRange.min !== 0 && this.humidityRange.max !== 0) {
          if (humidity < this.humidityRange.min || humidity > this.humidityRange.max) {
            const alert = {
              content: `当前湿度${humidity}%超出控制范围${this.humidityRange.min}%-${this.humidityRange.max}%`,
              category: "湿度超出范围",
              alertTime: currentTime,
              level: "中危",
              action: "检查湿度",
              actionTime: currentTime,
              deviceId: "WSD_001"
            }
            this.sdisConnected = 2;
            this.logAlert(alert)
          }
        }
        
        // 4. 湿度偏差报警：|温湿度计湿度 - 空调设定湿度| / 空调设定湿度 > 30%
        if (humidity !== undefined && humidity !== 0 && this.targetHumidity !== 0) {
          const humidityDiff = Math.abs(humidity - this.targetHumidity)
          const deviationPercent = (humidityDiff / this.targetHumidity) * 100
          
          if (deviationPercent > 30) {
            const alert = {
              content: `当前湿度${humidity}%与设定${this.targetHumidity}%偏差${deviationPercent.toFixed(1)}%`,
              category: "湿度偏差过大",
              alertTime: currentTime,
              level: "中危",
              action: "调整空调设定湿度",
              actionTime: currentTime,
              deviceId: "AC_001"
            }
            this.sdisConnected = 2;
            this.logAlert(alert)
          }
        }
      } else {
        console.log('📊 湿度数据无变化，跳过湿度报警检查')
      }
      
      // PM25相关报警检查（如果有的话）
      if (pm25Changed) {
        // 这里可以添加PM25相关的报警逻辑
      }
      
      // 更新上一次的数据
      this.updatePreviousData(apiData)
    },
    
    // 更新上一次的数据
    updatePreviousData(apiData) {
      const { temperature, humidity, pm25 } = apiData
      this.previousData.temperature = temperature
      this.previousData.humidity = humidity
      this.previousData.pm25 = pm25
    },
    
    // 记录报警到控制台并调用创建告警接口
    async logAlert(alert) {
      try {
        await alertApi.create(alert)
      } catch (error) {
        console.error('❌ 告警记录创建失败:', error)
      }
    },
    
    // 降低目标温度
    decreaseTemperature() {
      if (this.targetTemperature > 16) {
        const oldTemp = this.targetTemperature
        this.targetTemperature--
        this.showTemperatureChangeToast()
        // 记录温度调节日志
        this.logTemperatureAdjustment('降低', oldTemp, this.targetTemperature)
      } else {
        uni.showToast({
          title: '温度不能低于16°C',
          icon: 'none'
        })
      }
    },
    
    // 温度输入事件处理
    onTemperatureInput(event) {
      const value = event.detail.value
      this.tempInputValue = value
      this.validateTemperatureInput(value)
    },
    
    // 温度输入框获得焦点
    onTemperatureFocus() {
      this.isTempInputFocused = true
      this.tempInputValue = this.targetTemperature.toString()
      this.tempValidationMessage = ''
    },
    
    // 温度输入框失去焦点
    onTemperatureBlur() {
      this.isTempInputFocused = false
      const value = parseFloat(this.tempInputValue)
      
      if (this.tempValidationMessage === '') {
        // 如果没有验证错误，更新目标温度
        if (!isNaN(value)) {
          const oldTemp = this.targetTemperature
          this.targetTemperature = value
          this.showTemperatureChangeToast()
          // 记录温度调节日志
          this.logTemperatureAdjustment('设置', oldTemp, this.targetTemperature)
        }
        this.tempInputValue = ''
      } else {
        // 如果有验证错误，恢复原值
        this.tempInputValue = ''
      }
    },
    
    // 温度输入验证
    validateTemperatureInput(value) {
      if (value === '') {
        this.tempValidationMessage = ''
        this.tempValidationClass = ''
        return
      }
      
      const numValue = parseFloat(value)
      
      if (isNaN(numValue)) {
        this.tempValidationMessage = '请输入有效的数字'
        this.tempValidationClass = 'error'
        return
      }
      
      if (numValue < 16) {
        this.tempValidationMessage = '温度不能低于16°C'
        this.tempValidationClass = 'error'
        return
      }
      
      if (numValue > 30) {
        this.tempValidationMessage = '温度不能高于30°C'
        this.tempValidationClass = 'error'
        return
      }
      
      if (numValue % 0.5 !== 0) {
        this.tempValidationMessage = '温度精度为0.5°C'
        this.tempValidationClass = 'warning'
        return
      }
      
      // 验证通过
      this.tempValidationMessage = ''
      this.tempValidationClass = ''
    },
    
    // 提高目标温度
    increaseTemperature() {
      if (this.targetTemperature < 30) {
        const oldTemp = this.targetTemperature
        this.targetTemperature++
        this.showTemperatureChangeToast()
        // 记录温度调节日志
        this.logTemperatureAdjustment('升高', oldTemp, this.targetTemperature)
      } else {
        uni.showToast({
          title: '温度不能高于30°C',
          icon: 'none'
        })
      }
    },
    
    // 降低目标湿度
    decreaseHumidity() {
      if (this.targetHumidity > 30) {
        const oldHumidity = this.targetHumidity
        this.targetHumidity--
        this.showHumidityChangeToast()
        // 记录湿度调节日志
        this.logHumidityAdjustment('降低', oldHumidity, this.targetHumidity)
      } else {
        uni.showToast({
          title: '湿度不能低于30%',
          icon: 'none'
        })
      }
    },
    
    // 提高目标湿度
    increaseHumidity() {
      if (this.targetHumidity < 80) {
        const oldHumidity = this.targetHumidity
        this.targetHumidity++
        this.showHumidityChangeToast()
        // 记录湿度调节日志
        this.logHumidityAdjustment('升高', oldHumidity, this.targetHumidity)
      } else {
        uni.showToast({
          title: '湿度不能高于80%',
          icon: 'none'
        })
      }
    },
    
    // 湿度输入事件处理
    onHumidityInput(event) {
      const value = event.detail.value
      this.humidityInputValue = value
      this.validateHumidityInput(value)
    },
    
    // 湿度输入框获得焦点
    onHumidityFocus() {
      this.isHumidityInputFocused = true
      this.humidityInputValue = this.targetHumidity.toString()
      this.humidityValidationMessage = ''
    },
    
    // 湿度输入框失去焦点
    onHumidityBlur() {
      this.isHumidityInputFocused = false
      const value = parseFloat(this.humidityInputValue)
      
      if (this.humidityValidationMessage === '') {
        // 如果没有验证错误，更新目标湿度
        if (!isNaN(value)) {
          const oldHumidity = this.targetHumidity
          this.targetHumidity = value
          this.showHumidityChangeToast()
          // 记录湿度调节日志
          this.logHumidityAdjustment('设置', oldHumidity, this.targetHumidity)
        }
        this.humidityInputValue = ''
      } else {
        // 如果有验证错误，恢复原值
        this.humidityInputValue = ''
      }
    },
    
    // 湿度输入验证
    validateHumidityInput(value) {
      if (value === '') {
        this.humidityValidationMessage = ''
        this.humidityValidationClass = ''
        return
      }
      
      const numValue = parseFloat(value)
      
      if (isNaN(numValue)) {
        this.humidityValidationMessage = '请输入有效的数字'
        this.humidityValidationClass = 'error'
        return
      }
      
      if (numValue < 10) {
        this.humidityValidationMessage = '湿度不能低于10%'
        this.humidityValidationClass = 'error'
        return
      }
      
      if (numValue > 80) {
        this.humidityValidationMessage = '湿度不能高于80%'
        this.humidityValidationClass = 'error'
        return
      }
      
      if (numValue % 1 !== 0) {
        this.humidityValidationMessage = '湿度精度为1%'
        this.humidityValidationClass = 'warning'
        return
      }
      
      // 验证通过
      this.humidityValidationMessage = ''
      this.humidityValidationClass = ''
    },
    
    // 空调湿度更新
    showHumidityChangeToast() {
      // 发送空调参数到MQTT
      this.sendAirConditionerParams()
      
      // 湿度变化后检查报警（使用当前页面数据）
      this.checkAlertsFromApiData({
        temperature: this.temperature,
        humidity: this.humidity,
        pm25: this.cleanliness
      })
    },
    
    // 空调温度更新
    showTemperatureChangeToast() {
      // 发送空调参数到MQTT
      this.sendAirConditionerParams()
      
      // 温度变化后检查报警（使用当前页面数据）
      this.checkAlertsFromApiData({
        temperature: this.temperature,
        humidity: this.humidity,
        pm25: this.cleanliness
      })
    },
    
    // 发送空调参数
    async sendAirConditionerParams() {
      try {
        // 根据MQTT文档，空调温度使用BSQWD，但控制指令可能使用不同的TagName
        // 发送温度参数 - 使用BSQWD作为TagName（与接收数据保持一致）
        const temperatureData = {
          "TagValue": this.targetTemperature,
          "TagName": "SDWD", // 使用与接收数据一致的TagName
          "method": "setValue"
        }
        
        // 发送湿度参数 - 根据文档WSD设备湿度使用SD
        const humidityData = {
          "TagValue": this.targetHumidity,
          "TagName": "SDSD", // 使用与WSD设备湿度一致的TagName
          "method": "setValue"
        }
        // 调用发送MQTT数据的方法
        const tempSuccess = sendMqttData(temperatureData)
        const humiditySuccess = sendMqttData(humidityData)
        
        if (tempSuccess && humiditySuccess) {
          // 发送成功后调用提交温湿度数据API
          try {
            await this.submitTemperatureData()
            // 显示成功提示
            uni.showToast({
              title: '参数设置成功',
              icon: 'success',
              duration: 1500
            })
          } catch (apiError) {
            uni.showToast({
              title: 'MQTT已发送，接口保存失败',
              icon: 'none',
              duration: 2500
            })
          }
          
        } else {
          uni.showToast({
            title: 'MQTT发送失败',
            icon: 'error',
            duration: 2000
          })
        }
      } catch (error) {
        uni.showToast({
          title: '参数设置失败',
          icon: 'error',
          duration: 2000
        })
      }
    },
    
    // 空调开关切换控制
    async toggleAirConditioner() {
      if (this.acStatus === 2) { // 运行中，执行关机
        await this.sendAirConditionerControl(2, '关机')
        // 记录关机日志
        await this.logAirConditionerOperation('关机')
      } else if (this.acStatus === 0) { // 待机，执行开机
        await this.sendAirConditionerControl(1, '开机')
        // 记录开机日志
        await this.logAirConditionerOperation('开机')
      }
    },
    
    // 获取空调按钮样式类
    getAcButtonClass() {
      if (this.acStatus === 2) { // 运行中
        return 'power-off'
      } else if (this.acStatus === 0) { // 待机
        return 'power-on'
      } else {
        return 'power-disabled' // 其他状态（启动中、关机中、连接中）
      }
    },
    
    // 获取空调按钮文字
    getAcButtonText() {
      if (this.acStatus === 2) { // 运行中
        return '关机'
      } else if (this.acStatus === 0) { // 待机
        return '开机'
      } else {
        return this.acStatusList[this.acStatus] || '连接中'
      }
    },
    
    // 判断是否可以操作空调
    canOperateAc() {
      // 只有在待机(0)或运行中(2)状态才可以操作
      return this.acStatus === 0 || this.acStatus === 2
    },
    
    // 记录空调操作日志
    async logAirConditionerOperation(operation) {
      try {
        const currentTime = this.formatDateTime(new Date())
        const logEvent = {
          eventType: `空调${operation}`,
          eventTime: currentTime,
          status: "已完成",
          description: `用户手动执行空调${operation}操作，当前温度：${this.temperature}°C，目标温度：${this.targetTemperature}°C，空调状态：${this.acStatusList[this.acStatus]}`,
          deviceId: "AC_001"
        }
        
        const response = await eventApi.create(logEvent)
        
        // 显示日志记录成功提示
        uni.showToast({
          title: `操作日志已保存`,
          icon: 'success',
          duration: 1000
        })
      } catch (error) {
        console.error(`❌ 空调${operation}日志记录失败:`, error)
        // 日志记录失败不影响主要功能，只记录错误
        uni.showToast({
          title: `日志保存失败`,
          icon: 'none',
          duration: 1000
        })
      }
    },
    
    // 记录温度调节日志
    async logTemperatureAdjustment(action, oldTemp, newTemp) {
      try {
        const currentTime = this.formatDateTime(new Date())
        const logEvent = {
          eventType: `空调目标温度${action}:${oldTemp}°C -> ${newTemp}°C`,
          eventTime: currentTime,
          status: "已完成",
          description: `用户手动${action}空调目标温度，从${oldTemp}°C调整到${newTemp}°C，当前环境温度：${this.temperature}°C，空调状态：${this.acStatusList[this.acStatus]}`,
          deviceId: "AC_001"
        }
        
        const response = await eventApi.create(logEvent)
      } catch (error) {
        console.error(`❌ 温度${action}日志记录失败:`, error)
        // 日志记录失败不影响主要功能，只记录错误
      }
    },
    
    // 记录湿度调节日志
    async logHumidityAdjustment(action, oldHumidity, newHumidity) {
      try {
        const currentTime = this.formatDateTime(new Date())
        const logEvent = {
          eventType: `空调目标湿度${action}:${oldHumidity}% -> ${newHumidity}%`,
          eventTime: currentTime,
          status: "已完成",
          description: `用户手动${action}空调目标湿度，从${oldHumidity}%调整到${newHumidity}%，当前环境湿度：${this.humidity}%，空调状态：${this.acStatusList[this.acStatus]}`,
          deviceId: "AC_001"
        }
        
        const response = await eventApi.create(logEvent)
      } catch (error) {
        console.error(`❌ 湿度${action}日志记录失败:`, error)
        // 日志记录失败不影响主要功能，只记录错误
      }
    },
    
    // 记录参数设定保存日志
    async logSettingsSave() {
      try {
        const currentTime = this.formatDateTime(new Date())
        const logEvent = {
          eventType: `环境控制范围更新:温度范围${this.tempSettings.min}°C-${this.tempSettings.max}°C，湿度范围${this.humiditySettings.min}%-${this.humiditySettings.max}%`,
          eventTime: currentTime,
          status: "已完成",
          description: `用户修改温湿度控制范围：温度范围${this.tempSettings.min}°C-${this.tempSettings.max}°C，湿度范围${this.humiditySettings.min}%-${this.humiditySettings.max}%，当前环境温度：${this.temperature}°C，当前环境湿度：${this.humidity}%，空调状态：${this.acStatusList[this.acStatus]}`,
          deviceId: "WSD_001"
        }
        
        const response = await eventApi.create(logEvent)
      } catch (error) {
        console.error(`❌ 参数设定保存日志记录失败:`, error)
        // 日志记录失败不影响主要功能，只记录错误
      }
    },
    
    // 发送空调控制指令
    async sendAirConditionerControl(ctrlValue, actionName) {
      this.acControlLoading = true;
      try {
        // 构建控制指令数据
        const controlData = {
          "TagValue": ctrlValue,
          "TagName": "ctrlword",
          "method": "setValue"
        }
        
        // 调用发送MQTT数据的方法
        const success = sendMqttData(controlData)
        this.acControlLoading = false;
        if (success) {
          // 显示成功提示
          uni.showToast({
            title: `${actionName}指令已发送`,
            icon: 'success',
            duration: 1500
          })
        } else {
          uni.showToast({
            title: `${actionName}失败`,
            icon: 'error',
            duration: 2000
          })
        }
      } catch (error) {
        uni.showToast({
          title: `${actionName}异常`,
          icon: 'error',
          duration: 2000
        })
      } finally {
        // 清除加载状态
        this.acControlLoading = false
      }
    },
    
    // 提交温湿度数据
    async submitTemperatureData() {
      try {
        const temperatureHumidityData = {
          temperature: this.targetTemperature,
          humidity: this.targetHumidity,
          deviceId: "TH_SENSOR_001",
          timestamp: new Date().toISOString(),
          source: "manual_setting" // 标识为手动设置
        }
        const response = await thDataApi.submit(temperatureHumidityData)
      } catch (error) {
        // 接口失败不影响MQTT发送，只记录日志
        throw error // 重新抛出错误，让调用方知道接口失败了
      }
    },
    
    // 手动重连MQTT
    manualReconnect() {
      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()
    },
    async saveSettings() {
      try {
        // 构建API请求数据
        const wsdData = {
          id: 1, // 默认使用ID为1的设置
          settingName: "默认空调设置",
          minTemperature: parseFloat(this.tempSettings.min),
          maxTemperature: parseFloat(this.tempSettings.max),
          minHumidity: parseFloat(this.humiditySettings.min),
          maxHumidity: parseFloat(this.humiditySettings.max),
          description: "移动式检修车间空调温湿度控制区间",
          createdTime: new Date().toISOString(),
          updatedTime: new Date().toISOString()
        }
        
        // 调用API保存设置
        const response = await wsdApi.update(wsdData)
        // 保存设置到本地
        this.temperatureRange = { ...this.tempSettings }
        this.humidityRange = { ...this.humiditySettings }
        
        // 更新最后更新时间
        this.lastUpdate = new Date().toLocaleString()
        
        // 关闭弹窗
        this.closeSettingsModal()
        
        // 记录参数设定保存日志
        await this.logSettingsSave()
        
        // 显示保存成功提示
        uni.showToast({
          title: '参数设置已保存',
          icon: 'success'
        })
      } catch (error) {
        // 显示错误提示
        uni.showToast({
          title: '保存失败，请重试',
          icon: 'none'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.environment-page {
  min-height: 100vh;
  background: #f5f6fa;
  padding: 0;
  overflow-x: hidden;
}

/* 固定头部样式 */
.fixed-header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 1000;
  background: #ffffff;
  padding: 15rpx 20rpx; /* 减少padding，但保持基本间距 */
  border-bottom: 2rpx solid #e1e5e9;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

/* 内容区域 */
.tabbar-content {
  padding: 20rpx 20rpx 120rpx; /* 增加底部padding为tabbar留出空间 */
  margin-top: 150rpx; /* 为固定头部留出空间，增加距离 */
  min-height: calc(100vh - 200rpx); /* 调整最小高度计算 */
}

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

.card-item:hover {
  transform: translateY(-4rpx);
  box-shadow: 0 12rpx 40rpx rgba(0,0,0,0.15);
}

.card-icon {
  font-size: 36rpx;
  margin-bottom: 12rpx;
}

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

.card-label {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 8rpx;
  font-weight: 500;
}

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

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

.card-status.active {
  background-color: #4caf50;
  box-shadow: 0 0 8rpx rgba(76, 175, 80, 0.5);
}

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

/* 禁用按钮样式 */
button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}


.parameter-details {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
  margin-bottom: 20rpx;
}



/* 空调目标参数设置样式 */
.air-conditioner-settings {
  background: #ffffff;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
  border: 1rpx solid #e1e5e9;
  border-left: 4rpx solid #3498db;
}

.ac-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #e1e5e9;
}

.ac-title-container {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.ac-icon {
  font-size: 28rpx;
}

.ac-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #2c3e50;
}

.ac-status-indicator {
  display: flex;
  align-items: center;
  gap: 8rpx;
  background: rgba(52, 152, 219, 0.1);
  padding: 6rpx 12rpx;
  border-radius: 16rpx;
  border: 1rpx solid rgba(52, 152, 219, 0.2);
}

.status-dot {
  width: 10rpx;
  height: 10rpx;
  border-radius: 50%;
}

.status-dot.active {
  background: #27ae60;
  box-shadow: 0 0 8rpx rgba(39, 174, 96, 0.4);
}

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

/* 控制卡片样式 */
.ac-control-card {
  background: #f8f9fa;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-bottom: 16rpx;
  border: 1rpx solid #e1e5e9;
  transition: all 0.2s ease;
}

.ac-control-card:last-child {
  margin-bottom: 0;
}

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

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

.control-icon-container {
  display: flex;
  align-items: center;
  gap: 12rpx;
}

.control-label {
  font-size: 26rpx;
  color: #2c3e50;
  font-weight: 600;
}

.ac-temp-control {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 24rpx;
  background: #ffffff;
  border-radius: 12rpx;
  padding: 16rpx 24rpx;
  border: 1rpx solid #e1e5e9;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  margin-bottom: 12rpx;
}

.ac-btn {
  width: 72rpx;
  height: 72rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  color: white;
  transition: all 0.3s ease;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.15);
  position: relative;
  overflow: hidden;
}

.ac-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0) 100%);
  border-radius: 50%;
}

.btn-icon {
  font-size: 32rpx;
  font-weight: 700;
  position: relative;
  z-index: 1;
}

.temperature-decrease {
  background: linear-gradient(135deg, #e74c3c 0%, #c0392b 100%);
}

.temperature-increase {
  background: linear-gradient(135deg, #27ae60 0%, #229954 100%);
}

.humidity-decrease {
  background: linear-gradient(135deg, #f39c12 0%, #e67e22 100%);
}

.humidity-increase {
  background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
}

.ac-btn:active {
  transform: scale(0.92);
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.2);
}

/* 空调开关控制按钮样式 */
.ac-power-controls {
  display: flex;
  justify-content: center;
  background: #ffffff;
  border-radius: 8rpx;
  padding: 20rpx;
  border: 1rpx solid #e1e5e9;
  margin-bottom: 12rpx;
}

.ac-power-btn {
  width: 160rpx;
  // height: 60rpx;
  border-radius: 6rpx;
  border: 1rpx solid;
  font-size: 28rpx;
  font-weight: 500;
  transition: all 0.2s ease;
}

.power-on {
  background: #27ae60;
  color: white;
  border-color: #27ae60;
}

.power-on:active {
  background: #229954;
  border-color: #229954;
}

.power-off {
  background: #e74c3c;
  color: white;
  border-color: #e74c3c;
}

.power-off:active {
  background: #c0392b;
  border-color: #c0392b;
}

.power-disabled {
  background: #f39c12;
  color: white;
  // border-color: #f39c12;
}

.power-disabled:active {
  background: #e67e22;
  // border-color: #e67e22;
}

.ac-power-btn:disabled {
  background: #bdc3c7 !important;
  color: #7f8c8d !important;
  border-color: #bdc3c7 !important;
  opacity: 0.6;
  cursor: not-allowed;
}

.ac-temp-display {
  display: flex;
  align-items: baseline;
  gap: 8rpx;
  min-width: 120rpx;
  justify-content: center;
  background: #f8f9fa;
  border-radius: 8rpx;
  padding: 12rpx 16rpx;
  border: 2rpx solid #e1e5e9;
  transition: border-color 0.2s ease;
}

.ac-temp-display:focus-within {
  border-color: #3498db;
  background: #ffffff;
}

.ac-temp-input {
  font-size: 36rpx;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1;
  text-align: center;
  border: none;
  background: transparent;
  outline: none;
  width: 80rpx;
  padding: 0;
}

.ac-temp-input:focus {
  color: #3498db;
}

.ac-temp-unit {
  font-size: 24rpx;
  color: #7f8c8d;
  font-weight: 600;
}

.ac-temp-validation {
  text-align: center;
}

.validation-text {
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  display: inline-block;
  font-weight: 500;
}

.validation-text.error {
  color: #e74c3c;
  background: rgba(231, 76, 60, 0.1);
  border: 1rpx solid rgba(231, 76, 60, 0.3);
}

.validation-text.warning {
  color: #f39c12;
  background: rgba(243, 156, 18, 0.1);
  border: 1rpx solid rgba(243, 156, 18, 0.3);
}

.environment-control {
  background: #ffffff;
  border-radius: 8rpx;
  padding: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
  border: 1rpx solid #e1e5e9;
  border-left: 4rpx solid #16a085;
}

.env-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding-bottom: 16rpx;
  border-bottom: 1rpx solid #e1e5e9;
}

.env-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #2c3e50;
}

.status-dot {
  width: 10rpx;
  height: 10rpx;
  border-radius: 50%;
  background: #16a085;
}

.status-text {
  font-size: 22rpx;
  color: #2c3e50;
  font-weight: 500;
}

.env-info {
  margin-bottom: 20rpx;
}

.info-label {
  font-size: 26rpx;
  // color: #34495e;
  font-weight: 500;
}

.info-value {
  font-size: 24rpx;
  color: #16a085;
  font-weight: 600;
}

.control-ranges {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.range-item {
  padding: 16rpx;
  background: #f8f9fa;
  border-radius: 6rpx;
}

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

.range-label {
  font-size: 26rpx;
  color: #2c3e50;
  font-weight: 600;
}

.range-status {
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
  font-size: 22rpx;
  font-weight: 500;
}

.range-status.normal {
  background: #d5f4e6;
  color: #27ae60;
}

.range-status.low {
  background: #ffeaa7;
  color: #e67e22;
}

.range-status.high {
  background: #fab1a0;
  color: #e74c3c;
}

.range-status.no-data {
  background: #ecf0f1;
  color: #7f8c8d;
}

.settings-button {
  background: #2980b9;
  color: white;
  padding: 16rpx 20rpx;
  border-radius: 6rpx;
  font-size: 26rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8rpx;
  width: 100%;
  border: none;
  transition: background-color 0.2s ease;
  font-weight: 600;
}

.settings-button:active {
  background: #21618c;
}

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

.settings-text {
  font-size: 26rpx;
  font-weight: 600;
}

/* 弹窗样式 */
.settings-modal {
  background: #ffffff;
  border-radius: 8rpx;
  width: 600rpx;
  max-width: 90vw;
  overflow: hidden;
  border: 1rpx solid #e1e5e9;
  box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.15);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 24rpx;
  background: #f8f9fa;
  border-bottom: 1rpx solid #e1e5e9;
}

.modal-title {
  font-size: 28rpx;
  font-weight: 600;
  color: #2c3e50;
}

.close-btn {
  font-size: 24rpx;
  color: #7f8c8d;
  padding: 8rpx;
  border-radius: 4rpx;
  background: #ecf0f1;
  width: 48rpx;
  height: 48rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.2s ease;
  border: 1rpx solid #bdc3c7;
}

.close-btn:active {
  background: #d5dbdb;
  color: #e74c3c;
}

.modal-content {
  padding: 24rpx;
}

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

.setting-label {
  display: block;
  font-size: 26rpx;
  color: #2c3e50;
  margin-bottom: 12rpx;
  font-weight: 600;
}

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

.range-input {
  flex: 1;
  padding: 16rpx 12rpx;
  border: 1rpx solid #e1e5e9;
  border-radius: 6rpx;
  font-size: 26rpx;
  text-align: center;
  background: #ffffff;
  transition: border-color 0.2s ease;
  font-weight: 500;
  color: #2c3e50;
}

.range-input:focus {
  border-color: #2980b9;
  outline: none;
}

.range-separator {
  font-size: 26rpx;
  color: #2980b9;
  font-weight: 600;
  min-width: 32rpx;
  text-align: center;
}

.unit {
  font-size: 24rpx;
  color: #2980b9;
  min-width: 48rpx;
  font-weight: 600;
}

.modal-actions {
  display: flex;
  gap: 16rpx;
  padding: 20rpx 24rpx;
  background: #f8f9fa;
  border-top: 1rpx solid #e1e5e9;
}

.cancel-btn {
  flex: 1;
  background: #ecf0f1;
  color: #7f8c8d;
  padding: 16rpx 20rpx;
  border-radius: 6rpx;
  font-size: 26rpx;
  border: 1rpx solid #bdc3c7;
  transition: background-color 0.2s ease;
  font-weight: 600;
}

.cancel-btn:active {
  background: #d5dbdb;
}

.confirm-btn {
  flex: 1;
  background: #2980b9;
  color: white;
  padding: 16rpx 20rpx;
  border-radius: 6rpx;
  font-size: 26rpx;
  border: none;
  transition: background-color 0.2s ease;
  font-weight: 600;
}

.confirm-btn:active {
  background: #21618c;
}

/* 响应式设计 */
@media screen and (max-width: 750rpx) {
  .fixed-header {
    padding: 16rpx 20rpx;
  }
  
  .tabbar-content {
    padding: 16rpx 16rpx 100rpx; /* 调整小屏幕下的内边距 */
    margin-top: 90rpx; /* 调整小屏幕下的顶部间距，增加距离 */
  }
  

  
  .air-conditioner-settings {
    padding: 16rpx;
  }
  
  .ac-control-card {
    padding: 16rpx;
  }
  
  .ac-btn {
    width: 64rpx;
    height: 64rpx;
  }
  
  .btn-icon {
    font-size: 28rpx;
  }
  
  .environment-control {
    padding: 16rpx;
  }
  
  .ac-temp-control {
    gap: 16rpx;
    padding: 12rpx 16rpx;
  }
  
  .ac-btn {
    width: 56rpx;
    height: 56rpx;
    font-size: 28rpx;
  }
  
  .settings-modal {
    width: 520rpx;
  }
  
  .modal-content {
    padding: 20rpx;
  }
  
  .modal-actions {
    padding: 16rpx 20rpx;
  }
}

@media screen and (max-width: 600rpx) {
  .fixed-header {
    padding: 12rpx 16rpx;
  }
  
  .tabbar-content {
    padding: 16rpx 16rpx 90rpx; /* 更小屏幕下的内边距 */
    margin-top: 80rpx; /* 更小屏幕下的顶部间距，增加距离 */
  }
  
  .header-title {
    font-size: 28rpx;
  }
  
  .detail-label {
    font-size: 24rpx;
  }
  
  .detail-value {
    font-size: 24rpx;
  }
  
  .ac-title {
    font-size: 24rpx;
  }
  
  .env-title {
    font-size: 24rpx;
  }
  
  .ac-temp-control {
    gap: 16rpx;
    padding: 12rpx 16rpx;
  }
  
  .ac-btn {
    width: 56rpx;
    height: 56rpx;
  }
  
  .btn-icon {
    font-size: 24rpx;
  }
  
  .control-label {
    font-size: 24rpx;
  }
  
  .ac-temp-input {
    font-size: 32rpx;
    width: 70rpx;
  }
  
  .settings-modal {
    width: 480rpx;
  }
}
</style>