// 页面对象
var Page = {};

Page.initPhonePage = function () {

    var userAgentInfo = navigator.userAgent;
    var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
    var local_url = window.location.href;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) {
            var sURL2 = local_url.replace("/#/", "/h5/#/");
            console.log(sURL2);
            sessionStorage.removeItem('DateIndexH5');
            sessionStorage.removeItem('DateIndex');
            sessionStorage.removeItem('DateListH5');
            sessionStorage.removeItem('DateList');
            sessionStorage.removeItem('year');
            sessionStorage.removeItem('month');
            sessionStorage.removeItem('day');
            sessionStorage.removeItem('index');
            sessionStorage.removeItem('newInfo');
            window.location.href = sURL2;
        }
    }
};

//日历牌--开始
// 显示当前时间
Page.initShowCurDate = function () {
    var dateStr = Utils.dateFormat(Date.now(), 'yyyy年MM月dd日');
    $('#cur_date').text(dateStr);
};

// 初始化日历效果
Page.initCalendar = function () {
    var $calendar = $('#calendar');

    function loadData(date) {
        console.log(date)
        var m = date.year.toString() + "-" + (date.month < 10 ? ("0" + date.month) : date.month).toString();
        var navData = getPaper(m);
        var navUrl = "";
        $calendar.find('.day-valid').each(function (idx, item) {
            var index = navData["day"].indexOf(parseInt(idx + 1));
            if (index > -1) {
                $(item).removeClass('disabled');
                //navUrl = "../../" + (navData["date"][index]).match(/(\d{4}-\d{2})-(\d{2})/i)[1] + navData["url"][index].replace("../", "/")
                //$(item).attr('data-url', navData["date"][index]);
                //$(item).attr('data-url', navUrl);
            }
        });
    }

    $calendar.datePicker({
        activeDate: '',
        yearRange: [3, 2],
        onUpdateView: loadData,
        onCalendarChange: loadData,
        onSelect: function (date, $day) {
            var url = $day.attr('data-url');
            url && (location.href = url);
        }
    });
};

//获取当前页日期
function getDate(str) {
    var url = location.href;
    var re = /(\d{4})\-(\d{2})\/(\d{2})/;
    var r = url.match(re);
    //精确到日
    if (!r) {
        return;
    }
    if (str == "day") {
        var date = r[1] + "-" + r[2] + "-" + r[3];
        //精确到月
    } else if (str == "month") {
        var date = r[1] + "-" + r[2];
    }
    return date;
}

//获取当前月份报纸xml数据
function getPaper(m) {
    console.log(m);
    var myXmlUrl = `/dist/public/static/data/${m}.json`;
    var data = {'day': [], 'url': [], 'date': []};
    $.ajax({
        data:{'date':m},
        url: "https://jinrigushitwo.gushitv.com/api/dzb/date/dateList",
        type: 'POST',
        dataType: 'json',
        async: false,
        timeout: 1000,
        success: function (d) {
            console.log(d);
            var date = new Array();
            var day = new Array();
            var url = new Array();
            var url2 = new Array();

            d.data.forEach(function (item) {
                date.push(item.datetime);
                day.push(parseInt(item.datetime.split("-")[2]));
            });
            data = {"day": day, "url": url, "date": date};
            console.log(data);
        }
    });
    return data;
}

// 初始化跳转至日期
Page.initJump2Date = function () {

    $('#submit_btn').click(function () {
        var year = +$('#input_year').val(),
            month = +$('#input_month').val(),
            day = +$('#input_day').val();

        var date = new Date(year + '/' + month + '/' + day);
        console.log(date);
        if (date.getFullYear() === year && (date.getMonth() + 1) === month && date.getDate() === day) {
            //console.log('时间输入正确, 时间为' + year + '年' + month + '月' + day + '日');
            var m = year.toString() + "-" + ((date.getMonth() + 1) < 10 ? ("0" + (date.getMonth() + 1)) : (date.getMonth() + 1)).toString();
            var navData = getPaper(m);
            console.log(navData);
            var url = "";

            for (var idx = 0; idx < navData["day"].length; idx++) {
                if (navData["day"][idx] === day)
                    url = "/#/?time=" + year + "-" + month + "-" + day;
            }
            if (url != "")
            {
                window.location.href = "https://jinrigushitwo.gushitv.com/#/?date="+year + '-' + fixNumer(month) + '-' + fixNumer(day);
                setTimeout(()=>{
                    window.location.reload();
                },100)
                // sessionStorage.setItem("year", year);
                // sessionStorage.setItem("month", month);
                // sessionStorage.setItem("day", day);
                //window.location.reload();
            }
            else{
                alert("未查询到对应日期的报纸");
            }
        } else {
            alert('时间输入格式不正确');
        }
    });
};
//日历牌-结束

var fixNumer = function (num) {
    return ('0' + num).slice(-2);
};
/**
 * =============================================================================
 *                                  Dom Ready
 * =============================================================================
 */
$(function () {
    Page.initPhonePage();
    Page.initShowCurDate();
    Page.initCalendar();
    Page.initJump2Date();

    $('.paperarea').tooltip({
        track: true,
        content: function () {
            var element = $(this);
            var text = element.attr("title");
            if (text == '') {
                $(this).tooltip("option", "hide");
            } else {
                return '<span>' + text + '</span>';
            }
        }
    });
});
