import {DatePicker} from 'antd';
import moment from 'moment';
import React from 'react';

const monthFormat = 'YYYY-MM';

class MonthPicker extends React.Component {
  // state = {
  //   mode: ['month', 'month'],
  //   value: [],
  // };

  constructor(props) {
    super(props);
    // console.log('ttttttttttttttttttttttttt', props.value);
    const {value} = this.props
    this.state = {
      mode: ['month', 'month'],
      value: value ? value.map(m => moment(m, monthFormat)) : [],
    };
  }

  componentWillReceiveProps = (nextProps) => {
    // console.log('componentWillReceiveProps', nextProps.value, this.props.value);
    const {value} = nextProps
    if (nextProps.value != this.props.value) {
      this.setState({
        value: value ? value.map(m => moment(m, monthFormat)) : [],
      });
    }
  };

  handlePanelChange = (value, mode) => {
    // console.warn('handle change', value)
    this.props.onChange(value);
    this.setState({
      value,
      mode: [
        mode[0] === 'date' ? 'month' : mode[0],
        mode[1] === 'date' ? 'month' : mode[1],
      ],
    });
  };

  render() {
    const {mode, value} = this.state;
    // const { value } = this.props;
    return (
      // TODO 暂时没有找到clear事件的回调方法
      <DatePicker.RangePicker
        allowClear={false}
        placeholder={['开始月份', '结束月份']}
        format="YYYY-MM"
        value={value}
        mode={mode}
        onPanelChange={this.handlePanelChange}
      />
    );
  }
}

export default MonthPicker;
