import _defineProperty from 'babel-runtime/helpers/defineProperty';
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/DatePicker.jsx';
import React from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import Input from '../input';
import DtItem from './dateItem';
import Icon from '../icon';
import formatDate from '../util/formatDate';
import omitby from '../util/omit';
import { isUndefined } from '../util/isType';
import { DateRange, DateRangeUnity, DateSingle } from './components';

var DatePicker = function (_React$Component) {
    _inherits(DatePicker, _React$Component);

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

        /**
         * 初始化默认值，对空默认值进行处理
         * */
        var _this = _possibleConstructorReturn(this, (DatePicker.__proto__ || Object.getPrototypeOf(DatePicker)).call(this, props));

        _initialiseProps.call(_this);

        var _this$props = _this.props,
            defaultValue = _this$props.defaultValue,
            format = _this$props.format,
            type = _this$props.type;

        defaultValue = !!defaultValue ? defaultValue : void 0;
        var onlyTimeValue = void 0;
        var beginTimeValue = void 0;
        var endTimeValue = void 0;
        _this.datePickerKey = 'datePicker-' + Math.random();
        if (type === 'date') {
            onlyTimeValue = defaultValue && formatDate(defaultValue, format);
        } else {
            beginTimeValue = _this.initTimeValue(defaultValue, 0);
            endTimeValue = _this.initTimeValue(defaultValue, 1);
        }
        _this.state = {
            displayPicker: false,
            beginPicker: false,
            endPicker: false,
            onlyTimeValue: onlyTimeValue,
            beginTimeValue: beginTimeValue,
            endTimeValue: endTimeValue
        };
        return _this;
    }

    _createClass(DatePicker, [{
        key: 'componentWillReceiveProps',
        value: function componentWillReceiveProps(nextProps) {
            var nextPropsDefaultValue = nextProps.defaultValue,
                type = nextProps.type,
                format = nextProps.format;
            var defaultValue = this.props.defaultValue;
            var _state = this.state,
                beginTimeValue = _state.beginTimeValue,
                endTimeValue = _state.endTimeValue,
                onlyTimeValue = _state.onlyTimeValue;

            if (type === 'date') {
                // 格式化时间
                nextPropsDefaultValue = nextPropsDefaultValue !== '' ? nextPropsDefaultValue : void 0;
                nextPropsDefaultValue = formatDate(nextPropsDefaultValue, format);
                if (onlyTimeValue !== nextPropsDefaultValue) {
                    // 更新时间
                    this.setState({
                        onlyTimeValue: nextPropsDefaultValue
                    });
                }
            } else {
                var initDefaultValue = function initDefaultValue(value) {
                    if (!value) {
                        value = [void 0, void 0];
                    }
                    return value;
                };
                // 格式化时间
                defaultValue = initDefaultValue(defaultValue);
                nextPropsDefaultValue = initDefaultValue(nextPropsDefaultValue);
                var beginDate = formatDate(nextPropsDefaultValue[0], format);
                var endDate = formatDate(nextPropsDefaultValue[1], format);
                // 更新时间
                if (beginTimeValue !== beginDate || endTimeValue !== endDate) {
                    this.setState({
                        beginTimeValue: beginDate,
                        endTimeValue: endDate
                    });
                }
            }
        }
    }, {
        key: 'shouldComponentUpdate',
        value: function shouldComponentUpdate(nextProps, nextStates) {
            var defaultValue = this.props.defaultValue;
            var nextDefaultValue = nextProps.defaultValue;

            var boolProps = false;
            if (Array.isArray(defaultValue) && Array.isArray(nextDefaultValue)) {
                boolProps = defaultValue[0] !== nextDefaultValue[0] || defaultValue[1] !== nextDefaultValue[1];
            } else {
                boolProps = defaultValue !== nextDefaultValue;
            }
            var _state2 = this.state,
                beginTimeValue = _state2.beginTimeValue,
                endTimeValue = _state2.endTimeValue,
                onlyTimeValue = _state2.onlyTimeValue,
                onActive = _state2.onActive,
                beginActive = _state2.beginActive,
                endActive = _state2.endActive;
            var nextBeginTimeValue = nextStates.beginTimeValue,
                nextEndTimeValue = nextStates.endTimeValue,
                nextOnlyTimeValue = nextStates.onlyTimeValue,
                nextOnActive = nextStates.onActive,
                nextBeginActive = nextStates.beginActive,
                nextEndActive = nextStates.endActive;

            var boolState = false;
            var checkEmptyString = function checkEmptyString(value) {
                return value === '';
            };
            if (beginTimeValue !== nextBeginTimeValue && moment(nextBeginTimeValue).isValid() || checkEmptyString(nextBeginTimeValue) || endTimeValue !== nextEndTimeValue && moment(nextEndTimeValue).isValid() || checkEmptyString(nextEndTimeValue) || onlyTimeValue !== nextOnlyTimeValue && moment(nextOnlyTimeValue).isValid() || checkEmptyString(nextOnlyTimeValue) || onActive !== nextOnActive || beginActive !== nextBeginActive || endActive !== nextEndActive) {
                boolState = true;
            }
            return boolProps || boolState;
        }
    }, {
        key: 'componentDidUpdate',
        value: function componentDidUpdate(prevProps, prevState) {
            var _props = this.props,
                type = _props.type,
                onChange = _props.onChange;
            var _state3 = this.state,
                beginTimeValue = _state3.beginTimeValue,
                endTimeValue = _state3.endTimeValue,
                onlyTimeValue = _state3.onlyTimeValue;

            if (prevState.beginTimeValue !== beginTimeValue || prevState.endTimeValue !== endTimeValue || prevState.onlyTimeValue !== onlyTimeValue) {
                var onChangeProps = {
                    'date-range': [beginTimeValue, endTimeValue],
                    'date-range-unity': [beginTimeValue, endTimeValue],
                    date: onlyTimeValue
                }[type];
                var convertUndefinedValue = function convertUndefinedValue(values) {
                    if (Object.prototype.toString.call(values) === '[object Array]') {
                        values = values.map(function (value) {
                            return convertUndefinedValue(value);
                        });
                    } else {
                        if (isUndefined(values)) {
                            values = '';
                        }
                    }
                    return values;
                };
                onChange(convertUndefinedValue(onChangeProps));
            }
        }
    }, {
        key: 'render',
        value: function render() {
            var _this2 = this;

            var _props2 = this.props,
                prefixCls = _props2.prefixCls,
                dateRangeStyle = _props2.dateRangeStyle,
                type = _props2.type,
                separator = _props2.separator,
                readOnly = _props2.readOnly,
                inputClass = _props2.inputClass,
                inputProps = _props2.inputProps,
                dateRangeWholeStyle = _props2.dateRangeWholeStyle,
                convenientRange = _props2.convenientRange,
                disableExquisiteTimeRules = _props2.disableExquisiteTimeRules,
                _autoTestProps_ = _props2._autoTestProps_;

            if (Array.isArray(inputProps)) {
                inputProps.forEach(function (item) {
                    item.readOnly = readOnly;
                });
            } else {
                inputProps.readOnly = readOnly;
            }
            var _autoTest_isOpen = _autoTestProps_._autoTest_isOpen;
            var _state4 = this.state,
                onlyTimeValue = _state4.onlyTimeValue,
                beginTimeValue = _state4.beginTimeValue,
                endTimeValue = _state4.endTimeValue,
                dateRangeOpen = _state4.dateRangeOpen,
                selectRangeBar = _state4.selectRangeBar;

            var prefixClsDatePicker = prefixCls + '-datePicker';
            var singleDisableExquisiteTimeRules = null;
            var beginDisableExquisiteTimeRules = null;
            var endDisableExquisiteTimeRules = null;
            if (disableExquisiteTimeRules) {
                singleDisableExquisiteTimeRules = disableExquisiteTimeRules.singleTime;
                beginDisableExquisiteTimeRules = disableExquisiteTimeRules.beginTime;
                endDisableExquisiteTimeRules = disableExquisiteTimeRules.endTime;
            }
            var beginDtItemDiffProps = omitby({
                type: 'date-range-begin',
                disableExquisiteTimeRules: beginDisableExquisiteTimeRules,
                currentTime: beginTimeValue,
                switchType: type,
                title: '开始时间'
            }, function (value) {
                return value !== 0 && !value;
            });
            var endDtItemDiffProps = omitby({
                type: 'date-range-end',
                disableExquisiteTimeRules: endDisableExquisiteTimeRules,
                currentTime: endTimeValue,
                switchType: type,
                title: '结束时间'
            }, function (value) {
                return value !== 0 && !value;
            });
            var hocFunc = function hocFunc(commonProps) {
                return function (WrappedComponent, diffProps) {
                    return React.createElement(WrappedComponent, Object.assign({}, omitby(diffProps, function (value) {
                        return value !== 0 && !value;
                    }), omitby(commonProps, function (value) {
                        return value !== 0 && !value;
                    }), {
                        __source: {
                            fileName: _jsxFileName,
                            lineNumber: 449
                        },
                        __self: _this2
                    }));
                };
            };
            var readyRenderDom = hocFunc({
                prefixClsDatePicker: prefixClsDatePicker,
                inputProps: inputProps,
                clearBtn: this.clearBtn,
                renderDtItem: this.renderDtItem,
                renderInput: this.renderInput,
                handleActive: this.handleActive,
                inputClass: inputClass,
                _autoTest_isOpen: _autoTest_isOpen
            });
            var activeDateComponents = {
                date: readyRenderDom(DateSingle, {
                    onlyTimeValue: onlyTimeValue,
                    singleDisableExquisiteTimeRules: singleDisableExquisiteTimeRules,
                    type: type
                }),
                'date-range': readyRenderDom(DateRange, {
                    dateRangeStyle: dateRangeStyle,
                    prefixCls: prefixCls,
                    beginTimeValue: beginTimeValue,
                    separator: separator,
                    endTimeValue: endTimeValue,
                    beginDtItemDiffProps: beginDtItemDiffProps,
                    endDtItemDiffProps: endDtItemDiffProps
                }),
                'date-range-unity': readyRenderDom(DateRangeUnity, {
                    dateRangeWholeStyle: dateRangeWholeStyle,
                    beginTimeValue: beginTimeValue,
                    separator: separator,
                    endTimeValue: endTimeValue,
                    convenientRange: convenientRange,
                    dateRangeOpen: dateRangeOpen,
                    beginDtItemDiffProps: beginDtItemDiffProps,
                    selectRangeBar: selectRangeBar,
                    handleSelectRange: this.handleSelectRange,
                    endDtItemDiffProps: endDtItemDiffProps
                })
            }[type];
            return activeDateComponents;
        }
    }]);

    return DatePicker;
}(React.Component);

DatePicker.propTypes = {
    /**
     * @ignore
     * */
    readOnly: PropTypes.bool,
    /**
     * 是否禁用，true：禁用，false：不禁用，禁用状态无法选择时间
     * */
    disabled: PropTypes.bool,
    /**
     * 是否开启清除整个选择框时间功能，true为开启，false为不开启
     * */
    clearable: PropTypes.bool,
    /**
     * 所传组件类型，目前支持三种类型，分别为date（单控件）、date-range（双控件，选择范围）、date-range-unity（整体单控件、选择范围）
     * */
    type: PropTypes.string,
    /**
     * 当所传控件类型为date（单控件）时候，传递时间默认值，可以传字符串（如2018-01-01）、数字（毫秒数）、date（new Date）
     * */
    defaultValue: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.instanceOf(Date), PropTypes.array]),
    /**
     * input输入框的类名
     * */
    inputClass: PropTypes.string,
    /**
     * 选择时间后返回的时间格式，可以参考moment.js
     * */
    format: PropTypes.string,
    /**
     * 改变时间之后的回调函数
     * */
    onChange: PropTypes.func,
    /**
     * 时间格式化之后的回调函数，可以将格式化后的时间处理成需要的特殊格式
     * */
    onFormatDate: PropTypes.func,
    /**
     * 时间控件显示，true为显示，false为不显示
     * */
    showTime: PropTypes.bool,
    /**
     * 设置禁用时间
     * @param {Date} date - 传递组件所渲染的选项时间
     * @returns {bool} - 返回true为禁用,false为不禁用
     * */
    disableTime: PropTypes.func,
    /**
     * 当所传控件类型为date-range（双控件） 或者 date-range-whole（整体单控件、选择范围）时候，传递开始时间input组件的类名
     * */
    beginInputClass: PropTypes.string,
    /**
     * 当所传控件类型为date-range（双控件） 或者 date-range-whole（整体单控件、选择范围）时候，传递结束时间input组件的类名
     * */
    endInputClass: PropTypes.string,
    /**
     * 当所传控件类型为date-range（双控件） 或者 date-range-whole（整体单控件、选择范围）时候，传递中间连接符
     * */
    separator: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
    /**
     * 组件类名
     * */
    className: PropTypes.string,
    /**
     * 当所传控件类型为date-range（双控件） 或者 date-range-whole（整体单控件、选择范围）时候，传递开始日期input前的icon
     * */
    beginInputPrefix: PropTypes.object,
    /**
     * 当所传控件类型为date-range（双控件） 或者 date-range-whole（整体单控件、选择范围）时候，传递结束日期input前的icon
     * */
    endInputPrefix: PropTypes.object,
    /**
     * 组件类名前缀
     * */
    prefixCls: PropTypes.string,
    /**
     * input组件的一些属性设置
     * */
    inputProps: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
    /**
     * 快捷范围选择
     * */
    convenientRange: PropTypes.array,
    /**
     * input 尺寸
     * */
    inputSize: PropTypes.string,
    /**
     * 国际化 zh中文 en英文
     * */
    local: PropTypes.string,
    /**
     * 禁用小时、分钟、秒 具体使用请查看TimePicker组件
     * */
    disableExquisiteTimeRules: PropTypes.object,
    /**
     * 所选择的时间类型，有select-day(天)， select-month(月)，select-year(年)三种
     * */
    selectType: PropTypes.string,
    /**
     * @ignore
     * 用于单元测试的隐藏属性
     * */
    _autoTestProps_: PropTypes.object
};
DatePicker.defaultProps = {
    type: 'date',
    readOnly: true,
    disabled: false,
    format: 'YYYY-MM-DD',
    clearable: false,
    onChange: function onChange(obj) {
        return console.log(obj);
    },
    onFormatDate: function onFormatDate(date) {
        return date;
    },
    separator: '-',
    selectType: 'select-day',
    className: '',
    showTime: false,
    prefixCls: 'ne',
    inputProps: [],
    local: 'zh',
    beginInputPrefix: React.createElement(Icon, { type: 'date', __source: {
            fileName: _jsxFileName,
            lineNumber: 139
        },
        __self: this
    }),
    _autoTestProps_: {}
};

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

    this.initTimeValue = function (value, index) {
        var format = _this3.props.format;

        return value && value[index] && formatDate(value[index] !== '' ? value[index] : void 0, format);
    };

    this.onChange = function (type, time) {
        var onFormatDate = _this3.props.onFormatDate;

        var formatTime = onFormatDate(time);
        var targetType = {
            'date-range-begin': { beginTimeValue: formatTime },
            'date-range-end': { endTimeValue: formatTime },
            date: { onlyTimeValue: formatTime }
        }[type];
        _this3.setState(targetType);
    };

    this.clearDateInfo = function (e, dateItemType) {
        e && e.stopPropagation();
        var type = _this3.props.type;

        if (type === 'date-range') {
            if (dateItemType === 'begin') {
                _this3.setState({
                    beginTimeValue: ''
                });
            } else if (dateItemType === 'end') {
                _this3.setState({
                    endTimeValue: ''
                });
            }
        } else {
            _this3.setState({
                beginTimeValue: '',
                endTimeValue: '',
                onlyTimeValue: ''
            });
        }
    };

    this.handleSelectRange = function (range, label) {
        var format = _this3.props.format;

        _this3.setState({
            selectRangeBar: label,
            beginTimeValue: formatDate(range[0], format),
            endTimeValue: formatDate(range[1], format)
        });
    };

    this.handleActive = function (bool, type) {
        if (type) {
            _this3.setState(_defineProperty({}, type, bool));
        } else {
            _this3.setState({
                onActive: bool
            });
        }
    };

    this.renderInput = function () {
        var _props3 = _this3.props,
            disabled = _props3.disabled,
            readOnly = _props3.readOnly,
            inputPrefix = _props3.inputPrefix,
            inputSize = _props3.inputSize,
            inputClass = _props3.inputClass;

        var commonInputProps = {
            disabled: disabled,
            readOnly: readOnly,
            style: { flex: 1 },
            prefix: inputPrefix,
            size: inputSize,
            className: inputClass
        };
        var preCurryInputElm = function preCurryInputElm(commonInputProps) {
            return function (diffInputProps) {
                return React.createElement(Input, Object.assign({}, commonInputProps, diffInputProps, {
                    __source: {
                        fileName: _jsxFileName,
                        lineNumber: 338
                    },
                    __self: _this3
                }));
            };
        };
        return preCurryInputElm(commonInputProps);
    };

    this.renderDtItem = function () {
        var _props4 = _this3.props,
            local = _props4.local,
            selectType = _props4.selectType,
            prefixCls = _props4.prefixCls,
            showTime = _props4.showTime,
            disableTime = _props4.disableTime,
            type = _props4.type,
            format = _props4.format,
            dateClassName = _props4.dateClassName;

        var prefixClsDatePicker = prefixCls + '-datePicker';
        var _state5 = _this3.state,
            beginTimeValue = _state5.beginTimeValue,
            endTimeValue = _state5.endTimeValue;

        var dtItemCommonProps = {
            local: local,
            datePickerKey: _this3.datePickerKey,
            selectType: selectType,
            beginTime: beginTimeValue,
            endTime: endTimeValue,
            format: format,
            prefixCls: prefixClsDatePicker,
            className: dateClassName,
            onChange: _this3.onChange,
            showTime: showTime,
            disableTime: disableTime,
            datePickerType: type
        };
        var commonDateItem = function commonDateItem(commonProps) {
            return function (diffProps) {
                return React.createElement(DtItem, Object.assign({}, omitby(commonProps, function (item) {
                    return item !== 0 && !item;
                }), diffProps, {
                    __source: {
                        fileName: _jsxFileName,
                        lineNumber: 363
                    },
                    __self: _this3
                }));
            };
        };
        return commonDateItem(dtItemCommonProps);
    };

    this.clearBtn = function (dateItemType) {
        var _props5 = _this3.props,
            clearable = _props5.clearable,
            type = _props5.type;
        var _state6 = _this3.state,
            beginActive = _state6.beginActive,
            endActive = _state6.endActive,
            onActive = _state6.onActive;

        if (clearable) {
            var bool = false;
            if (type === 'date-range' && (dateItemType === 'begin' && beginActive || dateItemType === 'end' && endActive)) {
                bool = true;
            } else {
                bool = onActive;
            }
            return bool && React.createElement(Icon, {
                onClick: function onClick(e) {
                    return _this3.clearDateInfo(e, dateItemType);
                },
                style: { position: 'absolute', top: 6, right: 0, color: '#ddd' },
                type: 'cancel-o',
                __source: {
                    fileName: _jsxFileName,
                    lineNumber: 384
                },
                __self: _this3
            });
        }
    };
};

export default DatePicker;