<template>
  <div class="chart-container">
    <h3 class="title">{{ $t('AcidificationDataStatistics.refluxTitle') }}</h3>
    <div class="echarts-box" ref="chartRef"></div>
    
    <!-- 加载状态提示 -->
    <div v-if="isLoading" class="loading-tip">
      {{ $t('DetectionStatistics.dataLoading') }}
    </div>
    
    <!-- 错误提示 -->
    <div v-if="errorMessage && !isLoading" class="error-tip">
      {{ errorMessage }}
      <el-button type="primary" size="small" @click="fetchData">
        {{ $t('SoilCdStatistics.retry') }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { api5000 } from '@/utils/request';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

// 图表相关
const chartRef = ref(null);
let myChart = null;

// 数据状态
const chartData = ref([]);
const isLoading = ref(false);
const errorMessage = ref('');

// 接口地址
const API_URL = '/api/table-data?table_name=dataset_81';

// 获取数据函数
const fetchData = async () => {
  errorMessage.value = '';
  isLoading.value = true;
  
  try {
    const response = await api5000.get(API_URL);
    
    if (response.data && response.data.success) {
      if (Array.isArray(response.data.data) && response.data.data.length > 0) {
        // 检查数据结构，确保有 id 和 Delta_pH_105day 字段
        const validData = response.data.data.filter(item => 
          item.id !== undefined && item.Delta_pH_105day !== undefined
        );
        
        if (validData.length > 0) {
          chartData.value = validData;
        } else {
          errorMessage.value = t('DetectionStatistics.noValidData');
        }
      } else {
        errorMessage.value = t('DetectionStatistics.noValidData');
      }
    } else {
      errorMessage.value = t('AcidificationDataStatistics.apiError');
    }
  } catch (error) {
    console.error('数据获取失败:', error);
    if (error.response) {
      errorMessage.value = `${t('AcidificationDataStatistics.requestError')} (${error.response.status})`;
    } else if (error.request) {
      errorMessage.value = t('AcidificationDataStatistics.networkError');
    } else {
      errorMessage.value = t('AcidificationDataStatistics.requestError');
    }
  } finally {
    isLoading.value = false;
  }
};

// 初始化图表
const initChart = () => {
  if (!chartRef.value) {
    console.error('图表容器未找到');
    return;
  }

  if (chartData.value.length === 0) {
    console.error('没有数据可用于渲染图表');
    return;
  }
  
  if (myChart) {
    myChart.dispose();
  }
  
  myChart = echarts.init(chartRef.value);
  
  const xAxisData = chartData.value.map(item => item.id);
  const seriesData = chartData.value.map(item => ({
    value: item.Delta_pH_105day,
    itemStyle: {
      color: item.Delta_pH_105day >= 0 ? '#0F52BA' : '#F44336'
    }
  }));
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        // 安全地获取数据，避免 undefined 错误
        const itemName = params[0].name;
        const item = chartData.value.find(d => d.id === itemName);
        
        if (item) {
          return `ID: ${item.id}<br/>Delta_pH_105day: ${item.Delta_pH_105day.toFixed(4)}`;
        } else {
          return `ID: ${itemName}<br/>Delta_pH_105day: ${params[0].value.toFixed(4)}`;
        }
      }
    },
    grid: {
      left: '5%',
      right: '1%',
      bottom: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: xAxisData,
      name: 'ID',
      nameLocation: 'middle',
      nameGap: 30,
    },
    yAxis: {
      type: 'value',
      name: 'Delta_pH_105day',
      nameLocation: 'middle',
      nameGap: 50,
      axisLabel: {
        formatter: '{value}'
      }
    },
    series: [
      {
        name: 'Delta_pH_105day',
        type: 'bar',
        data: seriesData,
        barWidth: '60%',
        label: {
          show: false,
          position: 'top',
          formatter: function(params) {
            return params.value.toFixed(4);
          }
        }
      }
    ]
  };
  
  myChart.setOption(option);
};

// 监听数据变化
watch(chartData, () => {
  nextTick(() => {
    if (myChart) {
      myChart.clear(); // 清除现有内容
      myChart.setOption({}); // 重置选项
    }
    initChart(); // 重新初始化
  })
});

const handleResize = () => {
  if (myChart) {
    setTimeout(() => {
      myChart.resize();
    }, 100);
  }
};

onMounted(async() => {
  await fetchData();
  initChart();
  window.addEventListener('resize', handleResize);
});

onUnmounted(() => {
  if (myChart) {
    myChart.dispose();
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 470px;
  padding: 20px;
  box-sizing: border-box;
  position: relative;
}

.echarts-box {
  width: 100%;
  height: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.title {
  text-align: center;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.loading-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 14px;
  color: #666;
}

.error-tip {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #f44336;
  font-size: 14px;
}

.error-tip .el-button {
  margin-left: 10px;
}
</style>