<template>
  <div class="agricultural-input-management">
    <!-- 计算页面 -->
    <div v-if="showInputForm" class="page-container">
      <el-card class="gradient-card">
        <div class="calculation-content">
          <h2 class="page-title">农业投入品输入通量计算</h2>
          <div class="scrollable-content">
            <el-form label-position="left">
              <div class="input-section">
                <!-- 第一行：氮肥的两个输入栏 -->
                <div class="input-row">
                  <div class="input-item">
                    <div class="input-title">氮肥镉含量平均值 (mg/kg)</div>
                    <el-input
                      v-model="formData.f3_nitrogen_cd_content"
                      placeholder="0.12"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                  <div class="input-item">
                    <div class="input-title">氮肥单位面积使用量 (t/ha/a)</div>
                    <el-input
                      v-model="formData.nf_nitrogen_usage"
                      placeholder="0.25"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                </div>
                
                <!-- 第二行：磷肥的两个输入栏 -->
                <div class="input-row">
                  <div class="input-item">
                    <div class="input-title">磷肥镉含量平均值 (mg/kg)</div>
                    <el-input
                      v-model="formData.f4_phosphorus_cd_content"
                      placeholder="0.85"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                  <div class="input-item">
                    <div class="input-title">磷肥单位面积使用量 (t/ha/a)</div>
                    <el-input
                      v-model="formData.pf_phosphorus_usage"
                      placeholder="0.15"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                </div>
                
                <!-- 第三行：钾肥的两个输入栏 -->
                <div class="input-row">
                  <div class="input-item">
                    <div class="input-title">钾肥镉含量平均值 (mg/kg)</div>
                    <el-input
                      v-model="formData.f5_potassium_cd_content"
                      placeholder="0.05"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                  <div class="input-item">
                    <div class="input-title">钾肥单位面积使用量 (t/ha/a)</div>
                    <el-input
                      v-model="formData.kf_potassium_usage"
                      placeholder="0.12"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                </div>
                
                <!-- 第四行：复合肥的两个输入栏 -->
                <div class="input-row">
                  <div class="input-item">
                    <div class="input-title">复合肥镉含量平均值 (mg/kg)</div>
                    <el-input
                      v-model="formData.f6_compound_cd_content"
                      placeholder="0.45"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                  <div class="input-item">
                    <div class="input-title">复合肥单位面积使用量 (t/ha/a)</div>
                    <el-input
                      v-model="formData.cf_compound_usage"
                      placeholder="0.30"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                </div>
                
                <!-- 第五行：有机肥的两个输入栏 -->
                <div class="input-row">
                  <div class="input-item">
                    <div class="input-title">有机肥镉含量平均值 (mg/kg)</div>
                    <el-input
                      v-model="formData.f7_organic_cd_content"
                      placeholder="0.22"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                  <div class="input-item">
                    <div class="input-title">有机肥单位面积使用量 (t/ha/a)</div>
                    <el-input
                      v-model="formData.of_organic_usage"
                      placeholder="2.50"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                </div>
                
                <!-- 第六行：农药的两个输入栏 -->
                <div class="input-row">
                  <div class="input-item">
                    <div class="input-title">农药镉含量 (mg/kg)</div>
                    <el-input
                      v-model="formData.f8_pesticide_cd_content"
                      placeholder="0.08"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                  <div class="input-item">
                    <div class="input-title">农药单位面积使用量 (t/ha/a)</div>
                    <el-input
                      v-model="formData.p_pesticide_usage"
                      placeholder="0.02"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                </div>
                
                <!-- 第七行：农家肥的两个输入栏 -->
                <div class="input-row">
                  <div class="input-item">
                    <div class="input-title">农家肥镉含量 (mg/kg)</div>
                    <el-input
                      v-model="formData.f9_farmyard_cd_content"
                      placeholder="0.15"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                  <div class="input-item">
                    <div class="input-title">农家肥单位面积使用量 (t/ha/a)</div>
                    <el-input
                      v-model="formData.ff_farmyard_usage"
                      placeholder="1.80"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                </div>
                
                <!-- 第八行：农膜的两个输入栏 -->
                <div class="input-row">
                  <div class="input-item">
                    <div class="input-title">农膜镉含量 (mg/kg)</div>
                    <el-input
                      v-model="formData.f10_film_cd_content"
                      placeholder="0.03"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                  <div class="input-item">
                    <div class="input-title">农膜单位面积使用量 (t/ha/a)</div>
                    <el-input
                      v-model="formData.af_film_usage"
                      placeholder="0.05"
                      size="large"
                      class="fixed-width-input"
                    />
                  </div>
                </div>
              </div>
            </el-form>
          </div>

          <div class="button-container">
            <el-button
              class="calculate-btn"
              @click="calculateAndVisualize"
              :loading="loading"
              size="large"
            >
              计算农业投入品输入通量
            </el-button>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 结果页面 -->
    <div v-if="!showInputForm" class="page-container">
      <div class="toolbar">
        <el-button class="custom-button back-button" @click="showInputForm = true">
          返回计算
        </el-button>
      </div>
      
      <el-card class="results-card">
        <div class="results-content">
          <!-- 地图区域 -->
          <div class="map-section">
            <h3>农业投入品Cd通量分布图</h3>
            <div v-if="loadingMap" class="loading-container">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <span>地图加载中...</span>
            </div>
            <div class="image-container">
              <img v-if="mapImageUrl" :src=mapImageUrl class="result-image"></img>
              <div v-if="!mapImageUrl && !loadingMap" class="no-data">
                <el-icon><Picture /></el-icon>
                <p>暂无地图数据</p>
              </div>
            </div>
          </div>
          
          <!-- 统计图表区域 -->
          <div class="stats-area">
            <h3>农业投入品Cd通量统计信息</h3>
            <div class="model-info">
              <el-tag type="info">农业投入品Cd通量模型</el-tag>
              <span class="update-time">
                最后更新: {{ updateTime ? new Date(updateTime).toLocaleString() : '未知' }}
              </span>
            </div>
            
            <div v-if="loadingStats" class="loading-container">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <span>统计数据加载中...</span>
            </div>
            
            <div v-if="!loadingStats && customResult.data" class="stats-container">
              <div class="total-flux">
                总通量: {{ customResult.data.total_cd_flux }} g/ha/a
              </div>
              
              <el-table 
                :data="customResultDetails" 
                style="width: 100%; margin-bottom: 15px;"
                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="120" />
              </el-table>
            </div>
            
            <div v-if="!loadingStats && !customResult.data" class="no-data">
              <el-icon><DataAnalysis /></el-icon>
              <p>暂无统计数据</p>
            </div>
          </div>
          
          <!-- 饼图区域 -->
          <div class="chart-section">
            <h3>农业投入品Cd通量占比</h3>
            <div class="image-container">
              <div ref="pieChart" style="width: 100%; height: 350px;"></div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { 
  ElInput, 
  ElButton, 
  ElMessage, 
  ElCard, 
  ElTable, 
  ElTableColumn,
  ElTag,
  ElIcon,
  ElForm
} from 'element-plus';
import { 
  Loading, 
  Picture, 
  DataAnalysis 
} from '@element-plus/icons-vue';
import * as echarts from 'echarts';
import { api8000 } from '@/utils/request';

export default {
  components: {
    ElInput,
    ElButton,
    ElCard,
    ElTable,
    ElTableColumn,
    ElTag,
    ElIcon,
    ElForm,
    Loading,
    Picture,
    DataAnalysis
  },
  setup() {
    // 计算页面数据
    const showInputForm = ref(true);
    const formData = ref({
      f3_nitrogen_cd_content: "0.12",
      f4_phosphorus_cd_content: "0.85",
      f5_potassium_cd_content: "0.05",
      f6_compound_cd_content: "0.45",
      f7_organic_cd_content: "0.22",
      f8_pesticide_cd_content: "0.08",
      f9_farmyard_cd_content: "0.15",
      f10_film_cd_content: "0.03",
      nf_nitrogen_usage: "0.25",
      pf_phosphorus_usage: "0.15",
      kf_potassium_usage: "0.12",
      cf_compound_usage: "0.30",
      of_organic_usage: "2.50",
      p_pesticide_usage: "0.02",
      ff_farmyard_usage: "1.80",
      af_film_usage: "0.05"
    });
    const loading = ref(false);
    
    // 结果页面数据
    const mapImageUrl = ref('');
    const customResult = ref({});
    const updateTime = ref(new Date().toISOString());
    const loadingMap = ref(false);
    const loadingStats = ref(false);
    const pieChart = ref(null);
    
    // 格式化数字显示（保留4位小数）
    const formatNumber = (row, column, cellValue) => {
      if (typeof cellValue === 'number') {
        return cellValue.toFixed(4);
      }
      return cellValue;
    };
    
    // 获取类型名称
    const getTypeName = (type) => {
      const typeNames = {
        'nitrogen_fertilizer': '氮肥',
        'phosphorus_fertilizer': '磷肥',
        'potassium_fertilizer': '钾肥',
        'compound_fertilizer': '复合肥',
        'organic_fertilizer': '有机肥',
        'pesticide': '农药',
        'farmyard_manure': '农家肥',
        'agricultural_film': '农膜'
      };
      return typeNames[type] || type;
    };
    
    // 计算详情数据
    const customResultDetails = ref([]);
    
    // 计算并可视化
    const calculateAndVisualize = async () => {
      try {
        loading.value = true;
        loadingMap.value = true;
        loadingStats.value = true;
        mapImageUrl.value = '';
        
        // 准备请求数据
        const requestBody = {
          ...formData.value,
          // 将字符串值转换为数字
          f3_nitrogen_cd_content: parseFloat(formData.value.f3_nitrogen_cd_content),
          f4_phosphorus_cd_content: parseFloat(formData.value.f4_phosphorus_cd_content),
          f5_potassium_cd_content: parseFloat(formData.value.f5_potassium_cd_content),
          f6_compound_cd_content: parseFloat(formData.value.f6_compound_cd_content),
          f7_organic_cd_content: parseFloat(formData.value.f7_organic_cd_content),
          f8_pesticide_cd_content: parseFloat(formData.value.f8_pesticide_cd_content),
          f9_farmyard_cd_content: parseFloat(formData.value.f9_farmyard_cd_content),
          f10_film_cd_content: parseFloat(formData.value.f10_film_cd_content),
          nf_nitrogen_usage: parseFloat(formData.value.nf_nitrogen_usage),
          pf_phosphorus_usage: parseFloat(formData.value.pf_phosphorus_usage),
          kf_potassium_usage: parseFloat(formData.value.kf_potassium_usage),
          cf_compound_usage: parseFloat(formData.value.cf_compound_usage),
          of_organic_usage: parseFloat(formData.value.of_organic_usage),
          p_pesticide_usage: parseFloat(formData.value.p_pesticide_usage),
          ff_farmyard_usage: parseFloat(formData.value.ff_farmyard_usage),
          af_film_usage: parseFloat(formData.value.af_film_usage)
        };

        // 调用计算并可视化接口
        const [mapResponse, calcResponse] = await Promise.all([
          api8000.post(
            '/api/agricultural-input/calculate-and-visualize-file',
            requestBody,
            {
              params: {
                area: '乐昌市',
                level: 'county',
                colormap: 'green_yellow_red_purple',
                resolution_factor: 4.0,
                enable_interpolation: false,
                cleanup_intermediate: true
              },
              responseType: 'blob'
            }
          ),
          api8000.post(
            '/api/agricultural-input/calculate-with-custom-data',
            requestBody
          )
        ]);
        
        // 处理地图响应
        const blob = new Blob([mapResponse.data], { type: 'image/jpeg' });
        mapImageUrl.value = URL.createObjectURL(blob);
        
        // 处理计算结果
        if (calcResponse.data.success) {
          customResult.value = {
            success: true,
            data: calcResponse.data.data
          };
          
          // 更新详情数据
          customResultDetails.value = Object.entries(customResult.value.data.details).map(([type, flux]) => ({
            type: getTypeName(type),
            flux: flux
          }));
          
          showInputForm.value = false;
          updateTime.value = new Date().toISOString();
          
          // 初始化图表
          initPieChart();
          
          ElMessage.success('计算完成，结果已展示');
        } else {
          throw new Error(calcResponse.data.message);
        }
        
      } catch (error) {
        console.error('API调用错误:', error);
        ElMessage.error('计算失败: ' + (error.message || '请检查网络连接'));
      } finally {
        loading.value = false;
        loadingMap.value = false;
        loadingStats.value = false;
      }
    };
    
    // 初始化饼图
    const initPieChart = () => {
      if (!customResult.value.data || !customResult.value.data.details) return;
      
      nextTick(() => {
        const chartContainer = document.querySelector('.chart-section .image-container');
        if (!chartContainer) {
          console.error('图表容器未找到');
          return;
        }
        
        // 处理图表数据
        const chartData = Object.entries(customResult.value.data.details)
          .filter(([_, value]) => value > 0)
          .map(([type, value]) => ({
            name: getTypeName(type),
            value: parseFloat(value.toFixed(4))
          }));
        
        // 销毁旧图表实例
        if (pieChart.value) {
          pieChart.value.dispose();
        }
        
        // 初始化新图表
        pieChart.value = echarts.init(chartContainer);
        
        // 设置图表选项
        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} g/ha/a ({d}%)'
          },
          legend: {
            orient: 'vertical',
            right: 10,
            top: 'center',
            data: chartData.map(item => item.name)
          },
          series: [
            {
              name: '农业投入品Cd通量占比',
              type: 'pie',
              radius: ['40%', '70%'],
              center: ['40%', '50%'],
              avoidLabelOverlap: false,
              itemStyle: {
                borderRadius: 10,
                borderColor: '#fff',
                borderWidth: 2
              },
              label: {
                show: false,
                position: 'center'
              },
              emphasis: {
                label: {
                  show: true,
                  fontSize: '16',
                  fontWeight: 'bold',
                  formatter: '{b}\n{c} g/ha/a\n({d}%)'
                }
              },
              labelLine: {
                show: false
              },
              data: chartData
            }
          ],
          responsive: true,
          animation: true,
          animationDuration: 1000,
          animationEasing: 'cubicOut'
        };
        
        // 设置图表选项
        pieChart.value.setOption(option);
        
        // 添加窗口大小变化监听
        window.addEventListener('resize', function() {
          pieChart.value.resize();
        });
      });
    };
    
    // 响应式调整
    const handleResize = () => {
      if (pieChart.value) {
        pieChart.value.resize();
      }
    };
    
    onMounted(() => {
      window.addEventListener('resize', handleResize);
    });
    
    onBeforeUnmount(() => {
      window.removeEventListener('resize', handleResize);
      if (pieChart.value) {
        pieChart.value.dispose();
      }
      if (mapImageUrl.value) {
        URL.revokeObjectURL(mapImageUrl.value);
      }
    });
    
    return {
      showInputForm,
      formData,
      loading,
      mapImageUrl,
      customResult,
      updateTime,
      loadingMap,
      loadingStats,
      customResultDetails,
      formatNumber,
      calculateAndVisualize
    };
  }
};
</script>

<style scoped>
/* 整体布局优化 - 紧凑版 */
.agricultural-input-management {
  padding: 15px;
  background: linear-gradient(
    135deg, 
    rgba(230, 247, 255, 0.7) 0%, 
    rgba(240, 248, 255, 0.7) 100%
  );
  box-sizing: border-box;
}

.page-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.gradient-card, .results-card {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 6px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(5px);
  flex: 1;
  display: flex;
  flex-direction: column;
}

/* 计算内容区域 */
.calculation-content {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.page-title {
  text-align: center;
  margin-bottom: 5px;
  color: #333;
  font-size: 20px;
  font-weight: 600;
}

.scrollable-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px;
  margin-bottom: 10px;
}

/* 输入区域样式 - 响应式布局 */
.input-section {
  width: 100%;
  padding: 8px 0;
}

.input-row {
  display: flex;
  flex-wrap: wrap;
  margin-bottom: 12px;
  gap: 12px;
}

.input-item {
  flex: 1;
  display: flex;
  align-items: center;
  min-width: 300px; /* 最小宽度确保在小屏幕上也能正常显示 */
  gap: 12px; /* 增加标题和输入框之间的间距 */
}

.input-title {
  font-size: 16px;
  color: #666;
  text-align: left;
  font-weight: 500;
  width: 220px;
  white-space: nowrap;
  flex-shrink: 0;
  margin-right: 15px; /* 增加标题右侧间距 */
  margin-left: 20px;
  padding: 8px 0; /* 增加标题上下内边距 */
}

/* 固定输入栏宽度 */
.fixed-width-input {
  flex: 1;
  min-width: 150px; /* 确保输入框有最小宽度 */
}

/* 按钮容器 */
.button-container {
  padding: 10px 0;
  display: flex;
  justify-content: center;
  margin-top: auto;
}

.calculate-btn {
  width: 280px;
  background-color: #47C3B9 !important;
  color: white !important;
  font-weight: bold;
  height: 40px;
  border-radius: 6px;
  font-size: 15px;
}

.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, .chart-section {
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 6px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

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

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

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

.total-flux {
  text-align: center;
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
}

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

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

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 250px;
  color: #47C3B9;
}

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

.no-data .el-icon {
  font-size: 40px;
  margin-bottom: 8px;
}

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

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

/* 响应式设计 - 增强版 */
@media (max-width: 1200px) {
  .input-item {
    min-width: 280px;
  }
  
  .input-title {
    margin-right: 12px; /* 中等屏幕调整间距 */
    margin-left: 12px;
  }
}

@media (max-width: 992px) {
  .input-row {
    gap: 10px;
  }
  
  .input-item {
    min-width: 100%;
    flex-direction: row; /* 保持水平布局 */
    align-items: center;
    gap: 10px; /* 调整间距 */
  }
  
  .input-title {
    width: 220px;
    min-width: 220px; /* 固定标题宽度 */
    margin-right: 10px;
    font-size: 15px;
  }
  
  .fixed-width-input {
    width: 100%;
  }
  
  .page-title {
    font-size: 18px;
    margin-bottom: 15px;
  }
}

@media (max-width: 768px) {
  .toolbar {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  
  .input-item {
    gap: 8px;
  }
  
  .input-title {
    width: 180px;
    min-width: 180px;
    font-size: 14px;
    margin-right: 8px;
    margin-left: 8px;
  }
  
  .image-container {
    height: 280px;
  }
  
  :deep(.el-input__inner) {
    height: 34px;
    line-height: 34px;
    font-size: 13px;
  }
}

@media (max-width: 600px) {
  .input-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 6px;
  }
  
  .input-title {
    width: 100%;
    min-width: 100%;
    margin-right: 0;
    text-align: left;
    padding: 4px 0;
  }
  
  .fixed-width-input {
    width: 100%;
    margin-left: 0;
  }
}

@media (max-width: 480px) {
  .agricultural-input-management {
    padding: 10px;
  }
  
  .gradient-card, .results-card {
    padding: 12px;
  }
  
  .page-title {
    font-size: 16px;
    margin-bottom: 12px;
  }
  
  .input-item {
    min-width: 100%;
    gap: 5px;
  }
  
  .input-title {
    font-size: 13px;
    padding: 3px 0;
  }
  
  .calculate-btn {
    width: 100%;
    max-width: 280px;
    height: 38px;
    font-size: 14px;
  }
  
  .image-container {
    height: 220px;
  }
  
  .total-flux {
    font-size: 15px;
  }
  
  .input-row {
    margin-bottom: 10px;
    gap: 8px;
  }
}

/* 工具栏样式 */
.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;
}

/* 特殊小屏幕适配 */
@media (max-width: 360px) {
  .input-title {
    font-size: 12px;
    padding: 2px 0;
  }
  
  .calculate-btn {
    font-size: 13px;
    padding: 0 10px;
  }
  
  .input-item {
    gap: 4px;
  }
}

/* 为输入项添加悬停效果，提升用户体验 */
.input-item:hover .input-title {
  color: #47C3B9;
  transition: color 0.3s ease;
}

.input-item:hover :deep(.el-input__inner) {
  border-color: #47C3B9;
  transition: border-color 0.3s ease;
}
</style>