<script setup lang="ts">
/**
 * @Name: TrendChart.vue
 * @Description:
 * @Author: Cheney
 */

import * as echarts from 'echarts';
import * as api from '../api';
import { useResponse } from '/@/utils/useResponse';


const props = defineProps({
  asin: String,
  country: String
});
const { asin, country } = props;

let chartRef: any = useTemplateRef('chartRef');
let chart: echarts.ECharts | null = null;
let resizeObserver: ResizeObserver | null = null;
let chartData: any = ref([]);
const loading = ref(false)
//
// onBeforeMount(() => {
//  
// });

onMounted(() => {
  fetchChartData();
  initChart();
});

onUnmounted(() => {
  resizeObserver?.disconnect();
  chart?.dispose();
});

function updateChart() {
  if (!chart || chartData.value.length === 0) return;

  const chartOptions = {
    title: {
      text: '商品价格趋势'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: [ '价格' ]
    },
    grid: {
      top: '20%',
      left: '10%',
      right: '10%',
      bottom: '10%'
    },
    dataset: {
      dimensions: [ 'create_datetime', 'new_val' ],
      source: chartData.value
    },
    xAxis: {
      type: 'category'
    },
    yAxis: [
      {
        type: 'value',
        name: '价格',
        nameTextStyle: {
          fontWeight: 'bold',
          fontSize: 14,
          color: '#333'
        },
        splitLine: {
          show: true
        },
        axisLine: {
          show: true,
          lineStyle: {
            color: '#333',
            width: 1
          }
        }
      }
    ],
    series: [
      {
        name: '价格',
        type: 'line',
        areaStyle: {
          // 设置渐变颜色
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            {
              offset: 0,
              color: 'rgba(84,112,198, 0.4)'
            },
            {
              offset: 1,
              color: 'rgba(84,112,198, 0.1)'
            }
          ])
        }
      }
    ]
  };

  chart.setOption(chartOptions);
}

function initChart() {
  if (!chartRef.value) return;

  chart = echarts.init(chartRef.value);
  updateChart();

  resizeObserver = new ResizeObserver(() => {
    chart?.resize();
  });
  if (chartRef.value) {
    resizeObserver.observe(chartRef.value);
  }
}

async function fetchChartData() {
  const res = await useResponse(api.getChartData, { asin, country_code: country }, loading);
  if (res.code === 2000 && res.data) {
    chartData.value = res.data;
    updateChart();
  }
}
</script>

<template>
  <el-card class="border-none mt-2">
    <div v-show="chartData.length > 0" ref="chartRef" class="chart"></div>
    <el-empty v-if="chartData.length == 0" description="暂无数据" class="chart" />
  </el-card>
</template>

<style scoped>
.chart {
  width: 100%;
  height: 400px;
}
</style>
