<template>
  <view class="container">
    <!-- 地块信息 -->
    <view class="plot-section">
      <text class="plot-text">当前查看地块：</text>
      <text class="plot-name">{{ currentPlot }}</text>
    </view>
    
    <!-- 顶部区域：概览统计 -->
    <view class="overview-section">
      <view class="stat-item">
        <view class="stat-icon-wrapper">
          <image src="/static/icons/device_num.png" mode="aspectFit" class="stat-icon-img"></image>
        </view>
        <text class="stat-value">{{ totalDevices }}</text>
        <text class="stat-label">总数</text>
      </view>
      
      <view class="stat-item">
        <view class="stat-icon-wrapper online">
          <image src="/static/icons/device_online.png" mode="aspectFit" class="stat-icon-img"></image>
        </view>
        <text class="stat-value online">{{ onlineDevices }}</text>
        <text class="stat-label">在线</text>
      </view>
      
      <view class="stat-item">
        <view class="stat-icon-wrapper offline">
          <image src="/static/icons/device_offline.png" mode="aspectFit" class="stat-icon-img"></image>
        </view>
        <text class="stat-value offline">{{ offlineDevices }}</text>
        <text class="stat-label">离线</text>
      </view>
      
      <view class="stat-item">
        <view class="stat-icon-wrapper alert">
          <image src="/static/icons/device_alert.png" mode="aspectFit" class="stat-icon-img"></image>
        </view>
        <text class="stat-value alert">{{ alertDevices }}</text>
        <text class="stat-label">告警</text>
      </view>
    </view>
    
    <!-- 设备网格布局 -->
    <view class="device-grid">
      <view 
        v-for="(item, index) in deviceList" 
        :key="index" 
        @click="navigateToDeviceList(item.type)"
        class="device-card"
        :class="{'has-alert': item.alerts > 0}"
        hover-class="device-card-hover"
      >
        <!-- 告警角标 -->
        <view v-if="item.alerts > 0" class="alert-badge">{{ item.alerts }}</view>
        
        <!-- 设备图标 -->
        <view class="device-icon-container">
          <image :src="item.icon" mode="aspectFit" class="device-icon"></image>
        </view>
        
        <!-- 设备名称 -->
        <text class="device-name">{{ item.name }}</text>
        
        <!-- 设备状态信息区域 -->
        <view class="device-status-container">
          <!-- 在线状态 -->
          <view class="status-info">
            <view class="status-dot online-dot"></view>
            <text class="status-text">在线</text>
            <text class="status-num online-num">{{ item.online }}</text>
          </view>
          
          <!-- 离线状态 -->
          <view class="status-info">
            <view class="status-dot offline-dot"></view>
            <text class="status-text">离线</text>
            <text class="status-num offline-num">{{ item.offline }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
// 导入API服务
import { forEach } from "../../utils/lib/request/utils";
import { fetchDeviceOverview } from "@/api/services/device.js";
import storage from "@/utils/storage.js";

export default {
  data() {
    return {
      deviceList: [],
      currentPlot: "加载中...",
      totalDevices: 0,
      onlineDevices: 0,
      offlineDevices: 0,
      alertDevices: 0,
      loading: false,
      currentFieldId: null, // 当前选中的地块ID
	  typeOnline: 0,
	  typeOffline: 0
    }
  },
  
  methods: {
    // 初始化地块信息
    initFieldInfo() {
      const fieldInfo = storage.getPlots();
	  console.log("ggg ");
      if (fieldInfo) {
		  const plotData = JSON.parse(fieldInfo);
        this.currentFieldId = plotData.id;
        this.currentPlot = plotData.name || "未选择地块";
      } else {
        this.currentPlot = "未选择地块";
      }
    },
    
    // 获取设备数据
    fetchDeviceData() {
      if (this.loading) return;
      this.loading = true;
      
      uni.showLoading({
        title: '加载中...'
      });
      
      // 调用API获取设备概览数据
      fetchDeviceOverview(this.currentFieldId)
        .then(res => {
          if (res.data.code === 200 && res.data.data) {
            const data = res.data.data;
            // 更新设备总览数据
            this.totalDevices = data.totalDevices || 0;
            this.onlineDevices = data.onlineDevices || 0;
            this.offlineDevices = data.offlineDevices || 0;
            this.alertDevices = data.alertDevices || 0;
            
            // 更新设备类型列表
            if (data.deviceList && data.deviceList.length > 0) {
              this.deviceList = data.deviceList;
            }
            
            console.log('设备概览数据加载成功');
          } else {
            this.handleApiError(res);
          }
        })
        .catch(error => {
          console.error('获取设备概览数据失败', error);
          uni.showToast({
            title: '获取设备数据失败',
            icon: 'none'
          });
        })
        .finally(() => {
          this.loading = false;
          uni.hideLoading();
        });
    },
    
    // 处理API错误
    handleApiError(res) {
      console.error('API错误', res);
      uni.showToast({
        title: res.data.msg || '获取数据失败',
        icon: 'none'
      });
    },
    
    // 跳转到对应设备列表页面
    navigateToDeviceList(type) {
		// 传递指定设备类型的在线、离线数量
		this.deviceList.forEach((item, index) => {
			if(item.type === type){
				this.typeOnline = item.online
				this.typeOffline =  item.offline
			}
		});
      uni.navigateTo({
        url: `/pages/device/device-list/index?type=${type}&typeOnline=${this.typeOnline}&typeOffline=${this.typeOffline}`
      });
    },
    
    // 切换地块
    changePlot() {
      uni.navigateTo({
        url: '/pages/field-selector/index?callback=deviceCenter'
      });
    }
  },
  
  // 页面导航配置
  onShow() {
	this.initFieldInfo();
	this.fetchDeviceData();
  },
  
  // 下拉刷新
  onPullDownRefresh() {
    this.fetchDeviceData();
    setTimeout(() => {
      uni.stopPullDownRefresh();
    }, 1000);
  }
}
</script>

<style scoped>
.container {
  padding: 30rpx;
  background-color: #F9FCFA;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 地块选择区域 */
.plot-section {
  background-color: #FFFFFF;
  border-radius: 20rpx;
  padding: 26rpx 30rpx;
  margin-bottom: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.04);
}

.plot-text {
  font-size: 28rpx;
  color: #606060;
}

.plot-name {
  font-size: 32rpx;
  color: #333333;
  font-weight: 600;
  margin: 0 12rpx;
}

/* 顶部概览统计区域 */
.overview-section {
  background-color: #F2F7F3;
  border-radius: 20rpx;
  padding: 36rpx 40rpx;
  margin-bottom: 34rpx;
  display: flex;
  justify-content: space-between;
  box-shadow: 0 6rpx 16rpx rgba(0, 0, 0, 0.03);
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
}

.stat-icon-wrapper {
  width: 90rpx;
  height: 90rpx;
  border-radius: 50%;
  background-color: #F0F0F0;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 14rpx;
  box-shadow: 0 6rpx 12rpx rgba(0, 0, 0, 0.04);
}

.stat-icon-wrapper.online {
  background: linear-gradient(135deg, #E8F5EA, #D6ECD8);
}

.stat-icon-wrapper.offline {
  background: linear-gradient(135deg, #FDEAEA, #FDDCDC);
}

.stat-icon-wrapper.alert {
  background: linear-gradient(135deg, #FFF6E5, #FFEFD0);
}

.stat-icon-img {
  width: 48rpx;
  height: 48rpx;
  display: block;
}

.stat-value {
  font-size: 38rpx;
  color: #333333;
  font-weight: 600;
  margin: 8rpx 0;
  line-height: 1.2;
}

.stat-value.online {
  color: #4CAF50;
}

.stat-value.offline {
  color: #F44336;
}

.stat-value.alert {
  color: #FF9800;
}

.stat-label {
  font-size: 24rpx;
  color: #888888;
  font-weight: 400;
}

/* 设备网格区域 */
.device-grid {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  width: 100%;
}

.device-card {
  width: 48%;
  border-radius: 24rpx;  /* 加大卡片圆角 */
  background-color: #FFFFFF;
  box-shadow: 0 10rpx 30rpx rgba(0, 0, 0, 0.05);  /* 柔和阴影 */
  padding: 30rpx 0 24rpx 0;
  margin-bottom: 30rpx;  /* 增加卡片间距 */
  position: relative;
  display: flex;
  flex-direction: column;
  align-items: center;
  transition: all 0.25s ease;
}

.device-card-hover {
  background-color: #f2fef6;
  box-shadow: 0 12rpx 32rpx rgba(59, 180, 74, 0.1);
  transform: translateY(-3rpx);
}

.device-card.has-alert {
  box-shadow: 0 10rpx 30rpx rgba(245, 108, 108, 0.08);
}

/* 告警角标 */
.alert-badge {
  position: absolute;
  top: 16rpx;  /* 6px */
  right: 16rpx;  /* 6px */
  width: 40rpx;  /* 20px */
  height: 40rpx;  /* 20px */
  border-radius: 50%;
  background-color: #F56C6C;
  color: white;
  font-size: 24rpx;  /* 12px */
  font-weight: 600;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4rpx 8rpx rgba(245, 108, 108, 0.3);
  z-index: 2;
}

/* 设备图标 */
.device-icon-container {
  width: 72rpx;  /* 36px */
  height: 72rpx;  /* 36px */
  border-radius: 50%;
  background: linear-gradient(135deg, #66CC6A 0%, #3BB44A 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 18rpx;
  box-shadow: 0 6rpx 12rpx rgba(59, 180, 74, 0.15);
}

.device-icon {
  width: 40rpx;
  height: 40rpx;
  filter: brightness(0) invert(1);
}

/* 设备名称 */
.device-name {
  font-size: 32rpx;  /* 16px */
  color: #333333;
  font-weight: 600;
  text-align: center;
  margin-bottom: 24rpx;
  padding: 0 20rpx;
}

/* 设备状态信息区域 */
.device-status-container {
  width: 100%;
  display: flex;
  flex-direction: row;
  justify-content: center;
  padding: 16rpx 0;
  border-top: 1rpx solid #EEEEEE;
}

/* 状态信息项 */
.status-info {
  display: flex;
  align-items: center;
  margin: 0 16rpx;
}

/* 状态指示点 */
.status-dot {
  width: 8rpx;
  height: 8rpx;
  border-radius: 50%;
  margin-right: 6rpx;
}

.online-dot {
  background-color: #4CAF50;
}

.offline-dot {
  background-color: #F56C6C;
}

/* 状态文本 */
.status-text {
  font-size: 26rpx;
  color: #999999;
  margin-right: 6rpx;
}

/* 状态数字 */
.status-num {
  font-size: 26rpx;
  font-weight: 600;
}

.online-num {
  color: #4CAF50;
}

.offline-num {
  color: #F56C6C;
}
</style>