import React, { PureComponent } from 'react';
import moment from 'moment';
import { DatePicker } from 'antd';
const { RangePicker } = DatePicker;

type PickerProps = {
    onPanelChange: Function;
    disabledChange?: (value: moment.Moment[]) => boolean;
    [propName: string]: any;
}
export default class MonthRangePicker extends PureComponent<PickerProps>{
    state: {
        value: any[],
        open: boolean,
    };
    constructor(props){
        super(props);
        this.state = {
            value: props.defaultValue || [],
            open: false,
        };
    }
    onPanelChange = (val, mode) => {
        const { onPanelChange, disabledChange } = this.props;
        const { value } = this.state;
        this.setState({ value: val });
        if (!(disabledChange && disabledChange(val))) { // disabledChange()返回true时为disabled选项
            if (val[0] == value[0]) { // 换而言之：当改变的是结束月份的时间时，关闭面板，抛出value(因为每次点击start或者end，对应的值都是不等的)   
                this.setState({ open: false });
                onPanelChange(val)
            }
        }
    };

    onOpenChange = status => {
        const { onPanelChange, disabledChange } = this.props;
        const { value } = this.state;
        if (!status) { // 当手动关闭面板时，先判断选择时间是否在允许范围内，是则抛出value
            if (!(disabledChange && disabledChange(value))) {
                this.setState({ open: status });
                onPanelChange(value)
            }
        } else { // 打开面板时
            this.setState({ open: status });
        }

    };

    render() {
        const { value, open } = this.state;
        const { onPanelChange, disabledChange, ...restProps } = this.props;
        
        return (
            <RangePicker
                format="YYYY-MM"
                mode={['month', 'month']}
                placeholder={['开始月份', '结束月份']}
                open={open}
                value={value}
                onPanelChange={this.onPanelChange}
                onOpenChange={this.onOpenChange}
                allowClear={false}
                style={{ width: 230 }}
                {...restProps}
            />
        );
    }
}