/* eslint-disable no-restricted-syntax */
export function percentageFormat(value) {
  const number = Number(value);
  if (Number.isNaN(number)) {
    return value;
  }
  if (number === -1) {
    return '';
  }
  return `${Math.round(number * 10000) / 100}%`;
}

export function keepDecimals(value, digit = 2) {
  const number = Number(value);
  if (Number.isNaN(number)) {
    return value;
  }
  const temp = 10 ** digit;
  return Math.round(number * temp) / temp;
}

export function numberOfDigit(number) {
  let temp = Math.abs(number);
  let result = 0;
  while (temp >= 1) {
    temp /= 10;
    result += 1;
  }
  return result;
}

export function getLetterByNumber(number) {
  return String.fromCharCode(65 + number);
}

export function getLabelMapFromList(list) {
  const map = new Map();
  list.forEach(x => {
    map.set(x.value, x.label);
  });
  return map;
}

export function standardizeValue(val) {
  if (!val || val === -1) {
    return 0;
  }
  return val;
}

export const colors = [
  '#5B8FF9',
  '#5AD8A6',
  '#5D7092',
  '#F6BD16',
  '#E86452',
  '#6DC8EC',
  '#945FB9',
  '#FF9845',
  '#1E9493',
  '#FF99C3',
  '#43D0CB',
  '#6F6DA9',
  '#A3CE4E',
  '#E85288',
  '#876DEC',
  '#9E5F7E',
];

export const tooltipMarkColor = '#4B5CF0';

export function getRGBAColor(color, opacity = 1) {
  const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
  let newColor = color;
  if (reg.test(color)) {
    // 如果只有三位的值，需变成六位，如：#fff => #ffffff
    if (color.length === 4) {
      newColor = '#';
      for (let i = 1; i < 4; i += 1) {
        newColor += color.slice(i, i + 1).concat(color.slice(i, i + 1));
      }
    }
    // 处理六位的颜色值，转为RGB
    const colorChange = [];
    for (let i = 1; i < 7; i += 2) {
      colorChange.push(parseInt(newColor.slice(i, i + 2), 16));
    }
    return `rgba(${colorChange.join(',')},${opacity})`;
  }
  const match = /^rgb\((.*)\)$/.exec(color);
  if (match?.[1]) {
    return `rgba(${match[1]},${opacity})`;
  }
  return color;
}
