/**
 * @file index
 * @author lvzhiyi
 *
 * 包含两中类型的开关组件 Switch CheckBox
 */
import React, { Component } from 'react';
import classNames from 'classnames';
import Icon from '../../Icon/index';
import './index.styl';

interface Props {
    checked: boolean;
    type: string;
    onChange: React.ReactEventHandler<EventTarget>;
}

class Switch extends Component<Props, any> {
    /**
     * 开关类型，默认Switch
     *
     * type: String;
     */
    /**
     * 开关状态，默认选中
     *
     * checked: bool;
     */
    /**
     * 点击开关回调，
     *
     * onChange: () => {};
     */

    static defaultProps = {
        checked: true,
        type: 'switch'
    };
    constructor(props: Props) {
        super(props);
        this.state = {
            checked: this.props.checked
        };
    }

    checkedChange = (value: any) => {
        this.props.onChange(value);
    };

    componentWillReceiveProps({ checked }: any) {
        this.setState({ checked });
    }

    render() {
        const { checked } = this.state;
        const { type } = this.props;
        const swichClass = classNames({
            'switch-main': true,
            'checked-true': checked,
            'checked-false': !checked
        });
        return type === 'switch' ? (
            <div className={swichClass}>
                <div
                    className="switch-dot"
                    onTouchStart={this.checkedChange.bind(this, checked)}
                />
            </div>
        ) : (
            <div
                className="checked-box"
                onTouchStart={this.checkedChange.bind(this, checked)}
            >
                {checked ? (
                    <Icon type="xuanzhongduigou" />
                ) : (
                    <Icon type="unchecked" />
                )}
            </div>
        );
    }
}

export default Switch;
