import React, { Component } from 'react';
import { Popover } from 'antd';
import ColorPicker from './ColorPicker';
import './index.scss';

// 通用颜色拾取器
class ColorBtn extends Component<IColorBtnProps, IColorBtnState> {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      params: {}
    };
  }

  // 显隐切换
  changeVisible = (visible:boolean) => {
    const { footer, handleOk } = this.props;
    this.setState({
      visible: visible
    });

    // 当隐藏颜色拾取器，并且footer未设置时，触发确认回调函数
    if (!visible && !footer) {
      typeof handleOk === 'function' && handleOk(this.state.params);
    }
  };

  // 回调函数，更新最终返回参数
  handleParams = (params) => {
    this.setState({
      ...params
    });
  };

  render() {
    const {
      value = '',
      placement = 'bottom',
      destroyTooltipOnHide = true,
      children,
      ...rest
    } = this.props;

    return (
      <Popover
        placement={placement}
        destroyTooltipOnHide={destroyTooltipOnHide}
        visible={this.state.visible}
        overlayClassName={`colorPopover`}
        content={
          <ColorPicker
            value={value}
            handleParams={this.handleParams}
            {...rest}
          />
        }
        trigger="click"
        onVisibleChange={this.changeVisible}
      >
        {children || <div className="widgetBtn" />}
      </Popover>
    );
  }
}

export default ColorBtn;

export interface IColorBtnProps {
  footer?: IFooter;
  handleOk: Function;
  value?: string;
  placement?: string;
  destroyTooltipOnHide?: boolean;
}

export interface IFooter {
  okText?: string;
  cancelText?: string;
}

export interface IColorBtnState {
  params: IParams;
  visible: boolean;
}

export interface IParams{
  [key: string]: string | number | boolean | object|any;
}