/**
 * imui.monthPicker - Picker
 * @author riverhan
 * @date 2017-2-19
 */

import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import YearOper from './YearOper';
import Month from './Month';
import { getPureDate, getDayOfOffsetYear } from '../../datepicker/lib/dateUtils';

let onClickOutside = require('react-onclickoutside');

class Picker extends React.Component {
  static propTypes = {
    handleChangeYear: PropTypes.func, // 切换年份时的回调函数
  };

  static defaultProps = {

  };

  state = {
    day: getPureDate(this.props.day)
  };

  componentWillReceiveProps(nextProps) {
    if (nextProps.day.valueOf() !== this.props.day.valueOf()) {
      this.setState({
        day: getPureDate(nextProps.day)
      });
    }
  }

  increaseYear = () => {
    const nextYearDate = getDayOfOffsetYear(this.state.day, 1);

    this.setState({
      day: nextYearDate
    });
    this.props.onChangeYear(new Date(nextYearDate), new Date(this.state.day));
  };

  decreaseYear = () => {
    const prevYearDate = getDayOfOffsetYear(this.state.day, -1);

    this.setState({
      day: prevYearDate
    });
    this.props.onChangeYear(new Date(prevYearDate), new Date(this.state.day));
  };

  handleMonthClick = (month) => {
    this.props.onSelect(month);
  };

  handleClickOutside = () => {
    this.props.handleClickOutPicker();
  };

  render() {
    const { inline, pickerZindex, show } = this.props;
    let styleObj = {};

    if (pickerZindex) {
      styleObj.zIndex = pickerZindex;
    }

    return (
      <div
        className={classnames({
          'im-mp-picker': true,
          'im-mp-picker--inline': inline,
          hide: !show && !inline
        })}
        style={styleObj}
      >
        <YearOper
          {...this.state}
          onClickNextYear={this.increaseYear}
          onClickPrevYear={this.decreaseYear}
        />
        <Month
          {...this.props}
          {...this.state}
          onMonthClick={this.handleMonthClick}
        />
      </div>
    );
  }
}

export default onClickOutside(Picker);
