import React from 'react'
import { Input } from 'antd'
import { RGBToHex, HexToRGB } from '../../../utils/baseUtils'
import ColorPicker from 'rc-color-picker'
import 'rc-color-picker/assets/index.css'
import './index.less'

class InputColorPicker extends React.Component {
    render() {
        const { placeholder, value, onChange } = this.props;
        let colorHex, alpha;

        if((value + '').match(/^#/)) {
            if(value.length > 3) {
                colorHex = value;
            }
            alpha = 100;
        }else if(!!(value + '').match(/^rgb[a]{0,1}\(/i)) {
            let arr = value.split(/[(,)]/),
                colorRGB = 'RGB(' + (Number((arr[1] || '').trim()) || 0) + ',' + (Number((arr[2] || '').trim()) || 0) + ',' + (Number((arr[3] || '').trim()) || 0) + ',' + (Number((arr[4] || '').trim()) || 1) * 100 + ')'
            colorHex = RGBToHex(colorRGB);
            alpha = (Number((arr[4] || '').trim()) || 1) * 100;
        }
        return <div className='colorpicker-wrap'>
            <Input ref={node => this.inputRef = node} placeholder={placeholder} value={value} onChange={e => {
                typeof onChange === 'function' && onChange(e.target.value);
            }}/>
            <ColorPicker
                animation="slide-up"
                color={colorHex}
                alpha={alpha}
                onChange={(colors) => {
                    const { alpha, color: colorHex } = colors;
                    let color = colorHex;
                    if(alpha !== 100) {
                        color = HexToRGB(colorHex, alpha)
                    }
                    this.inputRef.value = color;
                    typeof onChange === 'function' && onChange(color)
                }}
            />
        </div> 
    }
}
export default InputColorPicker