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

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]
    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
    }
  }
  console.log(opt)
  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
}
