<script setup lang='ts'>
import { ref, onMounted, nextTick, onUnmounted, watch } from 'vue';
import VueEcharts from 'vue-echarts';
import 'echarts';
import { api5000 } from '../../../utils/request';
import { useI18n } from 'vue-i18n';

const { t } = useI18n();

interface HistoryDataItem {
  dataset_id: number;
  row_count: number;
  model_id: number;
  model_name: string;
  performance_score: number;
  timestamp: string;
}

interface HistoryDataResponse {
  data_type: string;
  timestamps: string[];
  row_counts: number[];
  performance_scores: number[];
  model_details: HistoryDataItem[];
}

interface ScatterDataResponse {
  scatter_data: [number, number][];
  r2_score: number;
  y_range: [number, number];
  model_name: string;
  model_type: string;
}

const props = defineProps({
  showLineChart: {
    type: Boolean,
    default: true
  },
  showInitScatterChart: {
    type: Boolean,
    default: true
  },
  showMidScatterChart: {
    type: Boolean,
    default: true
  },
  showFinalScatterChart: {
    type: Boolean,
    default: true
  },
  lineChartPathParam: {
    type: String,
    default: 'reflux'
  },
  initScatterModelId: {
    type: Number,
    default: 6
  },
  midScatterModelId: {
    type: Number,
    default: 7
  },
  finalScatterModelId: {
    type: Number,
    default: 17
  }
});

// 定义响应式变量
const ecLineOption = ref({});
const ecInitScatterOption = ref({});
const ecMidScatterOption = ref({});
const ecFinalScatterOption = ref({});

// 定义图表引用
const ecLineOptionRef = ref<InstanceType<typeof VueEcharts>>();
const ecInitScatterOptionRef = ref<InstanceType<typeof VueEcharts>>();
const ecMidScatterOptionRef = ref<InstanceType<typeof VueEcharts>>();
const ecFinalScatterOptionRef = ref<InstanceType<typeof VueEcharts>>();

// 新增：图片URL和模型类型选择
const learningCurveImageUrl = ref('');
const dataIncreaseCurveImageUrl = ref('');
const selectedModelType = ref('rf'); // 默认选择随机森林

// 模型类型选项
const modelTypeOptions = [
  { label: t('ModelIteration.randomForest'), value: 'rf' },
  { label: t('ModelIteration.xgboost'), value: 'xgbr' },
  { label: t('ModelIteration.gradientBoosting'), value: 'gbst' },
];


// 计算数据范围的函数
const calculateDataRange = (data: [number, number][]) => {
  const xValues = data.map(item => item[0]);
  const yValues = data.map(item => item[1]);
  return {
    xMin: Math.min(...xValues),
    xMax: Math.max(...xValues),
    yMin: Math.min(...yValues),
    yMax: Math.max(...yValues)
  };
};

// 获取折线图数据
const fetchLineData = async () => {
  try {
    const response = await api5000.get<HistoryDataResponse>(`/get-model-history/${props.lineChartPathParam}`);
    const data = response.data;

    const timestamps = data.timestamps;
    const performanceScores: Record<string, number[]> = {};

    data.model_details.forEach((item: HistoryDataItem) => {
      const score = Number(item.performance_score);
      if (!performanceScores[item.model_name]) {
        performanceScores[item.model_name] = [];
      }
      performanceScores[item.model_name].push(score);
    });

    const series = Object.keys(performanceScores).map(modelName => ({
      name: modelName,
      type: 'line',
      data: performanceScores[modelName]
    }));

    ecLineOption.value = {
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        data: Object.keys(performanceScores)
      },
      grid: {
        left: '3%',
        right: '17%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        name: t('ModelIteration.modelIteration'),
        type: 'category',
        boundaryGap: false,
        data: timestamps.map((_, index) => `${index + 1}代`)
      },
      yAxis: {
        name: 'Score (R^2)',
        type: 'value'
      },
      series
    };
    console.log('ecLineOption updated:', ecLineOption.value);
  } catch (error) {
    console.error('获取折线图数据失败:', error);
  }
};

// 获取散点图数据
const fetchScatterData = async (modelId: number, optionRef: any) => {
  try {
    const response = await api5000.get<ScatterDataResponse>(`/model-scatter-data/${modelId}`);
    const data = response.data;

    const scatterData = data.scatter_data;
    const range = calculateDataRange(scatterData);
    const padding = 0.1;
    const xMin = range.xMin - Math.abs(range.xMin * padding);
    const xMax = range.xMax + Math.abs(range.xMax * padding);
    const yMin = range.yMin - Math.abs(range.yMin * padding);
    const yMax = range.yMax + Math.abs(range.yMax * padding);
    const min = Math.min(xMin, yMin);
    const max = Math.max(xMax, yMax);

    optionRef.value = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      legend: {
        data: ['True vs Predicted']
      },
      grid: {
        left: '3%',
        right: '22%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        name: 'True Values',
        type: 'value',
        min: min,
        max: max
      },
      yAxis: {
        name: 'Predicted Values',
        type: 'value',
        min: parseFloat(min.toFixed(2)),
        max: parseFloat(max.toFixed(2))
      },
      series: [
        {
          name: 'True vs Predicted',
          type: 'scatter',
          data: scatterData,
          symbolSize: 10,
          itemStyle: {
            color: '#1f77b4',
            opacity: 0.7
          }
        },
        {
          name: 'Trendline',
          type: 'line',
          data: [
            [min, min],
            [max, max]
          ],
          lineStyle: {
            type: 'dashed',
            color: '#ff7f0e',
            width: 2
          }
        }
      ]
    };
  } catch (error) {
    console.error('获取散点图数据失败:', error);
  }
};

// 新增：获取学习曲线图片
const fetchLearningCurveImage = async () => {
  try {
    const response = await api5000.get('/latest-learning-curve', {
      params: {
        data_type: 'reflux',
        model_type: selectedModelType.value
      },
      responseType: 'blob'
    });
    
    const blob = new Blob([response.data], { type: 'image/png' });
    learningCurveImageUrl.value = URL.createObjectURL(blob);
  } catch (error) {
    console.error('获取学习曲线图片失败:', error);
  }
};

// 新增：获取数据增长曲线图片
const fetchDataIncreaseCurveImage = async () => {
  try {
    const response = await api5000.get('/latest-data-increase-curve', {
      params: {
        data_type: 'reflux',
      },
      responseType: 'blob'
    });
    
    const blob = new Blob([response.data], { type: 'image/png' });
    dataIncreaseCurveImageUrl.value = URL.createObjectURL(blob);
  } catch (error) {
    console.error('获取数据增长曲线图片失败:', error);
  }
};

// 监听模型类型变化，重新获取图片
watch(selectedModelType, () => {
  fetchLearningCurveImage();
  fetchDataIncreaseCurveImage();
});
// 定义调整图表大小的函数
const resizeCharts = () => {
  nextTick(() => {
    if (props.showLineChart) ecLineOptionRef.value?.resize();
    if (props.showInitScatterChart) ecInitScatterOptionRef.value?.resize();
    if (props.showMidScatterChart) ecMidScatterOptionRef.value?.resize();
    if (props.showFinalScatterChart) ecFinalScatterOptionRef.value?.resize();
  });
};

onMounted(async () => {
  if (props.showLineChart) await fetchLineData();
  if (props.showInitScatterChart) await fetchScatterData(props.initScatterModelId, ecInitScatterOption);
  if (props.showMidScatterChart) await fetchScatterData(props.midScatterModelId, ecMidScatterOption);
  if (props.showFinalScatterChart) await fetchScatterData(props.finalScatterModelId, ecFinalScatterOption);

  // 新增：获取图片
  await fetchLearningCurveImage();
  await fetchDataIncreaseCurveImage();

  // 页面加载完成后调整图表大小
  resizeCharts();

  // 监听窗口大小变化，调整图表大小
  window.addEventListener('resize', resizeCharts);
});

// 组件卸载时移除事件监听器
onUnmounted(() => {
  window.removeEventListener('resize', resizeCharts);

  // 清理Blob URL
  if (learningCurveImageUrl.value) {
    URL.revokeObjectURL(learningCurveImageUrl.value);
  }
  if (dataIncreaseCurveImageUrl.value) {
    URL.revokeObjectURL(dataIncreaseCurveImageUrl.value);
  }
});
</script>

<template>
  <div class="container">
    <template v-if="showInitScatterChart">
      <!-- 散点图 -->
      <h2 class="chart-header">{{ $t('ModelIteration.scatterPlotTitle') }}</h2>
      <div class="chart-container">
        <VueEcharts :option="ecInitScatterOption" ref="ecInitScatterOptionRef" />
      </div>
    </template>

   <h2 class="chart-header">{{ $t('ModelIteration.modelPerformanceAnalysis') }}</h2>
    <!-- 模型性能分析部分 -->
    <div class="analysis-section">
       <!-- 数据增长曲线模块 -->
      <div class="chart-module">
        <h2 class="chart-header">{{ $t('ModelIteration.dataIncreaseCurve') }}</h2>
        <div class="image-chart-item">
          <div class="image-container">
            <img v-if="dataIncreaseCurveImageUrl" :src="dataIncreaseCurveImageUrl" :alt="$t('ModelIteration.dataIncreaseCurve')" >
            <div v-else class="image-placeholder">{{ $t('ModelIteration.loading') }}</div>
          </div>
        </div>
      </div>
      <!-- 学习曲线模块 -->
      <div class="chart-module">
        <h2 class="chart-header">{{ $t('ModelIteration.learningCurve') }}</h2>
        <div class="model-selector-wrapper">
          <select v-model="selectedModelType" class="model-select">
            <option v-for="option in modelTypeOptions" :key="option.value" :value="option.value">
              {{ option.label }}
            </option>
          </select>
        </div>
        <div class="image-chart-item">
          <div class="image-container">
            <img v-if="learningCurveImageUrl" :src="learningCurveImageUrl" :alt="$t('ModelIteration.learningCurve')" >
            <div v-else class="image-placeholder">{{ $t('ModelIteration.loading') }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  gap: 20px;
  color: #000;
  background-color: white;
}

.chart-header {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  color: #2c3e50;
}

.sub-title {
  font-size: 14px;
  font-weight: 700;
}

.chart-container {
  width: 85%;
  height: 450px;
  margin: 0 auto;
  margin-bottom: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.VueEcharts {
  width: 100%;
  height: 100%;
  margin: 0 10px;
  background-color: white;
}

/* 新增：图片图表样式 */
.image-charts-section {
  width: 90%;
  margin: 30px auto;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.model-type-selector {
  margin: 20px 0;
  text-align: center;
}

.model-type-selector label {
  margin-right: 10px;
  font-weight: bold;
  color: #2c3e50;
}

.model-select {
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background-color: white;
  font-size: 14px;
}

.image-charts-container {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
  margin-top: 20px;
}

.image-chart-item {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

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

.image-container {
  width: 100%;
  height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f8f9fa;
  border-radius: 4px;
  overflow: hidden;
}

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

.image-placeholder {
  color: #6c757d;
  font-style: italic;
}

/* 确保图表内部也是白色背景 */
:deep(.echarts) {
  background-color: white;
}

/* 为图表标题添加样式 */
:deep(.echarts-title) {
  color: #2c3e50;
  font-weight: bold;
}

/* 为坐标轴添加样式 */
:deep(.echarts-axis) {
  color: #666;
}

/* 为图例添加样式 */
:deep(.echarts-legend) {
  color: #333;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .image-charts-container {
    grid-template-columns: 1fr;
  }
  
  .image-container {
    height: 300px;
  }
  
  .chart-container {
    width: 95%;
    height: 400px;
  }
}
</style>