<template>
  <div class="irrigation-management" style="display: flex; justify-content: center;">
    <!-- 计算页面 -->
    <div v-if="showCalculation" class="page-container">
      <el-card shadow="always" class="gradient-card">
        <!-- 将单选按钮组改为多选框组 -->
        <el-checkbox-group v-model="selectedLandTypes" style="width: 100%;">
          <!-- 水田 -->
          <el-row :gutter="20" style="margin-bottom: 10px; align-items: center;">
            <el-col :span="6">
              <div class="radio-container">
                <el-checkbox label="water" border>水田</el-checkbox>
              </div>
            </el-col>
            <el-col :span="9">
              <div class="input-title">灌溉水用量 (m³/亩/年)</div>
              <el-input
                v-model="irrigationWaterUsage"
                placeholder="请输入灌溉水用量"
                style="margin-top: 10px;"
              />
            </el-col>
            <el-col :span="9">
              <div class='input-title'>灌溉水有效利用率 (%)</div>
              <el-input
                v-model="irrigationEfficiency"
                placeholder="请输入灌溉水有效利用率"
                style="margin-top: 10px;"
              />
            </el-col>
          </el-row>

          <!-- 水浇地 -->
          <el-row :gutter="20" style="margin-bottom: 10px; align-items: center;">
            <el-col :span="6">
              <div class="radio-container">
                <el-checkbox label="irrigated" border>水浇地</el-checkbox>
              </div>
            </el-col>
            <el-col :span="9">
              <div class="input-title">灌溉水用量 (m³/亩/年)</div>
              <el-input
                v-model="irrigatedWaterUsage"
                placeholder="请输入灌溉水用量"
                style="margin-top: 10px;"
              />
            </el-col>
            <el-col :span="9">
              <div class="input-title">灌溉水有效利用率 (%)</div>
              <el-input
                v-model="irrigatedEfficiency"
                placeholder="请输入灌溉水有效利用率"
                style="margin-top: 10px;"
              />
            </el-col>
          </el-row>

          <!-- 旱地 -->
          <el-row :gutter="20" style="margin-bottom: 10px; align-items: center;">
            <el-col :span="6">
              <div class="radio-container">
                <el-checkbox label="dry" border>旱地</el-checkbox>
              </div>
            </el-col>
            <el-col :span="9">
              <div class="input-title">灌溉水用量 (m³/亩/年)</div>
              <el-input
                v-model="dryWaterUsage"
                placeholder="请输入灌溉水用量"
                style="margin-top: 10px;"
              />
            </el-col>
            <el-col :span="9">
              <div class="input-title">灌溉水有效利用率 (%)</div>
              <el-input
                v-model="dryEfficiency"
                placeholder="请输入灌溉水有效利用率"
                style="margin-top: 10px;"
              />
            </el-col>
          </el-row>
        </el-checkbox-group>

        <el-row justify="center" style="margin-top: 20px;">
          <el-button
            class="calculate-btn"
            @click="calculateFlux"
            :loading="loading"
          >
            计算灌溉水输入通量
          </el-button>
        </el-row>
      </el-card>
    </div>

    <!-- 结果页面 -->
    <div v-if="showResults" class="page-container">
      <el-card shadow="always" class="results-card">
        <div class="results-header">
          <el-button 
          type="primary" 
          @click="backToCalculation"
          class="back-button">
            返回计算
          </el-button>
          <div class="result-title">计算结果</div>
        </div>
        
        <div class="results-container">
          <!-- 图像区域（地图和直方图） -->
          <div class="image-row">
            <div class="image-container">
              <div class="result-subtitle">Cd含量地图</div>
              <div class="image-wrapper">
                <img v-if="mapImageUrl" :src="mapImageUrl" alt="Cd含量地图" class="result-image">
                <div v-else class="image-placeholder">地图加载中...</div>
              </div>
            </div>
            
            <div class="image-container">
              <div class="result-subtitle">Cd含量分布直方图</div>
              <div class="image-wrapper">
                <img v-if="histogramImageUrl" :src="histogramImageUrl" alt="Cd含量地图" class="result-image">
                <div v-else class="image-placeholder">直方图加载中...</div>
              </div>
            </div>
          </div>
          
          <!-- 统计结果 -->
          <el-row style="margin-top: 30px;">
            <el-col :span="24">
              <div class="result-subtitle">统计结果</div>
              <div class="statistics-container">
                <!-- 基础统计表格 -->
                <el-table
                  v-if="statisticsData"
                  :data="[statisticsData]"
                  border
                  size="small"
                  style="width: 100%; margin-bottom: 20px;"
                >
                  <el-table-column prop="土地类型" label="土地类型" align="center"></el-table-column>
                  <el-table-column prop="数据更新时间" label="数据更新时间" align="center"></el-table-column>
                  <el-table-column prop="数据点总数" label="数据点总数" align="center"></el-table-column>
                  <el-table-column prop="均值" label="均值" align="center" :formatter="formatNumber"></el-table-column>
                  <el-table-column prop="中位数" label="中位数" align="center" :formatter="formatNumber"></el-table-column>
                  <el-table-column prop="标准差" label="标准差" align="center" :formatter="formatNumber"></el-table-column>
                  <el-table-column prop="最小值" label="最小值" align="center" :formatter="formatNumber"></el-table-column>
                  <el-table-column prop="最大值" label="最大值" align="center" :formatter="formatNumber"></el-table-column>
                </el-table>
                
                <!-- 分位数和形态统计表格 -->
                <el-table
                  v-if="statisticsData"
                  :data="[statisticsData]"
                  border
                  size="small"
                  style="width: 100%; margin-bottom: 20px;"
                >
                  <el-table-column prop="25%分位数" label="25%分位数" align="center" :formatter="formatNumber"></el-table-column>
                  <el-table-column prop="75%分位数" label="75%分位数" align="center" :formatter="formatNumber"></el-table-column>
                  <el-table-column prop="偏度" label="偏度" align="center" :formatter="formatNumber"></el-table-column>
                  <el-table-column prop="峰度" label="峰度" align="center" :formatter="formatNumber"></el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue';
import axios from 'axios';
import { 
  ElCheckbox,
  ElCheckboxGroup,
  ElInput, 
  ElButton, 
  ElMessage, 
  ElCard, 
  ElRow, 
  ElCol, 
  ElTable, 
  ElTableColumn 
} from 'element-plus';

// 土地类型映射
const landTypeMap = {
  water: '水田',
  irrigated: '水浇地',
  dry: '旱地'
};

export default {
  components: {
    ElCheckbox,
    ElCheckboxGroup,
    ElInput,
    ElButton,
    ElMessage,
    ElCard,
    ElRow,
    ElCol,
    ElTable,
    ElTableColumn
  },
  setup() {
    // 将单选改为多选，初始值为空数组
    const selectedLandTypes = ref([]);
    
    // 设置默认值
    const irrigationWaterUsage = ref('711');
    const irrigationEfficiency = ref('0.524');

    const irrigatedWaterUsage = ref('427');
    const irrigatedEfficiency = ref('0.599');

    const dryWaterUsage = ref('200');
    const dryEfficiency = ref('0.7');

    const fluxResult = ref(null);
    const showCalculation = ref(true); // 显示计算页面
    const showResults = ref(false); // 显示结果页面
    const loading = ref(false);
    
    // 结果展示数据
    const mapImageUrl = ref('');
    const histogramImageUrl = ref('');
    const statisticsData = ref(null);

    // 格式化数字显示（保留4位小数）
    const formatNumber = (row, column, cellValue) => {
      if (typeof cellValue === 'number') {
        return cellValue.toFixed(4);
      }
      return cellValue;
    };

    // 获取默认地图
    const fetchDefaultMap = async (landTypeChinese) => {
      try {
        const response = await axios.get('http://localhost:8000/api/water/default-map', {
          params: { land_type: landTypeChinese },
          responseType: 'blob' // 接收二进制数据
        });
        
        // 创建对象URL
        return URL.createObjectURL(response.data);
      } catch (error) {
        console.error('获取默认地图失败:', error);
        ElMessage.error('获取地图失败，请重试');
        return '';
      }
    };

    // 获取默认直方图
    const fetchDefaultHistogram = async (landTypeChinese) => {
      try {
        const response = await axios.get('http://localhost:8000/api/water/default-histogram', {
          params: { land_type: landTypeChinese },
          responseType: 'blob' // 接收二进制数据
        });
        
        // 创建对象URL
        return URL.createObjectURL(response.data);
      } catch (error) {
        console.error('获取默认直方图失败:', error);
        ElMessage.error('获取直方图失败，请重试');
        return '';
      }
    };

    // 获取统计数据
    const fetchStatistics = async (landTypeChinese) => {
      try {
        const response = await axios.get('http://localhost:8000/api/water/statistics', {
          params: { land_type: landTypeChinese }
        });
        return response.data;
      } catch (error) {
        console.error('获取统计数据失败:', error);
        ElMessage.error('获取统计数据失败，请重试');
        return null;
      }
    };

    // 返回计算页面
    const backToCalculation = () => {
      showCalculation.value = true;
      showResults.value = false;
    };

    const calculateFlux = async () => {
      // 检查是否选择了土地类型
      if (selectedLandTypes.value.length === 0) {
        ElMessage.warning('请至少选择一种土地类型');
        return;
      }

      // 收集所有土地类型的通量计算结果
      const landFluxResults = [];
      let inputValid = true;  // 修复：在循环外部定义验证变量
      
      // 遍历所有选中的土地类型
      for (const landType of selectedLandTypes.value) {
        let flux = 0;
        let usage, efficiency;

        // 根据土地类型获取对应的输入值
        if (landType === 'water') {
          usage = irrigationWaterUsage.value;
          efficiency = irrigationEfficiency.value;
        } else if (landType === 'irrigated') {
          usage = irrigatedWaterUsage.value;
          efficiency = irrigatedEfficiency.value;
        } else if (landType === 'dry') {
          usage = dryWaterUsage.value;
          efficiency = dryEfficiency.value;
        }

        // 验证输入有效性
        if (!usage || !efficiency) {
          ElMessage.warning(`请输入${landTypeMap[landType]}的灌溉水用量和有效利用率`);
          inputValid = false;
          break;
        }

        const usageValue = parseFloat(usage);
        const efficiencyValue = parseFloat(efficiency) / 100;

        if (isNaN(usageValue) || isNaN(efficiencyValue)) {
          ElMessage.error(`请输入${landTypeMap[landType]}的有效数字`);
          inputValid = false;
          break;
        } else if (efficiencyValue > 1 || efficiencyValue < 0) {
          ElMessage.error(`${landTypeMap[landType]}的有效利用率应在0-100%之间`);
          inputValid = false;
          break;
        }

        // 计算通量
        flux = usageValue * efficiencyValue;
        landFluxResults.push({
          landType: landTypeMap[landType],
          flux,
          efficiency: efficiencyValue
        });
      }

      if (!inputValid) return;  // 使用在外部定义的验证变量

      loading.value = true;
      
      try {
        // 准备调用后端接口的数据
        const formData = new FormData();
        
        // 构建土地类型列表（中文名称）
        const landTypesChinese = selectedLandTypes.value.map(type => landTypeMap[type]);
        
        // 重要修改：将 land_types 作为数组传递（JSON字符串）
        landTypesChinese.forEach(landType => formData.append('land_types', landType));

        
        // 构建系数参数对象（每个土地类型对应的系数）
        const coefficientParams = {};
        landFluxResults.forEach(result => {
          coefficientParams[result.landType] = [result.flux, result.efficiency];
        });
        formData.append('coefficient_params', JSON.stringify(coefficientParams));
        
        // 其他固定参数
        formData.append('color_map_name', "绿-黄-红-紫");
        formData.append('output_size', 8);

        // 调用计算接口
        await axios.post('http://localhost:8000/api/water/calculate', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        });
        
        // 获取并显示结果
        // 使用下划线连接的土地类型名称作为参数获取结果
        const landTypeParam = landTypesChinese.join('_');
        
        // 获取默认地图
        mapImageUrl.value = await fetchDefaultMap(landTypeParam);
        
        // 获取默认直方图
        histogramImageUrl.value = await fetchDefaultHistogram(landTypeParam);
        
        // 获取统计数据
        statisticsData.value = await fetchStatistics(landTypeParam);
        
        // 切换到结果页面
        showCalculation.value = false;
        showResults.value = true;
        
        ElMessage.success('计算完成，结果已展示');
      } catch (error) {
        console.error('获取结果失败:', error);
        ElMessage.error('获取结果失败，请重试');
      } finally {
        loading.value = false;
      }
    };

    return {
      selectedLandTypes,
      irrigationWaterUsage,
      irrigationEfficiency,
      irrigatedWaterUsage,
      irrigatedEfficiency,
      dryWaterUsage,
      dryEfficiency,
      calculateFlux,
      fluxResult,
      showCalculation,
      showResults,
      loading,
      mapImageUrl,
      histogramImageUrl,
      statisticsData,
      formatNumber,
      backToCalculation
    };
  }
};
</script>

<style scoped>
/* 保持原有样式不变，添加地图和直方图并列样式 */
.gradient-card {
  background: linear-gradient(
    135deg, 
    rgba(250, 253, 255, 0.8), 
    rgba(137, 223, 252, 0.8)
  );
  width: 80%;
  max-width: 800px;
  padding: 25px;
  border-radius: 12px;
}

.results-card {
  background: linear-gradient(
    135deg, 
    rgba(250, 253, 255, 0.8), 
    rgba(137, 223, 252, 0.8)
  );
  width: 90%;
  max-width: 1200px;
  padding: 30px;
  border-radius: 12px;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.result-title {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  flex-grow: 1;
}

.input-title {
  font-size: 14px;
  font-weight: 500;
  color: #606266;
  margin-bottom: 5px;
  text-align: left;
}

.radio-container {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: 100%;
}

.calculate-btn {
  width: 100%;
  max-width: 300px;
  height: 42px;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  background: linear-gradient(45deg, #1a8cff, #00cc99);
  color: white;
}

.results-container {
  margin-top: 20px;
}

.result-subtitle {
  text-align: center;
  font-weight: bold;
  font-size: 20px;
  margin-bottom: 15px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}

/* 新增：地图和直方图并列样式 */
.image-row {
  display: flex;
  gap: 20px;
  margin-top: 30px;
}

.image-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.image-wrapper {
  flex: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  overflow: hidden;
  background-color: #f8f8f8;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  height: 400px; /* 固定高度 */
}

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

.image-placeholder {
  height: 100%;
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #909399;
  font-style: italic;
  font-size: 18px;
}

.statistics-container {
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 12px;
  padding: 25px;
}

/* 表格样式增强 */
:deep(.el-table) {
  margin-bottom: 25px;
  border-radius: 10px;
  overflow: hidden;
}

:deep(.el-table__header) {
  background-color: #f0f8ff;
}

:deep(.el-table th) {
  background-color: #f0f8ff;
  font-weight: bold;
}

/* 返回按钮样式 */
.back-button {
  position: absolute;
  top: 20px;
  left: 20px;
  width: 120px;
  padding: 10px;
  background: linear-gradient(to right, #8DF9F0, #26B046);
  color: white;
  border-radius: 20px;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .image-row {
    flex-direction: column;
  }
  
  .image-container {
    width: 100%;
  }
}
</style>