import React, { Component } from "react";
import ReactWordCloud from "react-wordcloud";

// 工具函数：生成渐变颜色
function generateGradientColors(startColor, endColor, steps) {
  function hexToRgb(hex) {
    const r = parseInt(hex.slice(1, 3), 16);
    const g = parseInt(hex.slice(3, 5), 16);
    const b = parseInt(hex.slice(5, 7), 16);
    return [r, g, b];
  }

  function rgbToHex([r, g, b]) {
    return (
      "#" +
      r.toString(16).padStart(2, "0") +
      g.toString(16).padStart(2, "0") +
      b.toString(16).padStart(2, "0")
    );
  }

  const [r1, g1, b1] = hexToRgb(startColor);
  const [r2, g2, b2] = hexToRgb(endColor);

  const colors = [];
  for (let i = 0; i < steps; i++) {
    const t = i / (steps - 1);
    const r = Math.round(r1 + (r2 - r1) * t);
    const g = Math.round(g1 + (g2 - g1) * t);
    const b = Math.round(b1 + (b2 - b1) * t);
    colors.push(rgbToHex([r, g, b]));
  }
  return colors;
}

class WordCloud extends Component {
  render() {
    const { data } = this.props;
    // 根据索引生成 words，索引越小，value 越大
    const words = data.map((item, idx) => ({
      text: item,
      value: data.length - idx // 越小索引值越大
    }));

    const colors = generateGradientColors("#7ECEF4", "#4032A6", words.length);

    const options = {
      spiral: "archimedean",
      fontFamily: "sans-serif",
      fontSizes: [20, 80], // 控制字体范围
      fontWeight: 'bold',
      rotations: 0,
      scale: "sqrt",
      padding: 10,
      colors,
      enableTooltip: false,
    };

    return (
      <div style={{ width: "100%", height: "100%" }}>
        <ReactWordCloud words={words} options={options} />
      </div>
    );
  }
}

export default WordCloud;
