;(function (factory) {
    if (typeof define === "function" && (define.amd || define.cmd) && !jQuery) {
        // AMD或CMD
        define(["jquery"], factory);
    } else if (typeof module === 'object' && module.exports) {
        // Node/CommonJS
        module.exports = function (root, jQuery) {
            if (jQuery === undefined) {
                if (typeof window !== 'undefined') {
                    jQuery = require('jquery');
                } else {
                    jQuery = require('jquery')(root);
                }
            }
            factory(jQuery);
            return jQuery;
        };
    } else {
        //Browser globals
        factory(jQuery);
    }
}(function ($) {

    //配置参数
    var defaults = {
        activeDate: '',
        yearToggle: '.year-toggle',
        monthToggle: '.month-toggle',
        contentEle: '.calendar-main',
        isInit: !0,
        yearRange: [12, 0],
        onSelect: function () {
        },
        onCalendarChange: function () {
        },
        onUpdateView: function () {
        },
        onInit: function () {
        }
    };

    // 修复数字为2位数
    var fixNumer = function (num) {
        return ('0' + num).slice(-2);
    };

    // 构造函数
    var DataPicker = function (element, options) {

        //全局变量
        var opts = options, //配置
            $document = $(document),
            $obj = $(element), // 包裹元素
            $yearToggle = $obj.find(options.yearToggle),
            $monthToggle = $obj.find(options.monthToggle),
            yearRange = options.yearRange,
            activeDate = options.activeDate,
            $contentEle = $obj.find(options.contentEle),
            _this = this; // 保存this对象

        var initYear, initMonth, initDay, // 初始化年月日
            year, month, day, // 保存当前的年月日
            yearStart, yearEnd; // 年份范围

        _this.init = function () {
            var activeDate = $('input[name="activeDate"]').val();
            var storageTimeYear= sessionStorage.getItem("year");
            var storageTimeMonth= sessionStorage.getItem("month");
            var storageTimeDay= sessionStorage.getItem("day");
            if(storageTimeYear && storageTimeMonth && storageTimeDay){
                activeDate=storageTimeYear+"-"+storageTimeMonth+"-"+storageTimeDay;
            }
            //获取当前期刊时间
            activeDate = activeDate ? new Date(activeDate) : new Date();
            console.log(activeDate);

            initYear = activeDate.getFullYear();
            initMonth = activeDate.getMonth() + 1;
            initDay = activeDate.getDate();

            year = initYear;
            month = initMonth;
            day = initDay;

            yearStart = year - yearRange[0];
            yearEnd = year + yearRange[1];

            var datenow = new Date();
            var yearnow = datenow.getFullYear();
            yearStart = 2007;
            yearEnd = yearnow;
        };

        _this.renderDom = function () {

            var weekStart = new Date(year, month - 1, 1).getDay(), // 本月1号是周几
                dayCounts = new Date(year, month, 0).getDate(), // 当前月天数
                whiteNumBefore = weekStart > 0 ? weekStart : 0; // 本月前面空的日期
            whiteNumAfter = (dayCounts + whiteNumBefore) % 7 === 0 ? 0 : (Math.floor((dayCounts + whiteNumBefore) / 7) + 1) * 7 - (whiteNumBefore + dayCounts); // 本月后面空的日期
            domStr = '';

            for (var i = 0; i < whiteNumBefore; i++) {
                domStr += '<span class="day disabled"></span>';
            }

            for (var i = 1; i <= dayCounts; i++) {
                if (i === initDay && month === initMonth && year === initYear) {
                    domStr += '<span class="day day-valid disabled active">' + i + '</span>';
                } else {
                    domStr += '<span class="day day-valid disabled">' + i + '</span>';
                }
            }
            $contentEle.html(domStr);
            if (options.isInit) { // 初始化
                options.onInit && options.onInit(initYear + '-' + fixNumer(initMonth) + '-' + fixNumer(initDay));
                isInit = !1;
            }

            _this.updateDateSelect();

            options.onUpdateView && options.onUpdateView({year: year, month: month});
        };

        _this.updateDateSelect = function () {

            var yearHtml = '',
                monthHtml = '';

            for (var i = yearStart; i <= yearEnd; i++) {

                if (i === year) {

                    yearHtml += '<option value="' + i + '" selected="selected">' + i + '</option>';
                } else {

                    yearHtml += '<option value="' + i + '">' + i + '</option>';
                }
            }

            $yearToggle.find('.date-select').html(yearHtml);

            for (var i = 1; i <= 12; i++) {

                if (i === month) {

                    monthHtml += '<option value="' + i + '" selected="selected">' + i + '</option>';
                } else {

                    monthHtml += '<option value="' + i + '">' + i + '</option>';
                }
            }

            $monthToggle.find('.date-select').html(monthHtml);
        };

        _this.bindEvents = function () {

            var $yearSelect = $yearToggle.find('.date-select'),
                $monthSelect = $monthToggle.find('.date-select');

            $monthToggle.on('click', '.icon-toggle-prev', function () {

                if (year > yearStart || month > 0) {

                    month--;

                    if (month === 0) {

                        month = 12;
                        year--;
                    }

                    options.onCalendarChange && options.onCalendarChange({year: year, month: month});
                    _this.renderDom();
                }
            });

            $monthToggle.on('click', '.icon-toggle-next', function () {

                if (year < yearEnd || month < 12) {

                    month++;

                    if (month === 13) {

                        month = 1;
                        year++;
                    }

                    options.onCalendarChange && options.onCalendarChange({year: year, month: month});
                    _this.renderDom();
                }
            });

            $yearToggle.on('click', '.icon-toggle-prev', function () {

                if (year > yearStart) {

                    year--;

                    options.onCalendarChange && options.onCalendarChange({year: year, month: month});
                    _this.renderDom();
                }
            });

            $yearToggle.on('click', '.icon-toggle-next', function () {

                if (year < yearEnd) {

                    year++;

                    options.onCalendarChange && options.onCalendarChange({year: year, month: month});
                    _this.renderDom();
                }
            });

            $yearSelect.change(function (e) {

                year = +$(this).val();

                options.onCalendarChange && options.onCalendarChange({year: year, month: month});
                _this.renderDom();
            });

            $monthSelect.change(function (e) {

                month = +$(this).val();

                options.onCalendarChange && options.onCalendarChange({year: year, month: month});
                _this.renderDom();
            });

            $obj.on('click', '.day', function (e) {

                var $this = $(this);

                if (!$this.hasClass('disabled') && !$this.hasClass('active')) {

                    $this.addClass('active').siblings().removeClass('active');

                    var curDay = $this.text();

                    sessionStorage.setItem("year", year);
                    sessionStorage.setItem("month", fixNumer(month));
                    sessionStorage.setItem("day", fixNumer(curDay));
                    //var dddd=sessionStorage.getItem("DateList");
                    options.onSelect && options.onSelect(year + '-' + fixNumer(month) + '-' + fixNumer(curDay), $this);

                    window.location.href = "https://jinrigushitwo.gushitv.com/#/?date="+year + '-' + fixNumer(month) + '-' + fixNumer(curDay);
                    setTimeout(()=>{
                        window.location.reload();
                    },100)
                }
            });
        };

        _this.render = function () {

            _this.init();
            _this.renderDom();
            _this.bindEvents();
        };

        _this.render();
    };

    $.fn.datePicker = function (parameter, callback) {

        if (typeof parameter == 'function') { //重载
            callback = parameter;
            parameter = {};
        } else {
            parameter = parameter || {};
            callback = callback || function () {
            };
        }

        var options = $.extend({}, defaults, parameter);

        return this.each(function () {
            var datePicker = new DataPicker(this, options);
            callback(datePicker);
        });
    };
}));
