'use strict';

Object.defineProperty(exports, "__esModule", {
    value: true
});

var _defineProperty2 = require('babel-runtime/helpers/defineProperty');

var _defineProperty3 = _interopRequireDefault(_defineProperty2);

var _extends2 = require('babel-runtime/helpers/extends');

var _extends3 = _interopRequireDefault(_extends2);

var _carousel = require('../carousel');

var _carousel2 = _interopRequireDefault(_carousel);

var _carouselItem = require('../carousel-item');

var _carouselItem2 = _interopRequireDefault(_carouselItem);

var _toast = require('../toast');

var _toast2 = _interopRequireDefault(_toast);

var _util = require('../calendar/util');

var _dateUtil = require('../utils/dateUtil');

var _numberUtil = require('../utils/numberUtil');

var _event = require('../_utils/dom/event');

var _raf = require('../_utils/dom/raf');

require('./index.less');

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

var Calendar = {
    name: 'SnCalendar',
    data: function data() {
        return {
            height: 0,
            panelTitle: '',
            times: [],
            selectedDate: [],
            selectedTime: [],
            weekList: ['日', '一', '二', '三', '四', '五', '六'],
            showCalender: true,
            showMonthSelect: false,
            showTimeSelect: false,
            year: 0,
            month: 0,
            today: (0, _dateUtil.dateFormat)(new Date(), 'YYYY/MM/DD'),
            currentValue: '',
            currentDate: '',
            currentTime: '08:30',
            swiperList: [],
            swiperItemIndex: 0,
            quickToday: true,
            minDate: false,
            maxDate: false
        };
    },

    props: {
        value: [String, Number, Array, Date],
        /** 时间控件模式
         * 1) 'date':         选择日期
         * 2) 'datetime':     选择时间
         * 3) 'year-month':   选择年月
         * 4） 'year':        选择年份
         * 5） 'month':       选择月份
         * 6)  'time':        选择时分
         */
        mode: { 'default': 'date' },
        disabledDate: Function,
        vertical: {
            type: Boolean,
            'default': true
        },
        showLastMonth: {
            type: Boolean,
            'default': false
        },
        showNextMonth: {
            type: Boolean,
            'default': false
        },
        workDate: {
            type: Array,
            'default': function _default() {
                return [];
            }
        },
        infoDate: {
            type: Array,
            'default': function _default() {
                return [];
            }
        },
        touchable: {
            type: Boolean,
            'default': true
        },
        mouseable: {
            type: Boolean,
            'default': true
        },
        minuteStep: [String, Number]
    },
    computed: {
        styleHeight: function styleHeight() {
            return this.height + 'px';
        }
    },
    watch: {
        value: function value(val) {
            this.currentValue = val;
        },
        currentValue: function currentValue(val) {
            var mode = this.mode,
                currentValue = this.currentValue,
                selectedDate = this.selectedDate;

            if (mode === 'date' || mode === 'datetime' || mode === 'year-month') {
                if (mode === 'date') {
                    this.panelTitle = (0, _dateUtil.dateFormat)(currentValue, 'YYYY年MM月DD日 EE');
                } else if (mode === 'datetime') {
                    this.panelTitle = (0, _dateUtil.dateFormat)(currentValue, 'YYYY年MM月DD日');
                } else {
                    this.panelTitle = selectedDate[0] + '\u5E74' + selectedDate[1] + '\u6708';
                }
            } else if (mode === 'year') {
                this.panelTitle = selectedDate[0] + '\u5E74';
            } else if (mode === 'month') {
                this.panelTitle = selectedDate[0] + '\u6708';
            }
        },
        selectedDate: function selectedDate(val) {
            var mode = this.mode;

            if (mode === 'date' || mode === 'datetime' || mode === 'year-month') {
                var now = new Date();

                if (parseInt(val[0]) === now.getFullYear() - 20 && parseInt(val[1]) === 1) {
                    this.minDate = true;
                }
                if (parseInt(val[0]) === now.getFullYear() + 20 && parseInt(val[1]) === 12) {
                    this.maxDate = true;
                }

                if (mode === 'year-month') {
                    this.panelTitle = val[0] + '\u5E74' + val[1] + '\u6708';
                }
            }
        },
        selectedTime: function selectedTime(val) {
            var mode = this.mode;

            if (mode === 'time') {
                this.panelTitle = val[0] + '\u65F6' + val[1] + '\u5206';
            }
        }
    },
    created: function created() {
        this.currentValue = this.value;
        var mode = this.mode;
        var date = void 0,
            year = void 0,
            month = void 0;

        if (this.currentValue instanceof Array) {
            if (mode === 'year-month') {
                if (this.currentValue.length === 0) {
                    year = new Date().getFullYear();
                    month = new Date().getMonth();
                } else if (this.currentValue.length === 1) {
                    year = Number(this.currentValue[0]);
                    month = new Date().getMonth();
                } else if (this.currentValue.length === 2) {
                    year = Number(this.currentValue[0]);
                    month = Number(this.currentValue[1]) - 1;
                }
            } else if (mode === 'year') {
                if (this.currentValue.length === 0) {
                    year = new Date().getMonth();
                } else if (this.currentValue.length === 1) {
                    year = Number(this.currentValue[0]);
                }
            } else if (mode === 'month') {
                if (this.currentValue.length === 0) {
                    month = new Date().getMonth();
                } else if (this.currentValue.length === 1) {
                    month = Number(this.currentValue[0]) - 1;
                }
            }
        } else {
            date = this.currentValue && new Date(this.currentValue) || new Date();
            year = date.getFullYear();
            month = date.getMonth();
        }

        var fullYear = '' + year,
            fullMonth = (0, _numberUtil.zeroComplete)(month + 1);
        if (mode === 'date') {
            this.currentValue = (0, _dateUtil.dateFormat)(date, 'YYYY/MM/DD');
            this.quickToday = true;
            this.selectedDate = [fullYear, fullMonth];
            this.render(year, month);
        } else if (mode === 'datetime') {
            try {
                this.currentDate = (0, _dateUtil.dateFormat)(date, 'YYYY/MM/DD');
            } catch (e) {
                throw Error('[sinosun-ui] datetimePickerView 时间格式不正确');
            }
            this.currentValue = (0, _dateUtil.dateFormat)(date, 'YYYY/MM/DD');
            this.quickToday = false;
            this.selectedDate = [fullYear, fullMonth];
            this.render(year, month);
        } else if (mode === 'year-month') {
            this.showCalender = false;
            this.showMonthSelect = true;
            this.quickToday = false;
            this.selectedDate = [fullYear, fullMonth];
        } else if (mode === 'year') {
            this.showCalender = false;
            this.showMonthSelect = true;
            this.quickToday = false;
            this.selectedDate = [fullYear];
        } else if (mode === 'month') {
            this.showCalender = false;
            this.showMonthSelect = true;
            this.quickToday = false;
            this.selectedDate = [fullMonth];
        } else if (mode === 'time') {
            this.showCalender = false;
            this.showMonthSelect = false;
            this.quickToday = false;
            this.showTimeSelect = true;
            if (this.currentValue) {
                if (this.currentValue instanceof Array === false) {
                    console.error('[sinosun-ui] DatetimePickerView 模式为time时，value值必须为数组。');
                }
            }
        }

        /* 动态计算swiper高度 */
        this.getHeight();
    },

    methods: {
        /* 获取高度 */
        getHeight: function getHeight() {
            var windowWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
            this.height = windowWidth < 480 ? windowWidth * 0.94 : 360;
        },

        /* 渲染入口 */
        render: function render(year, month) {
            var force = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;

            var value = this.currentValue;

            this.year = year;
            this.month = month;

            /* 注入滑动数组 */
            this.renderCarousel(year, month, value);
        },

        /* 渲染日历数据 */
        renderCarousel: function renderCarousel(year, month, value) {
            var _this = this;

            var disabledDate = this.disabledDate;

            /* 生成总共需要的四个月数据 */

            var prevTime = (0, _util.getPrevTime)(year, month);
            var nextTime = (0, _util.getNextTime)(year, month);
            var prevMonth = (0, _util.getDays)((0, _extends3['default'])({}, prevTime, { value: value, disabledDate: disabledDate }));
            var curMonth = (0, _util.getDays)({ year: year, month: month, value: value, disabledDate: disabledDate });
            var nextMonth = (0, _util.getDays)((0, _extends3['default'])({}, nextTime, { value: value, disabledDate: disabledDate }));

            this.$refs.carousel && this.$refs.carousel.swipeTo(0, { immediate: true });
            this.swiperItemIndex = 0;
            (0, _raf.doubleRaf)(function () {
                _this.swiperList = [];
                _this.swiperList = [curMonth, nextMonth, prevMonth];
            });
        },

        /* 上一页 */
        prev: function prev() {
            if (!this.minDate) {
                var swiperItemIndex = this.swiperItemIndex;
                var goIndex = swiperItemIndex - 1 >= 0 ? swiperItemIndex - 1 : 2;
                this.$refs.carousel.swipeTo(goIndex, { immediate: true });
            }
        },

        /* 下一页 */
        next: function next() {
            if (!this.maxDate) {
                var swiperItemIndex = this.swiperItemIndex;
                var goIndex = swiperItemIndex + 1 <= 2 ? swiperItemIndex + 1 : 0;
                this.$refs.carousel.swipeTo(goIndex, { immediate: true });
            }
        },

        /* 跳转页 */
        go: function go(year, month) {
            this.render(year, month, true);
        },

        /* 选择日期 */
        select: function select(event, k1, k2, data) {
            (0, _event.preventDefault)(event, true);
            var mode = this.mode,
                showLastMonth = this.showLastMonth,
                showNextMonth = this.showNextMonth;


            if (data.isDisabled) {
                return;
            }
            if (!showLastMonth && data.isLastMonth) {
                return;
            }
            if (!showNextMonth && data.isNextMonth) {
                return;
            }

            var _currentValue = data.formatedDate;
            if ((!data.isLastMonth || showLastMonth) && (!data.isNextMonth || showNextMonth)) {
                var index = this.swiperItemIndex;
                var month = this.swiperList[index];
                var days = month.days;
                for (var row = 0; row < days.length; row++) {
                    for (var day = 0; day < days[row].length; day++) {
                        if (row === k1 && day === k2) {
                            days[k1][k2].isCurrent = true;
                        } else {
                            days[row][day].isCurrent = false;
                        }
                    }
                }
                if (showLastMonth && data.isLastMonth) this.prev();
                if (showNextMonth && data.isNextMonth) this.next();
            }
            this.currentValue = _currentValue;
            this.currentDate = _currentValue;

            if (mode === 'date') {
                this.$emit('input', this.currentValue);
                this.$emit('change', this.currentValue);
            } else if (mode === 'datetime') {
                this.$emit('change', this.currentDate + ' ' + this.currentTime);
            }

            if (this.renderOnValueChange) {
                this.render(null, null);
            }
        },

        /* 设置选中的天 */
        setSelectedDay: function setSelectedDay() {
            var currentDate = new Date(this.currentValue);
            var day = currentDate.getDate();
            /* 当前月最大日期 */
            var selectedMonthMaxDate = new Date(this.year, this.month + 1, 0).getDate();
            var selectedDay = (0, _dateUtil.dateFormat)(new Date(this.year, this.month, day < selectedMonthMaxDate ? day : selectedMonthMaxDate), 'YYYY/MM/DD');
            this.currentValue = selectedDay;
            this.currentDate = selectedDay;

            for (var t = 0; t < this.swiperList.length; t++) {
                var month = this.swiperList[t];
                var days = month.days;
                for (var row = 0; row < days.length; row++) {
                    for (var _day = 0; _day < days[row].length; _day++) {
                        if (days[row][_day].formatedDate === selectedDay) {
                            this.swiperList[t].days[row][_day].isCurrent = true;
                        } else {
                            this.swiperList[t].days[row][_day].isCurrent = false;
                        }
                    }
                }
            }

            if (this.mode === 'date') {
                this.$emit('change', this.currentValue);
            } else if (this.mode === 'datetime') {
                this.$emit('change', this.currentDate + ' ' + this.currentTime);
            }
        },

        /* 日历onChange回调 */
        onCalendarChange: function onCalendarChange(currentIndex) {
            var _this2 = this;

            /* 滑动结束后执行选中滑动前选中的天 */
            if (currentIndex !== this.swiperItemIndex) {
                this.$nextTick(function () {
                    (0, _raf.doubleRaf)(function () {
                        var disabledDate = _this2.disabledDate;

                        var _year = _this2.year,
                            _month = _this2.month,
                            _currentValue = _this2.currentValue;

                        _this2.year = _this2.swiperList[currentIndex].year;
                        _this2.month = _this2.swiperList[currentIndex].month;
                        _this2.selectedDate = ['' + _this2.year, '' + (0, _numberUtil.zeroComplete)(_this2.month + 1)];
                        var prevTime = (0, _util.getPrevTime)(_year, _month);
                        var prev2Time = (0, _util.getPrevTime)(prevTime.year, prevTime.month);
                        var nextTime = (0, _util.getNextTime)(_year, _month);
                        var next2Time = (0, _util.getNextTime)(nextTime.year, nextTime.month);

                        var prev2Month = (0, _util.getDays)((0, _extends3['default'])({}, prev2Time, {
                            value: _currentValue,
                            disabledDate: disabledDate
                        }));
                        var next2Month = (0, _util.getDays)((0, _extends3['default'])({}, next2Time, {
                            value: _currentValue,
                            disabledDate: disabledDate
                        }));

                        /* 当前页为第一页 */
                        if (_this2.swiperItemIndex === 0) {
                            /* 下滑，进入第二页; 开始顺序 => [cur, next, prev], 结束顺序 => [cur, next, next2] */
                            if (currentIndex === 1) {
                                _this2.$set(_this2.swiperList, 2, next2Month);
                            } else {
                                /* 上滑，进入第三页; 开始顺序 => [cur, next, prev], 结束顺序 => [cur, prev2, prev] */
                                _this2.$set(_this2.swiperList, 1, prev2Month);
                            }
                        } else if (_this2.swiperItemIndex === 1) {
                            /* 当前页为第二页 */
                            /* 下滑，进入第三页; 开始顺序 => [prev, cur, next], 结束顺序 => [next2, cur, next] */
                            if (currentIndex === 2) {
                                _this2.$set(_this2.swiperList, 0, next2Month);
                            } else {
                                /* 上滑，进入第一页; 开始顺序 => [prev, cur, next], 结束顺序 => [prev, cur, prev2] */
                                _this2.$set(_this2.swiperList, 2, prev2Month);
                            }
                        } else if (_this2.swiperItemIndex === 2) {
                            /* 当前页为第三页 */
                            /* 下滑，进入第一页; 开始顺序 => [next, prev, cur], 结束顺序 => [next, next2, cur] */
                            if (currentIndex === 0) {
                                _this2.$set(_this2.swiperList, 1, next2Month);
                            } else {
                                /* 上滑，进入第二页; 开始顺序 => [next, prev, cur], 结束顺序 => [prev2, prev, cur] */
                                _this2.$set(_this2.swiperList, 0, prev2Month);
                            }
                        }
                        _this2.swiperItemIndex = currentIndex;

                        _this2.setSelectedDay();
                        _this2.$emit('calendar-change', _this2.currentValue);
                    });
                });
            }
        }
    },
    render: function render() {
        var _this3 = this;

        var h = arguments[0];
        var vertical = this.vertical,
            showLastMonth = this.showLastMonth,
            showNextMonth = this.showNextMonth,
            workDate = this.workDate,
            infoDate = this.infoDate,
            touchable = this.touchable,
            mouseable = this.mouseable,
            styleHeight = this.styleHeight,
            swiperList = this.swiperList,
            weekList = this.weekList;


        return h(
            'div',
            { 'class': 'sn-calendar' },
            [h(
                'div',
                { 'class': 'sn-calendar-weekday' },
                [weekList.map(function (week) {
                    return h(
                        'div',
                        { 'class': 'sn-calendar-weekday-item' },
                        [h('div', [week])]
                    );
                })]
            ), h(
                'div',
                { 'class': 'sn-calendar-panel' },
                [h(
                    _carousel2['default'],
                    {
                        ref: 'carousel',
                        attrs: { 'show-indicators': false,

                            vertical: vertical,
                            touchable: touchable,
                            mouseable: mouseable
                        },
                        on: {
                            'change': this.onCalendarChange
                        },
                        style: { height: styleHeight }
                    },
                    [swiperList.map(function (month) {
                        return h(_carouselItem2['default']
                        // style={{ height: styleHeight }}
                        , [h(
                            'div',
                            { 'class': 'sn-calendar-date' },
                            [month.year + '-' + month.month_str]
                        ), h(
                            'div',
                            { 'class': 'sn-calendar-month' },
                            [month.days.map(function (row, k1) {
                                return h(
                                    'div',
                                    { 'class': 'month-row' },
                                    [row.map(function (item, k2) {
                                        var workingDay = void 0,
                                            infoDay = void 0;
                                        if (workDate && workDate instanceof Array && workDate.length) {
                                            for (var i in workDate) {
                                                if (workDate[i].date === item.formatedDate) {
                                                    workingDay = workDate[i];
                                                }
                                            }
                                        }
                                        if (infoDate && infoDate instanceof Array && infoDate.length) {
                                            var _iteratorNormalCompletion = true;
                                            var _didIteratorError = false;
                                            var _iteratorError = undefined;

                                            try {
                                                for (var _iterator = infoDate[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
                                                    var infoItem = _step.value;

                                                    if (infoItem && typeof infoItem === 'string') {
                                                        if (infoItem === item.formatedDate) {
                                                            infoDay = {
                                                                date: infoItem
                                                            };
                                                        }
                                                    } else {
                                                        if (infoItem.date === item.formatedDate) {
                                                            infoDay = infoItem;
                                                        }
                                                    }
                                                }
                                            } catch (err) {
                                                _didIteratorError = true;
                                                _iteratorError = err;
                                            } finally {
                                                try {
                                                    if (!_iteratorNormalCompletion && _iterator['return']) {
                                                        _iterator['return']();
                                                    }
                                                } finally {
                                                    if (_didIteratorError) {
                                                        throw _iteratorError;
                                                    }
                                                }
                                            }
                                        }

                                        return h(
                                            'div',
                                            {
                                                'class': {
                                                    day: true,
                                                    'day-in-last-month': item.isLastMonth,
                                                    'day-in-next-month': item.isNextMonth
                                                }
                                            },
                                            [item.isCurMonth || item.isLastMonth && showLastMonth || item.isNextMonth && showNextMonth ? h(
                                                'div',
                                                {
                                                    'class': 'day-pack',
                                                    on: {
                                                        'click': function click(event) {
                                                            return _this3.select(event, k1, k2, item);
                                                        }
                                                    }
                                                },
                                                [h(
                                                    'div',
                                                    {
                                                        'class': {
                                                            today: item.isToday,
                                                            active: item.isCurrent,
                                                            disabled: item.isDisabled
                                                        }
                                                    },
                                                    [h(
                                                        'div',
                                                        { 'class': 'day-pack-cell' },
                                                        [h(
                                                            'div',
                                                            { 'class': 'header' },
                                                            [workingDay ? workingDay.isWorking ? h(
                                                                'span',
                                                                { 'class': 'working' },
                                                                ['\u73ED']
                                                            ) : h(
                                                                'span',
                                                                { 'class': 'rest' },
                                                                ['\u4F11']
                                                            ) : null]
                                                        ), h(
                                                            'div',
                                                            {
                                                                'class': {
                                                                    middle: true,
                                                                    isHoliday: item.isHoliday,
                                                                    hidden: item.dayHide
                                                                }
                                                            },
                                                            [item.isToday ? '今' : item.day]
                                                        ), h(
                                                            'div',
                                                            { 'class': 'footer' },
                                                            [infoDay ? h('span', {
                                                                'class': (0, _defineProperty3['default'])({
                                                                    'info-dot': true
                                                                }, infoDay['class'], infoDay['class']),
                                                                style: {
                                                                    borderColor: infoDay.color ? infoDay.color : ''
                                                                }
                                                            }) : null]
                                                        )]
                                                    )]
                                                )]
                                            ) : null]
                                        );
                                    })]
                                );
                            })]
                        )]);
                    })]
                )]
            )]
        );
    }
};

Calendar.install = function (Vue) {
    Vue.component(Calendar.name, Calendar);
};

exports['default'] = Calendar;
module.exports = exports.default;