<template>
  <div class="agricultural-input-management">
    <!-- 直接展示结果页面 -->
    <div class="page-container">
      <el-card class="results-card">
        <div class="results-content">
          <!-- 地图区域 -->
          <div class="map-section">
            <h3>籽粒移除Cd通量分布图</h3>
            <div v-if="loading" class="loading-container">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <span>数据加载中...</span>
            </div>
            <div v-else-if="error" class="error-container">
              <el-icon class="error-icon"><Warning /></el-icon>
              <span>{{ error }}</span>
            </div>
            <div v-else class="image-container">
              <img :src="visualizationImage" class="result-image"></img>
            </div>
          </div>
          
          <!-- 统计图表区域 -->
          <div class="stats-area">
            <h3>籽粒移除Cd通量统计信息</h3>
            <div class="model-info">
              <el-tag type="info">籽粒移除Cd通量模型</el-tag>
              <span class="update-time">
                最后更新: {{ reportTime }}
              </span>
            </div>
            
            <div v-if="loading" class="loading-container">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <span>统计数据加载中...</span>
            </div>
            
            <div v-else-if="error" class="error-container">
              <el-icon class="error-icon"><Warning /></el-icon>
              <span>{{ error }}</span>
            </div>
            
            <div v-else class="stats-container">
              <div class="stats-grid">
                <div class="stat-card">
                  <div class="stat-value">{{ statistics.total_samples.toLocaleString() }}</div>
                  <div class="stat-label">总样本数</div>
                </div>
                <div class="stat-card">
                  <div class="stat-value">{{ statistics.mean_flux.toFixed(4) }}</div>
                  <div class="stat-label">平均通量</div>
                </div>
                <div class="stat-card">
                  <div class="stat-value">{{ statistics.max_flux.toFixed(4) }}</div>
                  <div class="stat-label">最大通量</div>
                </div>
                <div class="stat-card">
                  <div class="stat-value">{{ statistics.min_flux.toFixed(4) }}</div>
                  <div class="stat-label">最小通量</div>
                </div>
              </div>
              
              <div v-if="resultDetails.length > 0" class="details-table">
                <el-table 
                  :data="resultDetails" 
                  style="width: 100%; margin-top: 20px;"
                  border
                  stripe
                >
                  <el-table-column prop="type" label="区域类型" align="center" min-width="120" />
                  <el-table-column prop="flux" label="Cd通量(g/ha/a)" align="center" :formatter="formatNumber" min-width="150" />
                </el-table>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { 
  ElButton, 
  ElCard, 
  ElTable, 
  ElTableColumn,
  ElTag,
  ElIcon
} from 'element-plus';
import { 
  Loading, 
  Picture, 
  Warning 
} from '@element-plus/icons-vue';
import { api8000 } from '@/utils/request';

export default {
  components: {
    ElButton,
    ElCard,
    ElTable,
    ElTableColumn,
    ElTag,
    ElIcon,
    Loading,
    Picture,
    Warning
  },
  props: {
    area: {
      type: String,
      default: '乐昌市'
    }
  },
  setup(props) {
    // 响应式数据
    const results = ref([]);
    const statistics = ref({
      total_samples: 0,
      mean_flux: 0,
      max_flux: 0,
      min_flux: 0
    });
    const visualizationImage = ref("");
    const reportTime = ref("");
    const loading = ref(true);
    const error = ref(null);
    
    // 格式化数字显示（保留4位小数）
    const formatNumber = (row, column, cellValue) => {
      if (typeof cellValue === 'number') {
        return cellValue.toFixed(4);
      }
      return cellValue;
    };
    
    // 计算详情数据
    const resultDetails = ref([]);
    
    // 从API获取数据
    const fetchData = async () => {
      try {
        loading.value = true;
        error.value = null;
        
        // 获取计算结果数据
        const dataResponse = await api8000.get(
          `/api/cd-flux-removal/grain-removal?area=${encodeURIComponent(props.area)}`
        );
        
        if (!dataResponse.data.success) {
          throw new Error(`API错误: ${dataResponse.data.message}`);
        }
        
        // 设置数据
        results.value = dataResponse.data.data.results;
        statistics.value = dataResponse.data.data.statistics;
        
        // 更新详情数据
        if (dataResponse.data.data.details) {
          resultDetails.value = Object.entries(dataResponse.data.data.details).map(([type, flux]) => ({
            type: getTypeName(type),
            flux: flux
          }));
        }
        
        // 获取可视化图片
        try {
          const imageResponse = await api8000.get(
            `/api/cd-flux-removal/grain-removal/latest-map/${encodeURIComponent(props.area)}`,
            { responseType: 'blob' }
          );
          
          // 创建图片Blob URL
          const blob = new Blob([imageResponse.data], { type: imageResponse.headers['content-type'] });
          visualizationImage.value = URL.createObjectURL(blob);
        } catch (imgErr) {
          console.error('图片加载错误:', imgErr);
        }
        
        // 设置报告时间
        reportTime.value = new Date().toLocaleString('zh-CN', {
          year: 'numeric',
          month: 'long',
          day: 'numeric',
          hour: '2-digit',
          minute: '2-digit'
        });
        
      } catch (err) {
        console.error('数据获取错误:', err);
        error.value = err.message || '获取数据时发生错误';
      } finally {
        loading.value = false;
      }
    };
    
    // 组件挂载时获取数据
    onMounted(() => {
      fetchData();
    });
    
    onBeforeUnmount(() => {
      if (visualizationImage.value) {
        URL.revokeObjectURL(visualizationImage.value);
      }
    });
    
    return {
      results,
      statistics,
      visualizationImage,
      reportTime,
      loading,
      error,
      resultDetails,
      formatNumber
    };
  }
};
</script>

<style scoped>
/* 整体布局优化 - 与农业投入品保持一致 */
.agricultural-input-management {
  padding: 20px;
  background: linear-gradient(
    135deg, 
    rgba(230, 247, 255, 0.7) 0%, 
    rgba(240, 248, 255, 0.7) 100%
  );
  min-height: 100vh;
  box-sizing: border-box;
}

.page-container {
  width: 100%;
  height: 100%;
}

/* 工具栏样式 */
.toolbar {
  display: flex;
  justify-content: flex-start;
  gap: 15px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(5px);
}

.custom-button {
  background-color: #47C3B9 !important;
  color: #DCFFFA !important;
  border: none;
  border-radius: 155px;
  padding: 10px 20px;
  font-weight: bold;
  display: flex;
  align-items: center;
}

/* 结果卡片样式 */
.results-card {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(5px);
  height: 100%;
  box-sizing: border-box;
}

.results-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.map-section, .stats-area {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

h3 {
  margin-bottom: 15px;
  color: #333;
  font-size: 18px;
  font-weight: 600;
}

.model-info {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 15px;
}

.update-time {
  color: #666;
  font-size: 14px;
}

/* 统计卡片样式 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  background: rgba(178, 235, 242, 0.3);
  border-radius: 15px;
  padding: 20px;
  text-align: center;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
  background: rgba(178, 235, 242, 0.5);
}

.stat-value {
  font-size: 1.8rem;
  font-weight: 700;
  color: #006064;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 1.1rem;
  color: #00838f;
}

/* 图片容器限定大小 */
.image-container {
  width: 100%;
  height: 500px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f9f9f9;
  border-radius: 8px;
  overflow: hidden;
}

.result-image {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
}

.loading-container, .error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  gap: 15px;
}

.loading-container {
  color: #47C3B9;
}

.error-container {
  color: #F56C6C;
}

.loading-icon {
  font-size: 36px;
  margin-bottom: 10px;
  animation: rotate 2s linear infinite;
}

.error-icon {
  font-size: 36px;
  margin-bottom: 10px;
}

.no-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  color: #999;
  font-size: 16px;
}

.no-data .el-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.details-table {
  margin-top: 20px;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  }
  
  .image-container {
    height: 300px;
  }
}

@media (max-width: 480px) {
  .agricultural-input-management {
    padding: 10px;
  }
  
  .results-card {
    padding: 15px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .stat-card {
    padding: 15px;
  }
  
  .image-container {
    height: 250px;
  }
  
  .stat-value {
    font-size: 1.5rem;
  }
}
</style>