/** ele admin pro theme util license by http://eleadmin.com */
import {generate} from '@ant-design/colors';
import {TinyColor} from '@ctrl/tinycolor';

/**
 * 切换主题色
 * @param color 颜色值
 * @param dark 是否暗黑模式
 */
export function changeColor(color, dark) {
  const id = `ele-admin-theme-var`, elem = document.getElementById(id);
  if (elem && elem.parentNode) {
    elem.parentNode.removeChild(elem);
  }
  if (color) {
    const colors = generate(color, dark ? {theme: 'dark'} : {}),
      rgb = new TinyColor(color).toRgb(),
      clazz = dark ? '.ele-admin-theme-dark' : ':root',
      elem = document.createElement('style');
    elem.id = id;
    elem.setAttribute('type', 'text/css');
    elem.innerHTML = `${clazz}{` + colors.map((c, i) => {
      return `--primary-${i + 1}:${c};`;
    }).concat([
      `--primary-color:${color};`,
      `--primary-fade-8:rgba(${rgb.r},${rgb.g},${rgb.b},.08);`,
      `--primary-fade-20:rgba(${rgb.r},${rgb.g},${rgb.b},.2);`
    ]).join('') + '}';
    document.head.appendChild(elem);
  }
  if (dark) {
    document.body.classList.add('ele-admin-theme-dark');
  } else {
    document.body.classList.remove('ele-admin-theme-dark');
  }
}
