import _ from 'lodash';
import * as echarts from 'echarts/core';
import { globalConfig } from './global';

const BASE_COLORS = [
  '#1685ff',
  '#00b809',
  '#ffa200',
  '#00d0c7',
  '#ff6b37',
  '#986aff',
  '#2f54eb',
  '#ff9e69',
  '#ffcb66',
  '#99ceff',
];

const THEME_LIST = {
  '#009C73': ['#01AA55', '#1685FF', '#FFB424', '#19D2BA', '#5842FF'],
  '#0087F7': BASE_COLORS,
  '#1890FF': BASE_COLORS,
};

const THEME = window.globalConfig?.variableTheme?.primaryColor;

/**
 * 16进制颜色值转rgba颜色值
 *
 * @param {string} hex 16进制颜色值
 * @param {number} opacity 透明度，缺省默认为1
 * @returns Rgba颜色值
 */
export const hexToRgba = (hex, opacity = 1) => {
  let result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return `rgba(${parseInt(result[1], 16)},${parseInt(result[2], 16)},${parseInt(
    result[3],
    16,
  )}, ${opacity})`;
};

// 图表基础配色
export const DEF_COLORS = THEME ? THEME_LIST[THEME] || BASE_COLORS : BASE_COLORS;

// 图表基础配色对应的线性渐变色, 适用面积曲线图
export const DEF_GRAD_COLORS = DEF_COLORS.map((color) => {
  return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    {
      offset: 0,
      color: hexToRgba(color, 0.2),
    },
    {
      offset: 1,
      color: hexToRgba(color, 0.02),
    },
  ]);
});

/**
 * 根据系列的序列下标获取对应的颜色
 *
 * @param {number} index 系列所在的下标
 * @param {Array} colors 配色方案
 * @returns 颜色值，可以是16进制, rgb, LinearGradient
 */
export const colorOfSeries = (index, colors) => {
  colors = colors || buildDefaultColors();
  return colors[index % colors.length];
};

export const toGRADColorForLine = (color) => {
  return new echarts.graphic.LinearGradient(0, 0, 0, 1, [
    {
      offset: 0,
      color: hexToRgba(color, 0.2),
    },
    {
      offset: 1,
      color: hexToRgba(color, 0.02),
    },
  ]);
};

export const buildDefaultColors = () => {
  const primaryColor = globalConfig.primaryColor;
  return primaryColor ? THEME_LIST[primaryColor] || BASE_COLORS : BASE_COLORS;
};

export const buildDefaultGRADColors = () => {
  const colors = buildDefaultColors();
  return colors.map((color) => toGRADColorForLine(color));
};
