<template>
  <div class="irrigation-management">
    <!-- 计算页面 -->
    <div v-if="showCalculation">
      <el-card shadow="always" class="gradient-card">
        <el-radio-group v-model="selectedLandType" style="width: 100%;">
          <!-- 水地 -->
          <el-row :gutter="20" style="margin-bottom: 10px; align-items: center;">
            <el-col :span="6">
              <div class="radio-container">
                <el-radio label="water" border>水田</el-radio>
              </div>
            </el-col>
            <el-col :span="9">
              <div class="input-title">灌溉水用量 (m³/亩/年)</div>
              <el-input
                v-model="irrigationWaterUsage"
                placeholder="请输入灌溉水用量"
                :disabled="selectedLandType !== 'water'"
                style="margin-top: 10px;"
              />
            </el-col>
            <el-col :span="9">
              <div class="input-title">灌溉水有效利用率 (%)</div>
              <el-input
                v-model="irrigationEfficiency"
                placeholder="请输入灌溉水有效利用率"
                :disabled="selectedLandType !== 'water'"
                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-radio label="irrigated" border>水浇地</el-radio>
              </div>
            </el-col>
            <el-col :span="9">
              <div class="input-title">灌溉水用量 (m³/亩/年)</div>
              <el-input
                v-model="irrigatedWaterUsage"
                placeholder="请输入灌溉水用量"
                :disabled="selectedLandType !== 'irrigated'"
                style="margin-top: 10px;"
              />
            </el-col>
            <el-col :span="9">
              <div class="input-title">灌溉水有效利用率 (%)</div>
              <el-input
                v-model="irrigatedEfficiency"
                placeholder="请输入灌溉水有效利用率"
                :disabled="selectedLandType !== 'irrigated'"
                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-radio label="dry" border>旱地</el-radio>
              </div>
            </el-col>
            <el-col :span="9">
              <div class="input-title">灌溉水用量 (m³/亩/年)</div>
              <el-input
                v-model="dryWaterUsage"
                placeholder="请输入灌溉水用量"
                :disabled="selectedLandType !== 'dry'"
                style="margin-top: 10px;"
              />
            </el-col>
            <el-col :span="9">
              <div class="input-title">灌溉水有效利用率 (%)</div>
              <el-input
                v-model="dryEfficiency"
                placeholder="请输入灌溉水有效利用率"
                :disabled="selectedLandType !== 'dry'"
                style="margin-top: 10px;"
              />
            </el-col>
          </el-row>
        </el-radio-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">
      <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">
          <el-row :gutter="20" style="margin-top: 30px;">
            <el-col :span="12">
              <div class="result-subtitle">Cd含量地图</div>
              <img v-if="mapImageUrl" :src="mapImageUrl" alt="Cd含量地图" class="result-image">
              <div v-else class="image-placeholder">地图加载中...</div>
            </el-col>
            <el-col :span="12">
              <div class="result-subtitle">Cd含量直方图</div>
              <img v-if="histogramImageUrl" :src="histogramImageUrl" alt="Cd含量直方图" class="result-image">
              <div v-else class="image-placeholder">直方图加载中...</div>
            </el-col>
          </el-row>
          
          <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 { 
  ElRadio, 
  ElRadioGroup, 
  ElInput, 
  ElButton, 
  ElMessage, 
  ElCard, 
  ElRow, 
  ElCol, 
  ElTable, 
  ElTableColumn 
} from 'element-plus';

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

export default {
  components: {
    ElRadio,
    ElRadioGroup,
    ElInput,
    ElButton,
    ElMessage,
    ElCard,
    ElRow,
    ElCol,
    ElTable,
    ElTableColumn
  },
  setup() {
    const selectedLandType = ref('water'); // 默认选择水田
    
    // 设置默认值
    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 () => {
      let totalFlux = 0;
      let valid = true;
      let currentLandType = '';

      if (selectedLandType.value === 'water') {
        if (!irrigationWaterUsage.value || !irrigationEfficiency.value) {
          ElMessage.warning('请输入水地的灌溉水用量和有效利用率');
          valid = false;
        } else {
          const usage = parseFloat(irrigationWaterUsage.value);
          const efficiency = parseFloat(irrigationEfficiency.value) / 100;

          if (isNaN(usage) || isNaN(efficiency)) {
            ElMessage.error('请输入有效的数字');
            valid = false;
          } else if (efficiency > 1 || efficiency < 0) {
            ElMessage.error('有效利用率应在0-100%之间');
            valid = false;
          } else {
            totalFlux = usage * efficiency;
            currentLandType = 'water';
          }
        }
      } 
      else if (selectedLandType.value === 'irrigated') {
        if (!irrigatedWaterUsage.value || !irrigatedEfficiency.value) {
          ElMessage.warning('请输入水浇地的灌溉水用量和有效利用率');
          valid = false;
        } else {
          const usage = parseFloat(irrigatedWaterUsage.value);
          const efficiency = parseFloat(irrigatedEfficiency.value) / 100;

          if (isNaN(usage) || isNaN(efficiency)) {
            ElMessage.error('请输入有效的数字');
            valid = false;
          } else if (efficiency > 1 || efficiency < 0) {
            ElMessage.error('有效利用率应在0-100%之间');
            valid = false;
          } else {
            totalFlux = usage * efficiency;
            currentLandType = 'irrigated';
          }
        }
      } 
      else if (selectedLandType.value === 'dry') {
        if (!dryWaterUsage.value || !dryEfficiency.value) {
          ElMessage.warning('请输入旱地的灌溉水用量和有效利用率');
          valid = false;
        } else {
          const usage = parseFloat(dryWaterUsage.value);
          const efficiency = parseFloat(dryEfficiency.value) / 100;

          if (isNaN(usage) || isNaN(efficiency)) {
            ElMessage.error('请输入有效的数字');
            valid = false;
          } else if (efficiency > 1 || efficiency < 0) {
            ElMessage.error('有效利用率应在0-100%之间');
            valid = false;
          } else {
            totalFlux = usage * efficiency;
            currentLandType = 'dry';
          }
        }
      } 
      else {
        ElMessage.warning('请选择一种土地类型');
        valid = false;
      }

      if (valid) {
        loading.value = true;
        fluxResult.value = totalFlux;
        
        try {
          // 获取土地类型中文名称
          const landTypeChinese = landTypeMap[currentLandType];
          
          // 第一步：调用calculate接口进行计算
          const formData = new FormData();
          formData.append('land_type', landTypeChinese);
          formData.append('param1', totalFlux);
          formData.append('param2', parseFloat(irrigationEfficiency.value || irrigatedEfficiency.value || dryEfficiency.value));
          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'
            }
          });
          
          // 第二步：获取默认地图
          mapImageUrl.value = await fetchDefaultMap(landTypeChinese);
          
          // 第三步：获取默认直方图
          histogramImageUrl.value = await fetchDefaultHistogram(landTypeChinese);
          
          // 第四步：获取统计数据
          statisticsData.value = await fetchStatistics(landTypeChinese);
          
          // 切换到结果页面
          showCalculation.value = false;
          showResults.value = true;
          
          ElMessage.success('计算完成，结果已展示');
        } catch (error) {
          console.error('获取结果失败:', error);
          ElMessage.error('获取结果失败，请重试');
        } finally {
          loading.value = false;
        }
      }
    };

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

<style scoped>
.compact-container {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.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;
  box-sizing: border-box;
  border-radius: 12px;
  border: none;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(5px); /* 添加模糊效果增强半透明感 */
}

.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;
  box-sizing: border-box;
  border-radius: 12px;
  border: none;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #e4e7ed;
}

.result-title {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  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%;
}

.compact-title-section {
  text-align: center;
  margin-bottom: 20px;
}

.compact-main-title {
  font-size: 1.5rem;
  color: #1a3c7a;
  margin-bottom: 8px;
  font-weight: 600;
}

.compact-sub-title {
  font-size: 0.9rem;
  color: #555;
  margin-bottom: 10px;
}

.compact-input-section {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.compact-land-section {
  display: flex;
  align-items: center;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 10px;
  padding: 12px 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
}

.compact-land-section:hover {
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.compact-land-checkbox {
  width: 80px;
}

.compact-land-label {
  font-weight: 600;
  font-size: 1rem;
  color: #1a3c7a;
}

.compact-input-group {
  flex: 1;
  margin: 0 8px;
}

.compact-input-label {
  font-size: 0.85rem;
  font-weight: 500;
  margin-bottom: 6px;
  color: #2c3e50;
}

:deep(.compact-input .el-input__inner) {
  height: 36px;
  font-size: 0.9rem;
  border-radius: 8px;
  padding: 0 12px;
  border: 1px solid #dcdfe6;
}

:deep(.compact-input .el-input__inner:focus) {
  border-color: #409EFF;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

:deep(.el-radio) {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  text-align: left;
}

:deep(.el-radio__label) {
  text-align: left;
}

.calculate-btn {
  width: 100%;
  max-width: 300px;
  height: 42px;
  border: none;
  border-radius: 8px;
  font-size: 1rem;
  font-weight: 600;
  transition: all 0.3s ease;
  background: linear-gradient(45deg, #1a8cff, #00cc99);
  color: white;
  box-shadow: 0 4px 10px rgba(26, 140, 255, 0.3);
}

.compact-calculate-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 12px rgba(26, 140, 255, 0.4);
  background: linear-gradient(45deg, #0d7de0, #00b386);
}

.compact-calculate-btn:active {
  transform: translateY(1px);
}

.compact-result-section {
  text-align: center;
  margin-top: 15px;
  padding: 15px;
  border-radius: 10px;
  background: rgba(255, 255, 255, 0.95);
  box-shadow: 0 3px 8px rgba(0, 0, 0, 0.08);
  border: 1px solid #e0f7fa;
}

.compact-result-title {
  font-size: 1.1rem;
  color: #1a3c7a;
  margin-bottom: 10px;
  font-weight: 600;
}

.compact-flux-value {
  font-size: 1.8rem;
  font-weight: 700;
  color: #e91e63;
  margin: 5px 0;
}

.compact-unit {
  font-size: 1.2rem;
  color: #555;
  font-weight: 600;
}

.compact-result-description {
  font-size: 0.9rem;
  color: #555;
  margin-top: 5px;
}

/* 结果区域样式 */
.results-container {
  margin-top: 20px;
}

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

.result-image {
  width: 100%;
  max-height: 400px;
  object-fit: contain;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  background-color: #f8f8f8;
}

.image-placeholder {
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #dcdfe6;
  border-radius: 8px;
  background-color: #f5f7fa;
  color: #909399;
  font-style: italic;
  font-size: 18px;
}

.statistics-container {
  background-color: rgba(255, 255, 255, 0.7);
  border-radius: 12px;
  padding: 25px;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
  margin-top: 20px;
}

/* 表格样式增强 */
:deep(.el-table) {
  margin-bottom: 25px;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

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

:deep(.el-table th) {
  background-color: #f0f8ff;
  font-weight: bold;
  color: #2c3e50;
  font-size: 16px;
}

:deep(.el-table td) {
  font-size: 15px;
}

/* 返回按钮样式 */
.back-button {
  position: absolute;
  top: 20px;
  left: 20px; /* 从right改为left */
  width: 120px;
  font-size: 16px;
  padding: 10px;
  background: linear-gradient(to right, #8DF9F0, #26B046);
  color: white;
  border: none;
  border-radius: 20px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
  z-index: 10; /* 确保按钮在顶层 */
}

.back-button:hover {
  background: linear-gradient(to right, #7de8df, #20a03d);
}
</style>