<script lang="ts" setup>
import * as echarts from 'echarts';
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { getTrends } from '/@/views/googleTrends/api';
import DateRangePicker from '/@/components/DateRangePicker/index.vue';
import dayjs from 'dayjs';


const dateRange = ref([
  dayjs().subtract(2, 'week').startOf('day').format('YYYY-MM-DD'),
  dayjs().subtract(1, 'week').endOf('day').format('YYYY-MM-DD')
]);

const { keywordList } = defineProps<{ keywordList: any; }>();
const defaultKeywords = ref<string[]>(keywordList.slice(0, 5));
const colors = ['#0098ed', '#229b32', '#35e6ee', '#ff4a4c', '#f8cb4b'];

let chartObj: any;
const chartRef = ref(null);
const loading = ref(false);
const dataSet = ref([]);

// 初始化 ECharts 图表
onMounted(() => {
  addResize();
  initLine();
});

// 组件卸载前清理
onBeforeUnmount(() => {
  if (chartObj) {
    chartObj.dispose();
    chartObj = null;
  }
  removeResize();
});

// ECharts 配置项
const option: any = {
  dataset: {
    source: [],
  },
  tooltip: {
    trigger: 'axis'
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  // toolbox: {
  //   feature: {
  //     saveAsImage: {}
  //   }
  // },
  xAxis: {
    type: 'category',
  },
  yAxis: {
    type: 'value',
    // name: '搜索量',
    show: true,
    splitLine: {
      show: true, // 设置显示分割线
    },
    axisLine: {
      show: true,
      lineStyle: {
        color: '#0090e4'
      }
    },

  },
  series: [
    {
      id: 0,
      name: '1',
      type: 'line',
      stack: 'Total',
      data: []
    },
    {
      id: 1,
      name: '2',
      type: 'line',
      stack: 'Total',
      data: []
    },
    {
      id: 2,
      name: '',
      type: 'line',
      stack: 'Total',
      data: []
    },
    {
      id: 3,
      name: '',
      type: 'line',
      stack: 'Total',
      data: []
    },
    {
      id: 4,
      name: '',
      type: 'line',
      stack: 'Total',
      data: []
    }
  ]
};

// 初始化 ECharts 图表的函数
async function initLine() {
  await loadData();
  chartObj = echarts.init(chartRef.value);
  option.dataset.source = dataSet.value;
  chartObj.setOption(option, true);
}

// 加载数据
async function loadData() {
  try {
    loading.value = true;
    const query = {
      keyword: defaultKeywords.value.join(','),
      date_start: dateRange.value[0],
      date_end: dateRange.value[1],
    }
    const resp = await getTrends(query);
    const trendData = resp.data;
    // dataSet.value = values; // 这里是 y 轴的数据
    option.xAxis.data = trendData.date; // 这里是 x 轴的数据
    option.series = defaultKeywords.value.map((keyword, index) => ({
      id: index,
      name: keyword,
      type: 'line',
      data: trendData[keyword],
      itemStyle: {
        color: colors[index]
      }
    }));
  }catch (e) {
    ElMessage.error('加载数据失败，请稍后再试');
  }
  finally {
    loading.value = false;
  }
}


function handleSelectChange(index: number) {
  console.log("=>(keywordTrendsChart.vue:175) index", index);
  // defaultKeywords.value[index] = keywordList[index];
  console.log("=>(keywordTrendsChart.vue:177) defaultKeywords.value[index]", defaultKeywords.value);
}

// 处理窗口大小变化
function resizeChart() {
  chartObj.resize();
}

// 添加窗口大小变化事件监听
function addResize() {
  window.addEventListener('resize', resizeChart);
}

// 移除窗口大小变化事件监听
function removeResize() {
  window.removeEventListener('resize', resizeChart);
}

// 动态计算 el-select 的宽度
function calculateSelectWidth(text) {
  const baseWidth = 50; // 基础宽度
  const padding = 15; // 额外的填充
  const charWidth = 10; // 平均字符宽度，可根据需要调整
  return baseWidth + (text.length * charWidth) + padding; // 计算宽度
}
</script>

<template>
  <div v-loading="loading">
    <div class="flex justify-between items-center mb-4">
      <span class="my-4 mx-1.5" style="font-size: 18px;font-weight: bold;color: #464646">谷歌关键词趋势</span>
      <DateRangePicker v-model="dateRange" @change="initLine()"></DateRangePicker>
    </div>
    <div class="keyword-select">
      <el-select
          v-for="(keyword, index) in defaultKeywords"
          :key="index"
          v-model="defaultKeywords[index]"
          @change="initLine()"
          :style="{'width': calculateSelectWidth(keyword) + 'px', 'border': 'none', 'box-shadow': 'none'}"
      >
        <el-option
            v-for="item in keywordList"
            :key="item"
            :disabled="defaultKeywords.includes(item)"
            :label="item"
            :value="item"
        />
        <template #label="{ label, value }">
          <el-tag :color="colors[index]" size="small"></el-tag>
          <span style="font-weight: bold;font-size:13px">{{ value }}</span>
        </template>
      </el-select>
    </div>
    <!-- 图表区域 -->
    <div ref="chartRef" style="height: 350px"></div>
  </div>
</template>

<style scoped>
.keyword-select {
  display: flex;
  /* align-items: center; */
  justify-content: space-between;
  padding: 20px;
  margin: 0 30px
}

:deep .el-select__wrapper {
  box-shadow: none;
}

:deep .is-hovering {
  box-shadow: none !important;
}

.el-tag {
  border: none;
  aspect-ratio: 1;
  margin-right: 10px;
}
</style>
