/**
 * 多选日历
 * Created by Gentean
 * Mail: 4083189@qq.com
 * Date: 2016/12/30
 * Time: 下午2:32
 */
import React from 'react'
import { message } from "antd";
import moment from 'moment';
require("./MultipleDatePicker.less");
class MultipleDatePicker extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      calendar: "",
      calendarDate: props.type ? moment(props.startTime):moment(),
      detailList: [],
      waitNoticeNumber: 0,
      totalCount: 0,
      selectDateList: props.selectDateList || [],
      endTime: props.endTime || null,
      startTime: props.startTime || null,
      homeworkProcessEnum: props.homeworkProcessEnum || ''
    };
  }

  componentWillReceiveProps(nextProps) {
    this.setState({endTime : nextProps.endTime,  startTime: nextProps.startTime, selectDateList: nextProps.selectDateList, homeworkProcessEnum:nextProps.homeworkProcessEnum},() => {
      this.handleQuery();
    });
  }
  
  componentDidMount() {
    this.handleQuery();
  }

  handleQuery() {
    var self = this;
    self.setState({
      calendar: self.renderCalendar(),
    });
  }

  renderCalendar() {
    var start = moment(this.state.calendarDate).startOf("month"),
      startDay = start.dates(),
      // 每月的第一天是星期几 [0-6] 6:日
      startWeekOf = start.weekday();
    var end = moment(this.state.calendarDate).endOf("month"),
      endDay = end.dates(),
      endWeekOf = end.weekday();
    var dateElms = [];
    // 上月余留的天
    var prevMonthDays = moment(start).subtract("month", 1).endOf("month"),
      prevMonthDaysNumber = prevMonthDays.dates();
    for (
      var j = prevMonthDaysNumber - startWeekOf + 1, i = 0;
      i < startWeekOf;
      i++, j++
    ) {
      var time = moment(prevMonthDays).subtract("days", startWeekOf - 1 - i);
      dateElms.push(
        <li className={"disabled"} key={"before" + i}>
          <span>{j}</span>
        </li>
      );
    }

    // 本月
    for (var i = startDay; i <= endDay; i++) {
      var time = moment(start).add("days", i - 1);
      var className = "";
      if(!this.props.canSelectTodayBefore && time.valueOf() < moment().valueOf() && time.format("YYYY-MM-DD") != moment().format("YYYY-MM-DD")) {
        className = 'before-disabled'
      }
      // 今日待跟进
      if (time.format("YYYY-MM-DD") == moment().format("YYYY-MM-DD")) {
        className += " today";
      }
      
      if (this.state.selectDateList.indexOf(time.valueOf()) > -1) {
        className += " active";
        const today = moment().startOf('day').valueOf();
        if(this.props.type && this.props.type == 'CALENDAR_CLOCK' && (time.valueOf() < today) && this.state.homeworkProcessEnum == 'ONGOING') {
          className += " past";
        }
      }
      if(this.state.startTime && this.state.endTime && (time.valueOf() > this.state.endTime.valueOf() || time.valueOf() < this.state.startTime.valueOf())) {
        className += " disabled"
      }

      dateElms.push(
        <li
          className={className}
          key={"curr" + i}
          onClick={this.handleShowDetail.bind(this, time, className)}
        >
          <span>{i}</span>
        </li>
      );
      
    }

    // 下月预来的天
    for (var j = 1, i = endWeekOf; i < 6; i++, j++) {
      var time = moment(end).add("days", i);
      dateElms.push(
        <li className={"disabled"} key={"after" + i}>
          <span>{j}</span>
        </li>
      );
    }
    return dateElms;
  }

  handleShowDetail(time, className) {
    if(!this.props.canSelectTodayBefore && className === 'before-disabled') {
      return 
    }
    let date = time.valueOf();
    const today = moment().startOf('day').valueOf();
    if(this.props.type && this.props.type == 'CALENDAR_CLOCK' && (date < today))  {
      return;
    }
    if(this.state.homeworkProcessEnum == 'ONGOING' && date == today) {
      return;
    }
    if(this.props.type && this.props.type == 'CALENDAR_CLOCK' && this.state.startTime && this.state.endTime && (date > this.state.endTime.valueOf() || date < this.state.startTime.valueOf())) {
      return;
    }
    let tempArr = this.state.selectDateList;

    if (tempArr.indexOf(date) > -1) {
      let index = tempArr.indexOf(date);
      tempArr.splice(index, 1);
    } else {
      if (tempArr.length > 29  && !this.props.type) {
        message.warning("最多选择30天");
        return;
      } else {
        tempArr.push(date);
      }
    }
    this.props.onSelect(tempArr);
    this.setState(
      {
        selectDateList: tempArr,
      },
      () => {
        this.handleQuery();
      }
    );
  }

  render() {
    const self = this;
    const {calendarDate, endTime,startTime } = this.state;
    const { type} = this.props;
    const prevMonth = startTime && calendarDate.subtract("month", 1).endOf('month').valueOf() < startTime.valueOf();
    const nextMonth = !(endTime && calendarDate.add("month", 1).valueOf() < endTime.valueOf());
    return (
      <div
        className={`multiple-calendar ${
          type == "CALENDAR_CLOCK" ? "punch-calender" : ""
        }`}
      >
        {type == "CALENDAR_CLOCK" ? (
          <div className="punch-control">
            <div className="punch-main">
              <div
                onClick={function () {
                  if(prevMonth){return}
                  this.state.calendarDate = this.state.calendarDate.subtract(
                    "month",
                    1
                  );
                  self.handleQuery();
                }.bind(this)}
                className={`prev-icon ${prevMonth?'disbled-icon':''}`}
              >
                <span className="icon iconfont">&#xe65f;</span>
              </div>
              <span className="month">{this.state.calendarDate.format("YYYY年MM月")}</span>
              <div
              className={`next-icon ${nextMonth?'disbled-icon':''}`}
                onClick={function () {
                  if(nextMonth){return}
                  this.state.calendarDate = this.state.calendarDate.add(
                    "month",
                    1
                  );
                  self.handleQuery();
                }.bind(this)}
              >
                <span className="icon iconfont">&#xe65e;</span>
              </div>
            </div>
            <div
            className="self"
              onClick={function () {
                this.state.calendarDate = moment(startTime);
                self.handleQuery();
              }.bind(this)}
            >
              回到起始月
            </div>
          </div>
        ) : (
          <div className="t-control">
            <div
              className="prev"
              onClick={function () {
                this.state.calendarDate = this.state.calendarDate.subtract(
                  "month",
                  1
                );
                self.handleQuery();
              }.bind(this)}
            >
              上月
            </div>
            <div className="loc">
              {this.state.calendarDate.format("YYYY年MM月")}
            </div>
            <div
              className="self"
              onClick={function () {
                this.state.calendarDate = moment();
                self.handleQuery();
              }.bind(this)}
            >
              本月
            </div>
            <div
              className="next"
              onClick={function () {
                this.state.calendarDate = this.state.calendarDate.add('month', 1);
                self.handleQuery()
              }.bind(this)}
            >
              下月
            </div>
          </div>
        )}
        <ul className="week">
          <li>一</li>
          <li>二</li>
          <li>三</li>
          <li>四</li>
          <li>五</li>
          <li>六</li>
          <li>日</li>
        </ul>
        <ul className="calendar" id="multiCalendar">
          {this.state.calendar}
        </ul>
      </div>
    );
  }
}

MultipleDatePicker.propTypes = {};

MultipleDatePicker.defaultProps = {
  reEditUrl: "",
  close: function () {},
  canSelectTodayBefore: true // 支持选择今天之前的日期
};

export default MultipleDatePicker;
