export const adjustColor1 = (pcolor: string, lightness: number) => {
    // 去除颜色字符串中的 '#' 符号
    const color = pcolor.replace('#', '');

    // 将 16 进制颜色转换为 RGB 值
    const r = parseInt(color.substr(0, 2), 16);
    const g = parseInt(color.substr(2, 2), 16);
    const b = parseInt(color.substr(4, 2), 16);

    // 根据明度系数调整 RGB 值
    const adjustedR = Math.round(r * lightness);
    const adjustedG = Math.round(g * lightness);
    const adjustedB = Math.round(b * lightness);

    // 将调整后的 RGB 值转换回 16 进制颜色
    const newColor = '#' +
        ((1 << 24) + (adjustedR << 16) + (adjustedG << 8) + adjustedB)
            .toString(16)
            .slice(1);

    return newColor;
}

export const adjustColor = (pcolor, lightness=1, saturation=1) => {
    // 去除颜色字符串中的 '#' 符号
    const color = pcolor.replace('#', '');

    // 将 16 进制颜色转换为 RGB 值
    let r = parseInt(color.substr(0, 2), 16);
    let g = parseInt(color.substr(2, 2), 16);
    let b = parseInt(color.substr(4, 2), 16);

    // 将 RGB 值转换为 HSV 值
    let [h, s, v] = rgbToHsv(r, g, b);

    // 调整明度
    v *= lightness;

    // 调整饱和度
    s *= saturation;
    s = Math.max(0, Math.min(1, s)); // 确保饱和度在 [0, 1] 范围内

    // 将 HSV 值转换回 RGB 值
    [r, g, b] = hsvToRgb(h, s, v);

    // 将 RGB 值转换回 16 进制颜色
    const newColor = '#' +
        ((1 << 24) + (r << 16) + (g << 8) + b)
            .toString(16)
            .slice(1);

    return newColor;
}

// 将 RGB 值转换为 HSV 值
export const rgbToHsv = (r, g, b) => {
    r /= 255, g /= 255, b /= 255;
    let max = Math.max(r, g, b), min = Math.min(r, g, b);
    let h, s, v = max;

    let d = max - min;
    s = max === 0 ? 0 : d / max;

    if (max === min) {
        h = 0; // achromatic
    } else {
        switch (max) {
            case r: h = (g - b) / d + (g < b ? 6 : 0); break;
            case g: h = (b - r) / d + 2; break;
            case b: h = (r - g) / d + 4; break;
        }
        h /= 6;
    }

    return [h, s, v];
}

// 将 HSV 值转换为 RGB 值
export const hsvToRgb = (h, s, v) => {
    let r, g, b;

    let i = Math.floor(h * 6);
    let f = h * 6 - i;
    let p = v * (1 - s);
    let q = v * (1 - f * s);
    let t = v * (1 - (1 - f) * s);

    switch (i % 6) {
        case 0: r = v, g = t, b = p; break;
        case 1: r = q, g = v, b = p; break;
        case 2: r = p, g = v, b = t; break;
        case 3: r = p, g = q, b = v; break;
        case 4: r = t, g = p, b = v; break;
        case 5: r = v, g = p, b = q; break;
    }

    return [Math.round(r * 255), Math.round(g * 255), Math.round(b * 255)];
}

export const colorToHexString = (color)=>{
    let hexR = color.r.toString(16).padStart(2, '0');
    let hexG = color.g.toString(16).padStart(2, '0');
    let hexB = color.b.toString(16).padStart(2, '0');
    let hexA = color.a.toString(16).padStart(2, '0');
    return `#${hexR}${hexG}${hexB}${hexA}`;
}