import React from 'react';
import { SketchPicker } from 'react-color';
import { Popover } from 'antd';
import IconFont from '../../themeComponents/IconFont';
import './index.less';

class SketchPickerForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: props.value || props.defaultValue
    };
  }
  static getDerivedStateFromProps(nextProps) {
    if ('value' in nextProps) {
      return {
        ...(nextProps.value || {})
      };
    }
    return null;
  }
  shouldComponentUpdate(nextProps) {
    if ('value' in nextProps && this.state.value !== nextProps.value) {
      this.setState({ value: nextProps.value || '' });
    }
    return true;
  }
  onChange = color => {
    const { r, g, b, a } = color.rgb;
    const value = `rgba(${r},${g},${b},${a})`;
    this.setState({ value });
    this.props.onChange && this.props.onChange(value);
  };
  clearColor = () => {
    this.setState({ value: '' });
    this.props.onChange && this.props.onChange('');
  };
  render() {
    const { value } = this.state;
    return (
      <Popover
        trigger="click"
        overlayClassName="lm-sketch-picker-popup"
        content={<SketchPicker width={250} color={getRGBA(value)} onChange={this.onChange} className="lm-sketch-picker"></SketchPicker>}
      >
        <span className="lm-color-picker-box" style={{ width: this.props.width }}>
          <span className="color-box" style={{ backgroundColor: value }}>
            {!value ? this.props.placeholder : value}
          </span>
          {this.props.hasClear && value && (
            <span className="delete-color" onClick={this.clearColor}>
              清除<IconFont type="icon-S_Edit_LineClose"></IconFont>
            </span>
          )}
        </span>
      </Popover>
    );
  }
}

function getRGBA(color) {
  if (!color) {
    return {
      r: 0,
      g: 0,
      b: 0,
      a: 1
    };
  }
  const rgba = color
    .toLowerCase()
    .replace('rgba(', '')
    .replace(')', '')
    .split(',');
  return {
    r: rgba[0],
    g: rgba[1],
    b: rgba[2],
    a: rgba[3]
  };
}

export default SketchPickerForm;
