// 根据颜色获取对应的hsv，在tinycolor中首先进行了归一化处理，这里没有
// 返回的结果h是0~360，代表的是色相的角度， sv的范围0-1
@function rbgToHsv($color) {
  $red: red($color);
  $green: green($color);
  $blue: blue($color);
  $max: max($red, $green, $blue);
  $min: min($red, $green, $blue);
  $diff: $max - $min;
  $h: 0;
  @if $max == $min {
    $h: 0;
  } @else if $max == $red {
    $h: 60 * ($green - $blue) / $diff + if($green >= $blue, 0, 360);
  } @else if $max == $green {
    $h: 60 * ($blue - $red) / $diff + 120;
  } @else if $max == $blue {
    $h: 60 * ($red - $green) / $diff + 240;
  }
  $s: if($max == 0, 0, $diff / $max);
  $v: $max / 255;
  @return $h, $s, $v;
}
// hsv转化成rgb，借鉴了tinycolor的做法，避免通过$th的值判断来获取对应的rgb的取值
// $t1~4的计算目前不清楚为什么这样做
@function hsvTorgb($h, $s, $v) {
  $th: floor($h / 60);
  $t1: $h / 60 - $th;
  $t2: $v * (1 - $s);
  $t3: $v * (1 - $t1 * $s);
  $t4: $v * (1 - (1 - $t1) * $s);
  $i: $th % 6 + 1;
  $r: nth(($v, $t3, $t2, $t2, $t4, $v), $i);
  $g: nth(($t4, $v, $v, $t3, $t2, $t2), $i);
  $b: nth(($t2, $t2, $t4, $v, $v, $t3), $i);
  @return rgb(round($r * 255), round($g * 255), round($b * 255));
}
// 求一个数的n次幂
@function pow($number, $n) {
  $ret: 1;
  @if $n >= 0 {
    @for $i from 1 through $n {
      $ret: $ret * $number;
    }
  } @else {
    @for $i from $n to 0 {
      $ret: $ret / $number;
    }
  }
  @return $ret;
}
// 浮点数保留小数位
@function toFixed($float, $digits: 2) {
  $pow: pow(10, $digits);
  @return round($float * $pow) / $pow;
}
//转换色相
@function getHue($h, $i, $isLight) {
  $hue: null;
  @if $h >= 60 and $h <= 240 {
    $hue: if($isLight, $h - $hueStep * $i, $h + $hueStep * $i);
  } @else {
    $hue: if($isLight, $h + $hueStep * $i, $h - $hueStep * $i);
  }
  $hue: ($hue + 360) % 360;
  @return round($hue);
}
// 转换饱和度
@function getSaturation($s, $i, $isLight) {
  $saturation: null;
  @if $isLight {
    $saturation: $s - $saturationStep1 * $i;
  } @else if $i == $darkColorCount {
    $saturation: $s + $saturationStep1;
  } @else {
    $saturation: $s + $saturationStep2 * $i;
  }
  $saturation: min($saturation, 1);

  @if $isLight and $i == $lightColorCount and $saturation > 0.1 {
    $saturation: 0.1;
  }
  $saturation: max($saturation, 0.06);
  @return toFixed($saturation, 2);
}
// 转换明度
@function getValue($v, $i, $isLight) {
  $value: min(
    if($isLight, $v + $brightnessStep1 * $i, $v - $brightnessStep2 * $i),
    1
  );
  @return toFixed($value, 2);
}
$hueStep: 2;
$saturationStep1: 0.16;
$saturationStep2: 0.05;
$brightnessStep1: 0.05;
$brightnessStep2: 0.15;
$lightColorCount: 5;
$darkColorCount: 4;

// 根据颜色和对应的色板位置，计算出对应的色板颜色
@function getColor($color, $index) {
  $isLight: if($index <= 6, true, false);
  $hsv: rbgToHsv($color);
  //这里将i转换成以主色为中心，两侧的i值逐渐增大
  $i: if(
    $isLight,
    $lightColorCount + 1 - $index,
    $index - $lightColorCount - 1
  );
  @return hsvTorgb(
    getHue(nth($hsv, 1), $i, $isLight),
    getSaturation(nth($hsv, 2), $i, $isLight),
    getValue(nth($hsv, 3), $i, $isLight)
  );
}
