<template>
  <div class="ks-model-chart-item" ref="chartContainer"></div>
</template>

<script lang="ts">
import { defineComponent, nextTick, type PropType, ref, watch } from 'vue';
import * as echarts from 'echarts';
import type { ModelDeductionData } from '../types';
import { createLineChartOption } from './line-options';

export default defineComponent({
  props: {
    datas: {
      type: Array as PropType<ModelDeductionData[]>,
      default: [],
    },
    redName: {
      type: String as PropType<String>,
      default: '红方',
    },
    blueName: {
      type: String as PropType<String>,
      default: '蓝方',
    },
  },
  setup(props) {
    const chartContainer = ref<HTMLElement | null>(null);
    let chartInstance: echarts.ECharts | null = null;

    const initChart = (option: any) => {
      if (!chartContainer.value) return;

      if (chartInstance) {
        chartInstance.dispose();
      }
      chartInstance = echarts.init(chartContainer.value);

      chartInstance.setOption(option);

      // 自适应窗口大小（可选，提升体验）
      window.addEventListener('resize', () => {
        chartInstance?.resize();
      });
    };

    const load = (d: ModelDeductionData[]) => {
      const xAxisData: string[] = [];
      const blueData: any[] = [];
      const redData: any[] = [];
      if (d) {
        d.forEach(item => {
          xAxisData.push(`轮数${item.currentEpisode}`);
          blueData.push(item.firstFireTimeBlue);
          redData.push(item.firstFireTimeRed);
        });
      }
      const options = createLineChartOption({
        title: '最早锁定发射时间',
        blueName: props.blueName as string,
        redName: props.redName as string,
        xAxisData: xAxisData,
        blueData: blueData,
        redData: redData,
        xAxisDataVisible: true,
        labelVisible: false,
      });
      nextTick(() => initChart(options));
    };

    watch(() => props.datas, (n: ModelDeductionData[]) => load(n), { deep: true, immediate: true });

    return {
      chartContainer
    };
  }
});
</script>
