/**
 * Created by liuling on 2017/3/9.
 */
var dataUtils = (function () {
    //'use strict';
    /**
     * 输入日期,返回格式化后的字符串,类似java中的SimpleDateFormat
     * @param date
     * @param fmt
     * @returns {*}
     */
    var dateFormat = function (date, fmt) {
        if ((typeof date == 'object') && date.constructor == Date) {

        } else {
            date = new Date(date);
        }
        const o = {
            "M+": date.getMonth() + 1, //月份
            "d+": date.getDate(), //日
            "h+": date.getHours(), //小时
            "m+": date.getMinutes(), //分
            "s+": date.getSeconds(), //秒
            "q+": Math.floor((date.getMonth() + 3) / 3), //季度
            "S": date.getMilliseconds() //毫秒
        };
        if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    };

    //传入时间的本月第一天
    var monthFirstDay = function (date) {
        if ((typeof date == 'object') && date.constructor == Date) {

        } else {
            date = new Date(date);
        }
        date.setDate(1);
        return dateFormat(date, 'yyyy-MM-dd');
    };

    var monthLastDay = function (date) {
        if ((typeof date == 'object') && date.constructor == Date) {

        } else {
            date = new Date(date);
        }
        var year = date.getFullYear();
        var month = date.getMonth() + 1;
        if (month > 12) {
            year++;
            month -= 12;
        }
        var nextMonthFirstDate = new Date(year, month, 1);
        var monthLasyDate = new Date(nextMonthFirstDate.getTime() - 1000 * 60 * 60 * 24);
        return dateFormat(monthLasyDate, 'yyyy-MM-dd');

    };

    var getYearAndWeek = function (date) {
        if (!date || date == '') {
            date = new Date();
        }
        var yearAndMonth = dateFormat(date, 'yyyy年MM月');
        return yearAndMonth + '第' + getWeekOfMonth(date) + '周';
    };

    var getWeekOfMonth = function (date) {
        var weekStart = 1;
        var dayOfWeek = date.getDay();
        var day = date.getDate();
        return Math.ceil((day - dayOfWeek - 1) / 7) + ((dayOfWeek >= weekStart) ? 1 : 0);
    };

    return {
        dateFormat: dateFormat,
        getYearAndWeek: getYearAndWeek,
        monthFirstDay: monthFirstDay,
        monthLastDay: monthLastDay
    }
})();