<template>
  <div class="container">
    <!-- 顶部操作栏 -->
    <div class="toolbar">
      <!-- 文件上传区域 -->
      <div class="upload-section">
        <input type="file" ref="fileInput" accept=".csv" @change="handleFileUpload" style="display: none">
        <el-button class="custom-button" @click="triggerFileUpload">
          <el-icon class="upload-icon"><Upload /></el-icon>
          选择CSV文件
        </el-button>
        <span v-if="selectedFile" class="file-name">{{ selectedFile.name }}</span>
        <el-button 
          class="custom-button" 
          :loading="isCalculating" 
          :disabled="!selectedFile" 
          @click="calculate"
        >
        <el-icon class="upload-icon"><Document /></el-icon>  
        上传并计算
        </el-button>
        <!-- 添加从数据库计算按钮 -->
        <el-button 
          class="custom-button" 
          :loading="isCalculatingFromDB" 
          @click="calculateFromDatabase"
        >
        <el-icon class="upload-icon"><Box /></el-icon>  
        从数据库计算
        </el-button>
      </div>
      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button class="custom-button" :disabled="!mapBlob" @click="exportMap">
          <el-icon class="upload-icon"><Download /></el-icon>
          导出地图</el-button>
        <el-button class="custom-button" :disabled="!histogramBlob" @click="exportHistogram">
          <el-icon class="upload-icon"><Download /></el-icon>
          导出直方图</el-button>
      </div>
    </div>

    <!-- 主体内容区 -->
    <div class="content-area">
      <!-- 地图区域 - 单独一行 -->
      <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>
        <img v-if="mapImageUrl && !loadingMap" :src="mapImageUrl" alt="有效态Cd预测地图" class="map-image">
        <div v-if="!mapImageUrl && !loadingMap" class="no-data">
          <el-icon><Picture /></el-icon>
          <p>暂无地图数据</p>
        </div>
      </div>
      
      <!-- 直方图区域 - 单独一行，放在统计信息下面 -->
      <div class="histogram-section">
        <h3>有效态Cd预测直方图</h3>
        <div v-if="loadingHistogram" class="loading-container">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span>直方图加载中...</span>
        </div>
        <img v-if="histogramImageUrl && !loadingHistogram" :src="histogramImageUrl" alt="有效态Cd预测直方图" class="histogram-image">
        <div v-if="!histogramImageUrl && !loadingHistogram" class="no-data">
          <el-icon><Histogram /></el-icon>
          <p>暂无直方图数据</p>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';
import { api8000 } from '@/utils/request';
import * as echarts from 'echarts';
import { 
  Loading, Upload, Picture, Histogram, Download, Document, Box 
} from '@element-plus/icons-vue';

export default {
  name: 'EffectiveCadmiumPrediction',
  components: { 
    Loading, Upload, Picture, Histogram, Download, Document, Box 
  },
  data() {
    return {
      isCalculating: false,
      isCalculatingFromDB: false,
      loadingMap: false,
      loadingHistogram: false,
      mapImageUrl: null,
      histogramImageUrl: null,
      mapBlob: null,
      histogramBlob: null,
      selectedFile: null,
      countyName: '乐昌市' // 默认县市名称
    };
  },

  mounted() {
    // 组件挂载时获取最新数据
    this.fetchLatestResults();
  },

  beforeDestroy() {
    if (this.mapImageUrl) URL.revokeObjectURL(this.mapImageUrl);
    if (this.histogramImageUrl) URL.revokeObjectURL(this.histogramImageUrl);
  },
  methods: {
    // 触发文件选择
    triggerFileUpload() {
      this.$refs.fileInput.click();
    },
    
    // 处理文件上传
    handleFileUpload(event) {
      const files = event.target.files;
      if (files && files.length > 0) {
        this.selectedFile = files[0];
      } else {
        this.selectedFile = null;
      }
    },
    
    // 获取最新结果
    async fetchLatestResults() {
      try {
        this.loadingMap = true;
        this.loadingHistogram = true;
        
        // 获取最新地图
        await this.fetchLatestMap();
        
        // 获取最新直方图
        await this.fetchLatestHistogram();
        
      } catch (error) {
        console.error('获取最新结果失败:', error);
        this.$message.error('获取最新结果失败');
      } finally {
        this.loadingMap = false;
        this.loadingHistogram = false;
      }
    },
    
    // 获取最新地图
    async fetchLatestMap() {
      try {
        const response = await api8000.get(
          `/api/cd-prediction/effective-cd/latest-map/${this.countyName}`,
          { responseType: 'blob' }
        );
        
        this.mapBlob = response.data;
        this.mapImageUrl = URL.createObjectURL(this.mapBlob);
      } catch (error) {
        console.error('获取最新地图失败:', error);
        this.$message.warning('获取最新地图失败，请先执行预测');
      }
    },
    
    // 获取最新直方图
    async fetchLatestHistogram() {
      try {
        const response = await api8000.get(
          `/api/cd-prediction/effective-cd/latest-histogram/${this.countyName}`,
          { responseType: 'blob' }
        );
        
        this.histogramBlob = response.data;
        this.histogramImageUrl = URL.createObjectURL(this.histogramBlob);
      } catch (error) {
        console.error('获取最新直方图失败:', error);
        this.$message.warning('获取最新直方图失败，请先执行预测');
      }
    },
    
    // 上传并计算
    async calculate() {
      if (!this.selectedFile) {
        this.$message.warning('请先选择CSV文件');
        return;
      }
      
      try {
        this.isCalculating = true;
        this.loadingMap = true;
        this.loadingHistogram = true;
        
        // 创建FormData
        const formData = new FormData();
        formData.append('area', this.countyName);
        formData.append('data_file', this.selectedFile);
        formData.append('use_database', 'false'); // 使用上传的文件
        
        // 调用有效Cd地图接口
        const mapResponse = await api8000.post(
          '/api/cd-prediction/effective-cd/generate-and-get-map',
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            },
            responseType: 'blob'
          }
        );
        
        // 保存地图数据
        this.mapBlob = mapResponse.data;
        this.mapImageUrl = URL.createObjectURL(this.mapBlob);
        
        // 更新后重新获取直方图
        await this.fetchLatestHistogram();
        
        this.$message.success('计算完成！');
        
      } catch (error) {
        console.error('计算失败:', error);
        let errorMessage = '计算失败，请重试';
        
        if (error.response) {
          if (error.response.status === 400) {
            errorMessage = '文件格式错误：' + (error.response.data.detail || '请上传正确的CSV文件');
          } else if (error.response.status === 404) {
            errorMessage = '不支持的县市：' + this.countyName;
          } else if (error.response.status === 500) {
            errorMessage = '服务器错误：' + (error.response.data.detail || '请稍后重试');
          }
        }
        
        this.$message.error(errorMessage);
      } finally {
        this.isCalculating = false;
        this.loadingMap = false;
        this.loadingHistogram = false;
      }
    },
    
    // 从数据库计算
    async calculateFromDatabase() {
      try {
        this.isCalculatingFromDB = true;
        this.loadingMap = true;
        this.loadingHistogram = true;
        
        // 创建FormData
        const formData = new FormData();
        formData.append('area', this.countyName);
        formData.append('use_database', 'true'); // 使用数据库数据
        
        // 调用有效Cd地图接口
        const mapResponse = await api8000.post(
          '/api/cd-prediction/effective-cd/generate-and-get-map',
          formData,
          {
            headers: {
              'Content-Type': 'multipart/form-data'
            },
            responseType: 'blob'
          }
        );
        
        // 保存地图数据
        this.mapBlob = mapResponse.data;
        this.mapImageUrl = URL.createObjectURL(this.mapBlob);
        
        // 更新后重新获取直方图
        await this.fetchLatestHistogram();
        
        this.$message.success('数据库计算完成！');
        
      } catch (error) {
        console.error('从数据库计算失败:', error);
        let errorMessage = '数据库计算失败，请重试';
        
        if (error.response) {
          if (error.response.status === 400) {
            errorMessage = '参数错误：' + (error.response.data.detail || '请检查县市名称');
          } else if (error.response.status === 404) {
            errorMessage = '不支持的县市：' + this.countyName;
          } else if (error.response.status === 500) {
            errorMessage = '服务器错误：' + (error.response.data.detail || '请稍后重试');
          }
        }
        
        this.$message.error(errorMessage);
      } finally {
        this.isCalculatingFromDB = false;
        this.loadingMap = false;
        this.loadingHistogram = false;
      }
    },
    
    // 导出地图
    exportMap() {
      if (!this.mapBlob) {
        this.$message.warning('请先计算生成地图');
        return;
      }
      
      const link = document.createElement('a');
      link.href = URL.createObjectURL(this.mapBlob);
      link.download = `${this.countyName}_有效态Cd预测地图.jpg`;
      link.click();
      URL.revokeObjectURL(link.href);
    },
    
    // 导出直方图
    exportHistogram() {
      if (!this.histogramBlob) {
        this.$message.warning('请先计算生成直方图');
        return;
      }
      
      const link = document.createElement('a');
      link.href = URL.createObjectURL(this.histogramBlob);
      link.download = `${this.countyName}_有效态Cd预测直方图.jpg`;
      link.click();
      URL.revokeObjectURL(link.href);
    },
    
    // 导出数据
    async exportData() {
      try {
        this.$message.info('正在获取有效Cd预测数据...');
        
        const response = await api8000.get(
          `/api/cd-prediction/download-final-effective-cd-csv`,
          { responseType: 'blob' }
        );
        
        const blob = new Blob([response.data], { type: 'text/csv' });
        const link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = `${this.countyName}_有效Cd预测数据.csv`;
        link.click();
        URL.revokeObjectURL(link.href);
        
        this.$message.success('数据导出成功');
      } catch (error) {
        console.error('导出数据失败:', error);
        this.$message.error('导出数据失败: ' + (error.response?.data?.detail || '请稍后重试'));
      }
    }
  }
};
</script>

<style scoped>
.container {
  padding: 20px;
  /* 添加70%透明度的渐变背景 */
  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;
}

.toolbar {
  display: flex;
  flex-direction: column;
  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); /* 添加模糊效果增强半透明感 */
}

.upload-section {
  display: flex;
  align-items: center;
  gap: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(0, 0, 0, 0.1); /* 调整边框透明度 */
}

.file-name {
  flex: 1;
  padding: 0 10px;
  color: #666;
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.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;
}

.upload-icon {
  margin-right: 5px;
}

.content-area {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 地图区域 */
.map-section {
  background-color: rgba(255, 255, 255, 0.8); /* 调整为半透明白色 */
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: relative;
  min-height: 500px;
  backdrop-filter: blur(5px); /* 添加模糊效果增强半透明感 */
}

.map-image {
  width: 100%;
  height: 100%;
  max-height: 500px;
  object-fit: contain;
  border-radius: 4px;
}

/* 直方图区域 */
.histogram-section {
  background-color: rgba(255, 255, 255, 0.8); /* 调整为半透明白色 */
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  position: relative;
  min-height: 500px;
  backdrop-filter: blur(5px); /* 添加模糊效果增强半透明感 */
}

.histogram-image {
  width: 100%;
  height: 100%;
  max-height: 600px;
  object-fit: contain;
  border-radius: 4px;
}

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

.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;
}

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

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

/* 响应式布局调整 */
@media (max-width: 992px) {
  .content-area {
    flex-direction: column;
  }
}
</style>