<template>
  <div style="height:100%;width:100%" :id="echartsId"></div>
</template>
<script setup>
import * as echarts from "echarts";
import { onMounted, ref, reactive, defineProps, onUnmounted, watch, nextTick } from "vue";
const props = defineProps({
  echartsId:{
    type:String,
    default:'lineId'
  },
  color:{ 
    type:String,
    default:'#fff'
  },
  data:{ 
    type:Array,
    default:[]
  }
});

// 保存echarts实例
const myChart = ref(null);

// 定义resize处理函数
const handleResize = () => {
  if (myChart.value) {
    myChart.value.resize();
  }
};

function chartFn() {
  // 如果已有实例，先销毁
  if (myChart.value) {
    myChart.value.dispose();
  }
  
  // 创建新实例
  myChart.value = echarts.init(document.getElementById(props.echartsId));
  var option = {
    grid: {
      top: "8%",
      right: "2%",
      left: "10%",
      bottom: "12%",
      containLabel:true
    },
    tooltip: {
      trigger: "axis",
      axisPointer: {
        lineStyle: {
          color: "#ddd"
        }
      },
      backgroundColor: "rgba(255,255,255,1)",
      padding: [5, 10],
      textStyle: {
        color: "#7588E4"
      },
      extraCssText: "box-shadow: 0 0 5px rgba(0,0,0,0.3)"
    },
    xAxis: {
      type: "category",
      data:props.data.map(v=>{return v.label}),
      axisTick: { show: false },
      axisLine: { show: false },
      axisLabel: { 
        show: true,
        color: props.color,
        interval: 0, // 强制显示所有标签
        // rotate: 15, // 标签旋转角度
      }
    },
    yAxis: {
      type: "value",
      splitLine: {
        show:true ,
        lineStyle: {
          type:'dashed',
          color: "rgba(14,95,255,0.5)"
        }
      },
      axisTick: { show: false },
      axisLine: { show: false },
      axisLabel: { color: props.color },
    },
    series: [
      {
        type: "line",
        smooth:true,
        showSymbol:false,
        data: props.data.map(v=>{return v.value}),
        areaStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                  offset: 0,
                  color: 'rgba(199, 237, 250,0.5)'
              }, {
                  offset: 1,
                  color: 'rgba(199, 237, 250,0.2)'
              }], false)
            }
        },
        itemStyle: {
          normal: {
            color: "rgb(4, 145, 216)"
          }
        },
        lineStyle: {
          normal: {
            width: 1,
            color:'#00FFFF'
          }
        }
      }
    ]
  };
  option && myChart.value.setOption(option);
}

// 监听数据变化
watch(()=>props.data,val=>{
  nextTick(()=>{ chartFn() })
},{immediate:true,deep:true})

// 组件挂载时初始化图表并添加事件监听
onMounted(()=>{
  chartFn();
  window.addEventListener('resize', handleResize);
});

// 组件卸载时清理资源
onUnmounted(()=>{
  if (myChart.value) {
    myChart.value.dispose();
    myChart.value = null;
  }
  window.removeEventListener('resize', handleResize);
});
</script>

<style lang="scss" scoped>

</style>