import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _slicedToArray from 'babel-runtime/helpers/slicedToArray';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
var _jsxFileName = 'src/datePicker/dateItem.jsx';
import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import YearPanel from './panel/yearPanel';
import MonthPanel from './panel/monthPanel';
import DatePanel from './panel/datePanel';
import dateConfig from './dateConfig';
import parseTime from './parseTime';
import timeToString from '../util/timeToString';
import pubsub from '../util/observer';

/**
 * @ignore
 * */

var DtItem = function (_React$PureComponent) {
    _inherits(DtItem, _React$PureComponent);

    function DtItem(props) {
        _classCallCheck(this, DtItem);

        var _this = _possibleConstructorReturn(this, (DtItem.__proto__ || Object.getPrototypeOf(DtItem)).call(this, props));

        _initialiseProps.call(_this);

        var newDate = moment();
        var _this$props = _this.props,
            currentTime = _this$props.currentTime,
            datePickerKey = _this$props.datePickerKey,
            showTime = _this$props.showTime,
            type = _this$props.type;

        _this.state = {
            currentDate: newDate,
            currentYear: newDate.year(),
            currentMonth: newDate.month() + 1,
            currentDay: newDate.day(),
            monthDaysArray: [],
            selectType: 'select-day',
            curDecadeyears: [],
            timePanel: showTime,
            datePanel: true,
            selectHour: timeToString(moment(currentTime).hour()),
            selectMinute: timeToString(moment(currentTime).minute()),
            selectSecond: timeToString(moment(currentTime).second()),
            disableDaysBtn: false,
            disableMonthsBtn: false,
            disableYearsBtn: false
        };
        var subscribeType = 'begin';
        var publishType = 'end';
        if (type.match('begin')) {
            subscribeType = 'end';
            publishType = 'begin';
        }
        _this.pubsubEvent = {
            subscribePickerKey: subscribeType + '-' + datePickerKey,
            publishPickerKey: publishType + '-' + datePickerKey,
            subscribeEqual: 'equal-' + subscribeType + '-' + datePickerKey,
            publishEqual: 'equal-' + publishType + '-' + datePickerKey
        };
        _this.count = 1;
        return _this;
    }

    _createClass(DtItem, [{
        key: 'componentDidMount',
        value: function componentDidMount() {
            var _this2 = this;

            var _props = this.props,
                currentTime = _props.currentTime,
                selectType = _props.selectType,
                switchType = _props.switchType;
            var _pubsubEvent = this.pubsubEvent,
                subscribePickerKey = _pubsubEvent.subscribePickerKey,
                subscribeEqual = _pubsubEvent.subscribeEqual,
                publishEqual = _pubsubEvent.publishEqual,
                publishPickerKey = _pubsubEvent.publishPickerKey;

            if (switchType === 'date-range-unity') {
                pubsub.subscribe(subscribePickerKey, function (event, args) {
                    var currentMonth = args.currentMonth,
                        currentYear = args.currentYear;

                    var disableDaysBtn = void 0;
                    var disableMonthsBtn = void 0;
                    var disableYearsBtn = void 0;
                    if (currentYear === _this2.state.currentYear) {
                        disableMonthsBtn = true;
                        disableYearsBtn = true;
                        if (currentMonth === _this2.state.currentMonth) {
                            disableDaysBtn = true;
                        }
                    }
                    pubsub.publish(publishEqual, { disableMonthsBtn: disableMonthsBtn, disableYearsBtn: disableYearsBtn, disableDaysBtn: disableDaysBtn });
                    _this2.setState({
                        disableDaysBtn: disableDaysBtn,
                        disableMonthsBtn: disableMonthsBtn,
                        disableYearsBtn: disableYearsBtn
                    });
                });
                pubsub.subscribe(subscribeEqual, function (event, args) {
                    var disableMonthsBtn = args.disableMonthsBtn,
                        disableYearsBtn = args.disableYearsBtn,
                        disableDaysBtn = args.disableDaysBtn;

                    _this2.setState({
                        disableDaysBtn: disableDaysBtn,
                        disableMonthsBtn: disableMonthsBtn,
                        disableYearsBtn: disableYearsBtn
                    });
                });
            }
            pubsub.publish(publishPickerKey, {
                currentMonth: this.state.currentMonth,
                currentYear: this.state.currentYear
            });
            this.initPanel(currentTime, selectType);
        }
    }, {
        key: 'componentWillReceiveProps',
        value: function componentWillReceiveProps(props) {
            var currentTime = props.currentTime,
                selectType = props.selectType;

            if (currentTime === this.props.currentTime && selectType === this.props.selectType) {
                return;
            }
            this.initPanel(currentTime, selectType);
        }

        //载入重渲染每月天数数据


        // 向上切换年月日面板


        // 展示年


        // 渲染年份


        // 选择年份


        // 选择月份


        // 选择天

    }, {
        key: 'render',
        value: function render() {
            var _this3 = this;

            var _props2 = this.props,
                className = _props2.className,
                beginTime = _props2.beginTime,
                endTime = _props2.endTime,
                format = _props2.format,
                showTime = _props2.showTime,
                prefixCls = _props2.prefixCls,
                datePickerType = _props2.datePickerType,
                componentType = _props2.componentType,
                local = _props2.local,
                type = _props2.type,
                disabledAfterDate = _props2.disabledAfterDate,
                disabledBeforeDate = _props2.disabledBeforeDate,
                disableTime = _props2.disableTime,
                disableExquisiteTimeRules = _props2.disableExquisiteTimeRules;
            var _dateConfig$local = dateConfig[local],
                days = _dateConfig$local.days,
                months = _dateConfig$local.months;

            var dateItemPrefixCls = prefixCls + '-dateItem';
            var _state = this.state,
                currentYear = _state.currentYear,
                currentMonth = _state.currentMonth,
                monthDaysArray = _state.monthDaysArray,
                selectType = _state.selectType,
                curDecadeyears = _state.curDecadeyears,
                currentDate = _state.currentDate,
                datePanel = _state.datePanel,
                selectHour = _state.selectHour,
                selectMinute = _state.selectMinute,
                selectSecond = _state.selectSecond,
                disableDaysBtn = _state.disableDaysBtn,
                disableMonthsBtn = _state.disableMonthsBtn,
                disableYearsBtn = _state.disableYearsBtn;


            var commonProps = {
                prefixCls: dateItemPrefixCls,
                beginTime: beginTime,
                endTime: endTime,
                format: format,
                local: local,
                selectType: selectType,
                currentDate: currentDate,
                type: type,
                disableTime: disableTime,
                onChangePanel: this.changePanel
            };

            var proxyProps = function proxyProps(commonProps, diffProps) {
                return function (WrappedComponent) {
                    return React.createElement(WrappedComponent, Object.assign({}, commonProps, diffProps, {
                        __source: {
                            fileName: _jsxFileName,
                            lineNumber: 538
                        },
                        __self: _this3
                    }));
                };
            };
            var yearPanelProps = {
                disabledBtn: disableYearsBtn,
                curDecadeyears: curDecadeyears,
                disabledBeforeDate: disabledBeforeDate,
                disabledAfterDate: disabledAfterDate,
                componentType: componentType,
                onSelectYear: this.selectYear,
                onDisplayYears: this.displayYears
            };

            var monthPanelProps = {
                disabledBtn: disableMonthsBtn,
                disabledBeforeDate: disabledBeforeDate,
                disabledAfterDate: disabledAfterDate,
                currentYear: currentYear,
                datePickerType: datePickerType,
                months: months,
                onSelectMonth: this.selectMonth,
                onChangeSelectType: this.changeSelectType
            };

            var datePanelProps = {
                datePickerType: datePickerType,
                datePanel: datePanel,
                currentMonth: currentMonth,
                currentYear: currentYear,
                days: days,
                monthDaysArray: monthDaysArray,
                disabledBeforeDate: disabledBeforeDate,
                disabledAfterDate: disabledAfterDate,
                selectHour: selectHour,
                selectMinute: selectMinute,
                selectSecond: selectSecond,
                onChangeSelectType: this.changeSelectType,
                onChangeTimeOrDatePanel: this.changeTimeOrDatePanel,
                onHandleSureTime: this.handleSureTime,
                onSelectTime: this.selectTime,
                onSelectDay: this.selectDay,
                disabledBtn: disableDaysBtn,
                disableExquisiteTimeRules: disableExquisiteTimeRules,
                dateConfig: dateConfig,
                showTime: showTime
            };
            var datePanelComponent = proxyProps(commonProps, datePanelProps)(DatePanel);
            var monthPanelComponent = proxyProps(commonProps, monthPanelProps)(MonthPanel);
            var yearPanelComponent = proxyProps(commonProps, yearPanelProps)(YearPanel);
            return React.createElement(
                'div',
                { className: className, ref: function ref(container) {
                        return _this3.container = container;
                    }, __source: {
                        fileName: _jsxFileName,
                        lineNumber: 587
                    },
                    __self: this
                },
                selectType === 'select-day' && datePanelComponent,
                selectType !== 'select-year' && monthPanelComponent,
                yearPanelComponent
            );
        }
    }]);

    return DtItem;
}(React.PureComponent);

DtItem.propTypes = {
    readonly: PropTypes.bool,
    disabled: PropTypes.bool,
    editable: PropTypes.bool,
    clearable: PropTypes.bool,
    size: PropTypes.string,
    placeholder: PropTypes.string,
    type: PropTypes.string,
    align: PropTypes.string,
    popperClass: PropTypes.string,
    pickerOptions: PropTypes.object,
    rangeSeparator: PropTypes.string,
    defaultValue: PropTypes.string,
    disabledBtn: PropTypes.object,
    disabledAfterDate: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.instanceOf(Date)]),
    disabledBeforeDate: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.instanceOf(Date)]),
    disableTime: PropTypes.func
};
DtItem.defaultProps = {
    currentTime: moment().format('YYYY-MM-DD'),
    readonly: false,
    disabled: false,
    editable: true,
    clearable: true,
    size: 'small',
    placeholder: '',
    type: 'date',
    align: 'left',
    popperClass: '',
    pickerOptions: {},
    rangeSeparator: '-',
    disabledBtn: { prevBtn: false, nextBtn: false }
};

var _initialiseProps = function _initialiseProps() {
    var _this4 = this;

    this.initPanel = function (currentTime, selectType) {
        var newDate = void 0;
        if (currentTime) {
            newDate = moment(currentTime);
        } else {
            newDate = moment();
        }
        var year = newDate.year();
        var month = newDate.month() + 1;
        var day = newDate.day();
        var hour = newDate.hour();
        var minute = newDate.minute();
        var second = newDate.second();

        var _parseTime = parseTime([month, day, hour, minute, second]),
            _parseTime2 = _slicedToArray(_parseTime, 5),
            strCurrentMonth = _parseTime2[0],
            strCurrentDay = _parseTime2[1],
            _parseTime2$ = _parseTime2[2],
            selectHour = _parseTime2$ === undefined ? '' : _parseTime2$,
            _parseTime2$2 = _parseTime2[3],
            selectMinute = _parseTime2$2 === undefined ? '' : _parseTime2$2,
            _parseTime2$3 = _parseTime2[4],
            selectSecond = _parseTime2$3 === undefined ? '' : _parseTime2$3;

        _this4.setState({
            selectType: selectType,
            currentDate: newDate,
            currentYear: year,
            currentMonth: month,
            currentDay: day,
            strCurrentMonth: strCurrentMonth,
            strCurrentDay: strCurrentDay,
            selectHour: selectHour,
            selectMinute: selectMinute,
            selectSecond: selectSecond
        }, function () {
            _this4.initMonthArray();
            _this4.renderYearsPanel();
        });
    };

    this.changePanel = function (type) {
        var switchType = _this4.props.switchType;

        var daysBtnTrigger = function daysBtnTrigger(arrowNo) {
            var month = _this4.state.currentMonth + arrowNo;
            var year = _this4.state.currentYear;
            if (arrowNo === 1 && _this4.state.currentMonth === 12) {
                month = 1;
                year += arrowNo;
            } else if (arrowNo === -1 && _this4.state.currentMonth === 1) {
                month = 12;
                year += arrowNo;
            }
            var strMonth = parseTime(month);
            _this4.setState({
                currentMonth: month,
                strCurrentMonth: strMonth,
                currentYear: year
            }, function () {
                if (switchType === 'date-range-unity') {
                    var publishPickerKey = _this4.pubsubEvent.publishPickerKey;

                    pubsub.publish(publishPickerKey, { currentMonth: month, currentYear: year });
                }
                _this4.initMonthArray();
            });
        };
        var monthBtnTrigger = function monthBtnTrigger(num) {
            var switchType = _this4.props.switchType;

            _this4.setState({
                currentYear: _this4.state.currentYear + num
            }, function () {
                if (switchType === 'date-range-unity') {
                    var publishPickerKey = _this4.pubsubEvent.publishPickerKey;

                    pubsub.publish(publishPickerKey, { currentYear: _this4.state.currentYear });
                }
                _this4.initMonthArray();
            });
        };
        var yearBtnTrigger = function yearBtnTrigger(num) {
            var switchType = _this4.props.switchType;

            _this4.setState({
                currentYear: _this4.state.currentYear + num
            }, function () {
                if (switchType === 'date-range-unity') {
                    var publishPickerKey = _this4.pubsubEvent.publishPickerKey;

                    pubsub.publish(publishPickerKey, { currentYear: _this4.state.currentYear });
                }
                _this4.initMonthArray();
                _this4.renderYearsPanel();
            });
        };
        switch (type) {
            case 'days-prev':
                daysBtnTrigger(-1);
                break;
            case 'days-next':
                daysBtnTrigger(1);
                break;
            case 'months-prev':
                monthBtnTrigger(-1);
                break;
            case 'months-next':
                monthBtnTrigger(1);
                break;
            case 'years-prev':
                yearBtnTrigger(-10);
                break;
            case 'years-next':
                yearBtnTrigger(10);
                break;
            default:
                return;
        }
    };

    this.initMonthArray = function () {
        var _state2 = _this4.state,
            currentYear = _state2.currentYear,
            currentMonth = _state2.currentMonth,
            strCurrentMonth = _state2.strCurrentMonth,
            selectHour = _state2.selectHour,
            selectMinute = _state2.selectMinute,
            selectSecond = _state2.selectSecond;
        var _props3 = _this4.props,
            format = _props3.format,
            local = _props3.local;

        var curTime = moment(currentYear + '-' + strCurrentMonth + '-01');
        var curDay = curTime.day(); // 得到当前月份第一天是星期中的第几天
        if (!curDay) {
            curDay = 7; // 如果得到第0天，那说明当月的第一天是星期一
        }
        var curMonthDays = moment(curTime.year() + '-' + parseTime(curTime.month() + 1) + '-01').daysInMonth();
        var lastMonthDays = moment(curTime.year() + '-' + parseTime(curTime.month()) + '-01').daysInMonth();
        if (curTime.month() === 0) {
            lastMonthDays = moment(curTime.year() - 1 + '-12-01').daysInMonth();
        }
        var monthDaysArray = [];
        var newDay = 1;
        var currentDay = 1;
        // 默认为中文显示，开始是星期一，结束为星期天
        var startDayIndex = 1;
        var endDayIndex = 42;
        if (local === 'en') {
            startDayIndex = 0;
            endDayIndex = 41;
        }
        for (var i = startDayIndex; i <= endDayIndex; i++) {
            // 上月 过去
            if (i < +curDay) {
                var day = lastMonthDays - curDay + i + 1;
                var oldFormatMonth = timeToString(+currentMonth - 1);
                var oldYear = +currentYear;
                if (+currentMonth === 1) {
                    oldFormatMonth = 12;
                    oldYear -= 1;
                }
                var oldFormatDay = timeToString(day);
                var dayFormatString = oldYear + '-' + oldFormatMonth + '-' + oldFormatDay + ' ' + timeToString(selectHour) + ':' + timeToString(selectMinute) + ':' + timeToString(selectSecond);
                monthDaysArray.push({
                    title: day,
                    type: 'old',
                    dayFormat: moment(dayFormatString).format(format)
                });
            } else if (i >= curDay && i <= curDay - 1 + curMonthDays) {
                // 当月 现在
                var currentFormatDay = timeToString(currentDay);
                var _dayFormatString = currentYear + '-' + strCurrentMonth + '-' + currentFormatDay + ' ' + timeToString(selectHour) + ':' + timeToString(selectMinute) + ':' + timeToString(selectSecond);
                monthDaysArray.push({
                    title: currentDay,
                    type: 'current',
                    dayFormat: moment(_dayFormatString).format(format)
                });
                currentDay++;
            } else {
                // 未来 下一个月
                var newFormatMonth = timeToString(currentMonth + 1);
                var newYear = +currentYear;
                if (+currentMonth === 12) {
                    newFormatMonth = '01';
                    newYear += 1;
                }
                var newFormatDay = timeToString(newDay);
                var _dayFormatString2 = newYear + '-' + newFormatMonth + '-' + newFormatDay + ' ' + timeToString(selectHour) + ':' + timeToString(selectMinute) + ':' + timeToString(selectSecond);
                monthDaysArray.push({
                    title: newDay,
                    type: 'new',
                    dayFormat: moment(_dayFormatString2).format(format)
                });
                newDay++;
            }
        }
        _this4.setState({
            monthDaysArray: monthDaysArray
        });
    };

    this.changeSelectType = function (selectType) {
        _this4.setState({
            selectType: selectType
        });
        if (selectType === 'select-year') {
            _this4.renderYearsPanel();
        }
    };

    this.displayYears = function () {
        var currentYear = _this4.state.currentYear;

        var singleDigit = currentYear % 10;

        if (singleDigit !== 0) {
            return currentYear - singleDigit + ' - ' + (currentYear - singleDigit + 10);
        } else {
            return currentYear + ' - ' + (currentYear + 10);
        }
    };

    this.renderYearsPanel = function () {
        var currentYear = _this4.state.currentYear;

        var singleDigit = currentYear % 10;
        var curDecadeyears = [];
        if (singleDigit) {
            for (var i = -1; i < 11; i++) {
                curDecadeyears.push(currentYear - singleDigit + i);
            }
        } else {
            for (var _i = -1; _i < 11; _i++) {
                curDecadeyears.push(currentYear + _i);
            }
        }
        _this4.setState({
            curDecadeyears: curDecadeyears
        });
    };

    this.selectYear = function (index) {
        var _props4 = _this4.props,
            selectType = _props4.selectType,
            format = _props4.format,
            onChange = _props4.onChange,
            type = _props4.type;
        var curDecadeyears = _this4.state.curDecadeyears;

        var rightType = selectType === 'select-year';
        var checkedYear = curDecadeyears[index];
        if (rightType) {
            _this4.setState({
                currentYear: checkedYear
            }, function () {
                _this4.initMonthArray();
                onChange && onChange(type, moment(checkedYear + '-01-01').format(format));
            });
            if (index === 11) {
                _this4.changePanel('years-next');
            } else if (index === 0) {
                _this4.changePanel('years-prev');
            }
        } else {
            _this4.setState({
                currentYear: checkedYear,
                selectType: 'select-month'
            });
        }
    };

    this.selectMonth = function (index) {
        var _props5 = _this4.props,
            selectType = _props5.selectType,
            format = _props5.format,
            onChange = _props5.onChange,
            type = _props5.type;
        var currentYear = _this4.state.currentYear;

        var rightType = selectType === 'select-month';
        if (rightType) {
            _this4.setState({
                currentMonth: index + 1,
                currentDate: moment(currentYear + '-' + parseTime(index + 1) + '-01').format(format)
            }, function () {
                _this4.initMonthArray();
            });
            onChange && onChange(type, moment(currentYear + '-' + (index + 1 >= 10 ? index + 1 : '0' + (index + 1)) + '-01').format(format));
        } else {
            _this4.setState({
                currentMonth: index + 1,
                strCurrentMonth: parseTime(index + 1),
                selectType: 'select-day'
            }, function () {
                _this4.initMonthArray();
            });
        }
    };

    this.selectDay = function (index) {
        var monthDaysArray = _this4.state.monthDaysArray;
        var _props6 = _this4.props,
            format = _props6.format,
            onChange = _props6.onChange,
            type = _props6.type;

        _this4.setState({
            currentDate: monthDaysArray[index].dayFormat
        });
        var finalDateValue = monthDaysArray[index].dayFormat;
        onChange && onChange(type, moment(finalDateValue).format(format));
    };

    this.changeTimeOrDatePanel = function () {
        _this4.setState({
            datePanel: !_this4.state.datePanel
        });
    };

    this.selectTime = function (type, time) {
        _this4.setState(_defineProperty({}, type, time), function () {
            _this4.handleSureTime();
        });
    };

    this.handleSureTime = function () {
        var _props7 = _this4.props,
            onChange = _props7.onChange,
            format = _props7.format,
            type = _props7.type;
        var _state3 = _this4.state,
            currentDate = _state3.currentDate,
            selectHour = _state3.selectHour,
            selectMinute = _state3.selectMinute,
            selectSecond = _state3.selectSecond;

        var formatDateString = function formatDateString(number) {
            var formatString = number.toString();
            if (formatString.length < 2) {
                formatString = '0' + number;
            }
            return formatString;
        };
        onChange && onChange(type, moment(moment(currentDate).format('YYYY-MM-DD') + ' ' + formatDateString(selectHour) + ':' + formatDateString(selectMinute) + ':' + formatDateString(selectSecond)).format(format));
    };
};

export default DtItem;