import dayjs, { Dayjs } from 'dayjs'
import { unref } from 'vue'
import XEUtils from 'xe-utils'
import * as echarts from 'echarts'

export function recentDaysRange(timezone: string, days: number): string[] {
  const now_tz = dayjs(new Date()).tz(timezone)
  const start = now_tz.subtract(days, 'day')
  const end = now_tz.subtract(1, 'day')
  return [start.format('YYYY-MM-DD'), end.format('YYYY-MM-DD')]
}

// export function buildChartOpt(option: any, metrics: any[]) {
//   const tmp: any = {}
//   const opt: any = {
//     legend: { selected: {} },
//     yAxis: [],
//     series: [],
//   }
//   for (const info of metrics) {
//     tmp[info.color] = info
//   }
//   for (const info of option.series) {
//     const color = info.itemStyle.color
//     const metricInfo = tmp[color]
//     console.log('tmp[color]', tmp[color]);
//     if (metricInfo) {
//       opt.series.push({
//         id: info.id,
//         name: metricInfo.label,
//         encode: { y: metricInfo.metric },
//       })
//       opt.yAxis.push({ id: info.id, name: metricInfo.label, show: true })
//     } else {
//       opt.yAxis.push({ id: info.id, show: false })
//     }
//   }
//   for (const label of Object.keys(option.legend.selected)) {
//     if (XEUtils.findIndexOf(metrics, (info) => info.label === label) === -1) {
//       opt.legend.selected[label] = false
//     } else {
//       opt.legend.selected[label] = true
//     }
//   }
//   return opt
// }

export function buildChartOpt(option: any, metrics: any[], allMetrics: any[]) {
  const opt: any = {
    legend: { selected: {} },
    yAxis: [],
    series: [],
  }

  // 创建一个指标到颜色的映射
  const metricToColor = allMetrics.reduce((acc, metric, index) => {
    acc[metric.metric] = {color: metric.color, index};
    return acc;
  }, {});

  // 更新系列和 y 轴
  allMetrics.forEach((metric, index) => {
    const isSelected = metrics.some(m => m.metric === metric.metric);
    const colorInfo = metricToColor[metric.metric];

    opt.series.push({
      ...option.series[index], // 保留原有的系列配置
      id: index,
      name: metric.label,
      encode: { y: metric.metric },
      itemStyle: {
        color: colorInfo.color,
        opacity: isSelected ? 1 : 0
      },
      lineStyle: {
        color: colorInfo.color,
        opacity: isSelected ? 1 : 0
      },
      areaStyle: option.series[index].type === 'line' ? {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: colorInfo.color + '53' },
          { offset: 1, color: colorInfo.color + '03' },
        ]),
        opacity: isSelected ? 1 : 0
      } : undefined,
    });

    opt.yAxis.push({
      ...option.yAxis[index], // 保留原有的轴配置
      id: index,
      name: metric.label,
      show: isSelected,
      axisLine: {
        show: isSelected,
        lineStyle: { color: colorInfo.color }
      }
    });

    // 更新图例
    opt.legend.selected[metric.label] = isSelected;
  });

  return opt;
}

export function getCompareDate(dateRange: string[]) {
  const start = dayjs(dateRange[0])
  const end = dayjs(dateRange[1])
  const days = end.diff(start, 'day')
  const preEnd = start.subtract(1, 'day')
  const preStart = preEnd.subtract(days, 'day')
  return [preStart.format('YYYY-MM-DD'), preEnd.format('YYYY-MM-DD')]
}

export function parseQueryParams(body: any) {
  const ret: any = {}
  for (const key in body) {
    const val = unref(body[key])
    if (key === 'dateRange') {
      ret['startDate'] = val[0]
      ret['endDate'] = val[1]
    } else {
      ret[key] = val
    }
  }
  return ret
}

export function getEnumLabel(enumObj: { label: string; value: string }[], value: any) {
  return enumObj.find((item) => item.value === value)?.label
}

export function getTagType(state){
    switch (state) {
      case 'ENABLED':
      case 'enabled':
        return 'success';  // 投放中或已开启
      case 'PAUSED':
      case 'paused':
        return 'warning';  // 已暂停
      case 'DISABLED':
        return 'danger';   // 禁用
      default:
        return 'info';  // 其他状态
    }
}
