// 工具类函数
// 输入hex颜色值或rgba 颜色值 与 alpha值，返回rgba颜色值
export const applyAlphaToColor = (color, alpha = 1) => {
  if (!color || alpha === 1) return color;
  const s = color.trim();

  const hex3 = /^#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])$/i.exec(s);
  if (hex3) {
    const r = parseInt(hex3[1] + hex3[1], 16);
    const g = parseInt(hex3[2] + hex3[2], 16);
    const b = parseInt(hex3[3] + hex3[3], 16);
    return `rgba(${r}, ${g}, ${b}, ${Number(alpha)})`;
  }

  const hex6 = /^#([0-9a-fA-F]{6})$/i.exec(s);
  if (hex6) {
    const h = hex6[1];
    const r = parseInt(h.slice(0, 2), 16);
    const g = parseInt(h.slice(2, 4), 16);
    const b = parseInt(h.slice(4, 6), 16);
    return `rgba(${r}, ${g}, ${b}, ${Number(alpha)})`;
  }

  const hex8 = /^#([0-9a-fA-F]{8})$/i.exec(s);
  if (hex8) {
    const h = hex8[1];
    const r = parseInt(h.slice(0, 2), 16);
    const g = parseInt(h.slice(2, 4), 16);
    const b = parseInt(h.slice(4, 6), 16);
    return `rgba(${r}, ${g}, ${b}, ${Number(alpha)})`;
  }

  const rgb = /^rgb\s*\(([^)]+)\)$/i.exec(s);
  const rgba = /^rgba\s*\(([^)]+)\)$/i.exec(s);
  if (rgba || rgb) {
    const parts = (rgba ? rgba[1] : rgb[1]).split(',').map(p => p.trim());
    const r = parts[0] || '0';
    const g = parts[1] || '0';
    const b = parts[2] || '0';
    return `rgba(${r}, ${g}, ${b}, ${Number(alpha)})`;
  }

  return color;
};