import React, { useState, useEffect } from 'react';
import { InputNumber } from 'antd';
import './index.scss';

/**
 * 渐变颜色拾取器
 * @param current 位置
 * @param color 颜色--数组（包含两项）
 * @param angle 角度（-360～360）
 * @param handleChange 变更回调函数
 * @return {*}
 * @constructor
 */
const GradientColorPicker = ({
  current = 0,
  color = [],
  angle = 0,
  handleChange
}: IGradientColorPicker) => {
  const [curPos, setCurPos] = useState<number>(current);
  const [gradientAngle, setGradientAngle] = useState<number>(angle);
  const start = color?.[0] ?? '#5B8FF9';
  const end = color?.[1] ?? '#5B8FF9';

  const gradientNodes = [
    {
      key: 'start',
      name: '起点',
      pos: 0,
      background: start,
      active: curPos === 0
    },
    {
      key: 'block',
      name: '背景块',
      background: `linear-gradient(${gradientAngle + 90}deg, ${start}, ${end})`
    },
    {
      key: 'end',
      name: '起点',
      pos: 1,
      background: end,
      active: curPos === 1
    }
  ];

  useEffect(() => {
    setGradientAngle(angle);
  }, [angle]);

  // 选择需要修改的起始位置
  const choosePos = (val:number) => {
    setCurPos(val);
    typeof handleChange === 'function' && handleChange({ position: val });
  };

  // 修改角度
  const changeAngle = (val:number) => {
    val = val && typeof Number(val) === 'number' ? val : angle;
    setGradientAngle(val);
    typeof handleChange === 'function' && handleChange({ angle: val });
  };

  return (
    <div className="gradient">
      <div className="gradientColor">
        {gradientNodes.map((item) => (
          <span
            key={item.key}
            className={curPos === item.pos ? 'active' : ''}
            style={{ background: item.background }}
            onClick={() => choosePos(item.pos)}
          />
        ))}
      </div>
      <div className="angle">
        <label>角度</label>
        <InputNumber
          defaultValue={angle}
          min={0}
          max={360}
          onChange={changeAngle}
        />
      </div>
    </div>
  );
};

export default GradientColorPicker;

export interface IGradientColorPicker {
  current: number;
  color: string[];
  angle: number;
  handleChange: Function;
}
