<template>
  <view class="page-container visual-monitoring-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="monitoring-content">
      <view class="c">
        <image 
          class="camera-image" 
          :src="currentImage" 
          mode="aspectFill"
          @load="onImageLoad"
          @error="onImageError"
        />
        
        <!-- 加载状态 -->
        <view class="loading-overlay" v-if="isLoading">
          <view class="loading-spinner"></view>
          <text class="loading-text">加载中...</text>
        </view>
        
        <!-- 连接状态指示器 -->
        <view class="connection-status" :class="{ connected: isConnected }">
          <view class="status-dot"></view>
          <text class="status-text">{{ isConnected ? '已连接' : '未连接' }}</text>
        </view>
      </view>
    </view>
    
    <!-- 底部控制按钮 -->
    <view class="control-panel">
      <button 
        class="control-button on-button" 
        :class="{ active: isDeviceOn }"
        @click="toggleDevice(true)"
        :disabled="isControlling"
      >
        开
      </button>
      <button 
        class="control-button off-button" 
        :class="{ active: !isDeviceOn }"
        @click="toggleDevice(false)"
        :disabled="isControlling"
      >
        关
      </button>
    </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue';

// 页面状态
const currentImage = ref('/static/inspection-room.jpg');
const isLoading = ref(false);
const isConnected = ref(false);
const isDeviceOn = ref(false);
const isControlling = ref(false);

// MQTT服务接口（预留）
const mqttService = {
  // 连接MQTT服务器
  connect: async () => {
    console.log('MQTT视觉监控连接中...');
    try {
      // 模拟连接延迟
      await new Promise(resolve => setTimeout(resolve, 1000));
      isConnected.value = true;
      console.log('MQTT视觉监控连接成功');
      return Promise.resolve();
    } catch (error) {
      console.error('MQTT连接失败:', error);
      isConnected.value = false;
      return Promise.reject(error);
    }
  },
  
  // 订阅图像数据
  subscribeImageData: () => {
    console.log('订阅视觉监控图像数据');
    // 这里后期会实现真实的MQTT图像订阅
    return Promise.resolve();
  },
  
  // 获取实时图像
  getRealtimeImage: async () => {
    console.log('获取实时监控图像');
    try {
      // 模拟图像请求
      isLoading.value = true;
      await new Promise(resolve => setTimeout(resolve, 500));
      
      // 模拟返回不同的图像
      const images = [
        '/static/inspection-room.jpg',
        '/static/camera-placeholder.jpg'
      ];
      const randomImage = images[Math.floor(Math.random() * images.length)];
      currentImage.value = randomImage;
      
      isLoading.value = false;
      return Promise.resolve(randomImage);
    } catch (error) {
      console.error('获取图像失败:', error);
      isLoading.value = false;
      return Promise.reject(error);
    }
  },
  
  // 发送设备控制指令
  sendDeviceControl: async (command) => {
    console.log(`发送设备控制指令: ${command}`);
    try {
      isControlling.value = true;
      // 模拟控制指令发送延迟
      await new Promise(resolve => setTimeout(resolve, 800));
      
      // 更新设备状态
      isDeviceOn.value = command === 'on';
      isControlling.value = false;
      
      uni.showToast({
        title: `设备已${command === 'on' ? '开启' : '关闭'}`,
        icon: 'success'
      });
      
      return Promise.resolve();
    } catch (error) {
      console.error('设备控制失败:', error);
      isControlling.value = false;
      uni.showToast({
        title: '控制失败',
        icon: 'error'
      });
      return Promise.reject(error);
    }
  },
  
  // 获取设备状态
  getDeviceStatus: async () => {
    console.log('获取设备状态');
    try {
      // 模拟获取设备状态
      await new Promise(resolve => setTimeout(resolve, 300));
      const status = Math.random() > 0.5; // 随机状态
      isDeviceOn.value = status;
      return Promise.resolve(status);
    } catch (error) {
      console.error('获取设备状态失败:', error);
      return Promise.reject(error);
    }
  },
  
  // 断开连接
  disconnect: () => {
    console.log('MQTT视觉监控断开连接');
    isConnected.value = false;
    // 这里后期会实现真实的MQTT断开
  }
};

// 设备控制
const toggleDevice = async (turnOn) => {
  if (isControlling.value || !isConnected.value) return;
  
  try {
    await mqttService.sendDeviceControl(turnOn ? 'on' : 'off');
    // 控制成功后刷新图像
    setTimeout(() => {
      mqttService.getRealtimeImage();
    }, 1000);
  } catch (error) {
    console.error('设备控制失败:', error);
  }
};

// 图像加载事件
const onImageLoad = () => {
  console.log('图像加载成功');
  isLoading.value = false;
};

const onImageError = () => {
  console.error('图像加载失败');
  isLoading.value = false;
  uni.showToast({
    title: '图像加载失败',
    icon: 'error'
  });
};

// 定时刷新图像
let imageRefreshTimer = null;

const startImageRefresh = () => {
  if (imageRefreshTimer) return;
  
  imageRefreshTimer = setInterval(() => {
    if (isConnected.value && !isLoading.value) {
      mqttService.getRealtimeImage();
    }
  }, 5000); // 每5秒刷新一次图像
};

const stopImageRefresh = () => {
  if (imageRefreshTimer) {
    clearInterval(imageRefreshTimer);
    imageRefreshTimer = null;
  }
};

// 组件生命周期
onMounted(async () => {
  try {
    // 连接MQTT并初始化
    await mqttService.connect();
    await mqttService.subscribeImageData();
    await mqttService.getDeviceStatus();
    await mqttService.getRealtimeImage();
    
    // 开始定时刷新图像
    startImageRefresh();
  } catch (error) {
    console.error('视觉监控初始化失败:', error);
    uni.showToast({
      title: '连接失败',
      icon: 'error'
    });
  }
});

onUnmounted(() => {
  stopImageRefresh();
  mqttService.disconnect();
});
</script>

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

.visual-monitoring-container {
  // 继承通用页面容器样式
  position: relative;
}

.monitoring-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
  min-height: 500rpx;
  /* 滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: #c1c1c1 #f1f1f1;
}

/* Webkit浏览器滚动条样式 */
.monitoring-content::-webkit-scrollbar {
  width: 8rpx;
}

.monitoring-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4rpx;
}

.monitoring-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4rpx;
}

.monitoring-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.camera-container {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
//   margin: 0 30rpx;
  background-color: #000000;
  overflow: hidden;
  border-radius: 16rpx;
}

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

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 20rpx;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid rgba(255, 255, 255, 0.3);
  border-top: 4rpx solid #ffffff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

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

.connection-status {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  display: flex;
  align-items: center;
  gap: 8rpx;
  padding: 8rpx 16rpx;
  background-color: rgba(0, 0, 0, 0.6);
  border-radius: 20rpx;
  backdrop-filter: blur(10rpx);
}

.status-dot {
  width: 12rpx;
  height: 12rpx;
  border-radius: 50%;
  background-color: #ff4444;
  transition: background-color 0.3s;
}

.connection-status.connected .status-dot {
  background-color: #44ff44;
}

.status-text {
  color: white;
  font-size: 24rpx;
  font-weight: 500;
}

.control-panel {
  position: absolute;
  bottom: 24rpx;
  left: 50%;
  transform: translateX(-50%);
  display: flex;
  justify-content: center;
  gap: 24rpx;
  padding: 16rpx 24rpx;
  background-color: rgba(255, 255, 255, 0.95);
  border-radius: 8rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10rpx);
  z-index: 20;
}

.control-button {
  width: 120rpx;
  height: 60rpx;
  border: none;
  border-radius: 6rpx;
  font-size: 24rpx;
  font-weight: 500;
  color: white;
  position: relative;
  overflow: hidden;
  transition: all 0.2s ease;
  box-shadow: 0 1rpx 3rpx rgba(0, 0, 0, 0.1);
}

.control-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), transparent);
  opacity: 0;
  transition: opacity 0.2s;
}

.control-button:hover::before {
  opacity: 1;
}

.on-button {
  background: #1a73e8;
}

.on-button.active {
  background: #1557b0;
  box-shadow: 0 2rpx 6rpx rgba(26, 115, 232, 0.3);
}

.off-button {
  background: #5f6368;
}

.off-button.active {
  background: #3c4043;
  box-shadow: 0 2rpx 6rpx rgba(95, 99, 104, 0.3);
}

.control-button:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.control-button:not(:disabled):active {
  transform: translateY(1rpx);
  box-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.1);
}

// 响应式设计 - 平板设备适配
@media (min-width: 768px) and (max-width: 1024px) {
  .camera-image {
    min-height: 500rpx;
  }
  
  .control-button {
    font-size: 26rpx;
    width: 140rpx;
    height: 70rpx;
  }
}

// 响应式设计 - 手机设备适配
@media (max-width: 750rpx) {
  .camera-image {
    min-height: 400rpx;
  }
  
  .control-button {
    font-size: 20rpx;
    width: 100rpx;
    height: 50rpx;
  }
}

// 响应式设计 - 大屏设备适配
@media (min-width: 1200px) {
  .camera-image {
    min-height: 600rpx;
  }
  
  .control-button {
    font-size: 28rpx;
    width: 160rpx;
    height: 80rpx;
  }
}
</style>