<template>
  <div ref="chart" :style="chartStyle"></div>
</template>

<script>
/**
 * 折线图
 * 和柱状图对比
 * - 增加了: smooth/step/symbol="emptyCircle"/symbolSize=4 
 * - 去掉了: borderRadius/barWidth 
 * 
  <!-- 基础用法 -->
  <line-chart-plus 
    :seriesData="barLineChartOptions.seriesData"
    :xAxisData="barLineChartOptions.xAxisData"
  ></line-chart-plus>
  
  <!-- 全量配置 -->
  <bar-chart-plus 
    :seriesData="barLineChartOptions.seriesData" 
    :xAxisData="barLineChartOptions.xAxisData"
    width="600px" 
    height="400px" 
    theme="light" 
    :colorStart="['#333', 'rgba(255, 0, 0, 0.1)']"
    :colorEnd="['#fff', 'rgba(255, 0, 0, 0.9)']" 
    :colorCenter="['#999', 'rgba(255, 255, 0, 01)']"
    textColor="#f0f" 
    label 
    smooth 
    step 
    symbol="emptyCircle" 
    symbolSize="10" 
    minSpan="50" 
    x_rotate="45" 
    y_name="金额" 
    y_axisLine 
    y_splitLine 
    y_type="log"
  ></bar-chart-plus>
**/
import * as echarts from 'echarts';

export default {
  name: 'LineChartPlus',
  props: {
    // 系列数据 (数组对象)
    seriesData: {
      type: Array,
      required: true
    },
    // X轴数据
    xAxisData: {
      type: Array,
      required: true
    },
    // 图表宽度(支持 400（px） '100%' '100vh'等格式)
    width: {
      type: [String, Number],
      default: '100%'
    },
    // 图表高度
    height: {
      type: [String, Number],
      default: '300px'
    },
    // 主题 (可选值: 'dark', 'light', 自定义主题)
    theme: {
      type: String,
      default: 'light'
    },
    // 渐变色开始（数组，传递参数需要: 不要传成字符串）
    colorStart: {
      type: Array,
      default: () => ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452', '#9a60b4', '#ea7ccc']
    },
    // 渐变色结束
    colorEnd: {
      type: Array,
      default: () => []
    },
    // 渐变色中段（一般只配置收尾，支持raba透明度处理效果）
    colorCenter: {
      type: Array,
      default: () => []
    },
    // 默认的x轴/y轴标签+轴线等文字颜色
    textColor: {
      type: String,
      default: '#7D7D7D'
    },
    // 柱子标签
    label: {
      type: Boolean,
      default: false
    },
    // 是否平滑
    smooth: {
      type: Boolean,
      default: false
    },
    // 是否阶梯
    step: {
      type: Boolean,
      default: false
    },
    // 顶点形状 circle-圆形 emptyCircle-空心圆圈
    symbol: {
      type: String,
      default: 'emptyCircle'
    },
    // 顶点大小
    symbolSize: {
      type: [String, Number],
      default: 4
    },
    // x轴滑块（简易处理x轴数据过多）
    minSpan: {
      type: [String, Number],
      default: 100
    },
    // X轴旋转
    x_rotate: {
      type: [String, Number],
      default: 0
    },
    // Y轴名称
    y_name: {
      type: String,
      default: ''
    },
    // y轴轴线
    y_axisLine: {
      type: Boolean,
      default: false
    },
    // y轴分割线
    y_splitLine: {
      type: Boolean,
      default: false
    },
    // 柱子类型（为了支持log传入）
    y_type: {
      type: String,
      default: 'value'
    },
  },
  data() {
    return {
      chartInstance: null
    };
  },
  computed: {
    chartStyle() {
      const parseDimension = (value) => {
        if (typeof value === 'number') {
          // 数字类型，添加 px 单位
          return `${value}px`;
        } else if (typeof value === 'string') {
          // 字符串类型，检查是否需要添加 px 单位
          const numericValue = parseFloat(value);
          if (!isNaN(numericValue) && value.trim() === numericValue.toString()) {
            // 纯数字字符串，添加 px 单位
            return `${numericValue}px`;
          }
          // 已经包含单位（如 '100%' 或 '400px'），直接返回
          return value;
        }
        // 默认值
        return '100%';
      };

      return {
        width: parseDimension(this.width),
        height: parseDimension(this.height)
      };
    }
  },
  watch: {
    xAxisData: 'updateChart',
    seriesData: 'updateChart',
    theme: 'initChart'
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    this.disposeChart();
  },
  methods: {
    // 初始化
    initChart() {
      // 主题切换需要销毁
      if (this.chartInstance) {
        this.disposeChart();
      }
      this.chartInstance = echarts.init(this.$refs.chart, this.theme);
      this.updateChart();
      window.addEventListener('resize', this.resizeChart);
    },
    // 销毁
    disposeChart() {
      if (this.chartInstance) {
        this.chartInstance.dispose();
        this.chartInstance = null;
      }
      window.removeEventListener('resize', this.resizeChart);
    },
    // 监听缩放
    resizeChart() {
      if (this.chartInstance) {
        this.chartInstance.resize();
      }
    },
    // 更新图表
    updateChart() {
      if (!this.chartInstance) return;
      const option = this.getOption();
      this.chartInstance.setOption(option);
    },
    // 加载配置
    getOption() {
      const hasColorEnd = Array.isArray(this.colorEnd) && this.colorEnd.length > 0;
      const hasColorCenter = Array.isArray(this.colorCenter) && this.colorCenter.length > 0;

      // [{ name: '收入', data: [100, 150, 200, 250, 300] }]
      const series = this.seriesData.map((item, index) => ({
        type: 'line',
        name: item.name,
        data: item.data,
        label: {
          show: this.label,
          position: 'top',
          color: this.theme === 'dark' ? '#fff' : this.textColor
        },
        smooth: this.smooth,
        step: this.step,
        symbol: this.symbol,
        symbolSize: Number(this.symbolSize),
        areaStyle: { // 填充区域样式
          color: hasColorEnd && hasColorCenter
            ? new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: this.colorStart[index % this.colorStart.length] },
              { offset: 0.5, color: this.colorCenter[index % this.colorCenter.length] },
              { offset: 1, color: this.colorEnd[index % this.colorEnd.length] }
            ])
            : hasColorEnd && !hasColorCenter ? new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: this.colorStart[index % this.colorStart.length] },
              { offset: 1, color: this.colorEnd[index % this.colorEnd.length] }
            ])
              : this.colorStart[index % this.colorStart.length]
        },
        lineStyle: {
          width: 1,
          type: 'solid', // 'solid'/'dashed'/'dotted'
        }
      }));
      return {
        backgroundColor: 'transparent', // 背景选用传入，放弃默认背景色
        legend: { top: '5%', left: 'center' },
        grid: { top: '15%', bottom: '15%', left: '25%', right: '15%' },
        tooltip: { trigger: 'axis', axisPointer: { type: 'cross' } },
        color: this.colorStart,
        xAxis: {
          type: 'category',
          data: this.xAxisData,
          axisLabel: { interval: 0, rotate: this.x_rotate, color: this.textColor },
          axisLine: { lineStyle: { color: this.textColor } },
          axisTick: { show: false },
        },
        yAxis: {
          type: this.y_type,
          name: this.y_name,
          boundaryGap: [0, '3%'],
          axisLabel: { interval: 0, rotate: 0 },
          axisLine: { show: this.y_axisLine, lineStyle: { color: this.textColor } },
          axisTick: { show: false },
          splitLine: {
            show: this.y_splitLine,
            lineStyle: { color: [this.textColor], type: 'dashed', width: 1 }
          },
        },
        // x轴滑块
        dataZoom: this.minSpan != 100 ? [{
          type: 'inside', // 内部缩放
          minSpan: Number(this.minSpan), // 缩放系数(0-缩小到极限，100-不缩放)
        }] : [],
        series,
      };
    },
  }
};
</script>

<style scoped></style>