var gs_xml_doc;
var nvese;
var week = [$.i18n.prop("i18n-systemmanit-week7"), $.i18n.prop("i18n-systemmanit-week1"), $.i18n.prop("i18n-systemmanit-week2"), $.i18n.prop("i18n-systemmanit-week3"), $.i18n.prop("i18n-systemmanit-week4"), $.i18n.prop("i18n-systemmanit-week5"), $.i18n.prop("i18n-systemmanit-week6")]
$(document).ready(function() {
    if (localStorage.getItem('time')) {
        $("#loginout").val(localStorage.getItem('time'));
    } else {
        $("#loginout").val(5)
    }
    initSystemManit();
    getautomaintenancecfgfromdevice();
    $("#arMode").change(function() { //维护模式
        // if ($(this).select2("val") == "everyweek") { //周
        //     $("#weekplan").show();
        //     neartime();
        // }
        // else {
        //     $("#weekplan").hide();
        //     //对比当前日期是几点
        //     neardate();
        //     $(".datatime").show();
        //     $("#hour").text($("#clearhour").val());
        // }
        // 如果每周的星期模式全没选中 那么就给全选中
        if (isAllSeclect() == '0000000') {
            var arr = $("input[name='Wpaln']");
            for (index = 0; index < arr.length; index++) {
                arr[index].checked = true;
            };
        }
        MaintenanceModeChanngeEvent()
    });
    $("input[name='Wpaln']").change(function() {
        neartime();
    });
    // 点击保存
    $("#SetAuto").click(function() {
        if ("admin" == config.user || "super_admin" == config.user) {
            SetAutoMaintenanceCfg()
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
        }
    })
});

function validateInput(event) {
    var input = event.target.value;
    // 转换为数字（更安全的转换方式）
    var number = parseInt(input, 10);
    
    // 验证是否是整数并且在5到30之间（兼容IE）
    var isInteger = (number % 1 === 0) || (number === parseInt(number, 10));
    var isValidRange = number >= 5 && number <= 30;
    
    // 如果验证失败则重置为5
    if (!isInteger || !isValidRange || isNaN(number)) {
        number = 5;
        event.target.value = 5;
    }
    
    // 确保存储的是数值而不是字符串
    localStorage.setItem("time", number);
}

function initSystemManit() {
    if (!$('.select2').hasClass('select2-offscreen')) {
        $(".select2").select2({
            minimumResultsForSearch: -1,
            width: 220
        }).on('click', function() {
            $('.datetimepicker').hide();
        });
    }
    for (var index = 0; index < week.length; index++) {
        $('<label class="checkbox-inline"><input type="checkbox" name="Wpaln"><span>' + week[index] + '</span></label>').appendTo($("#week"))

    }
    $("#wh-time").datetimepicker({
        format: 'hh:ii',
        language: 'zh-CN',
        autoclose: 1,
        todayHighlight: 0,
        startView: 1, //日期时间选择器打开之后首先显示的视图。 可接受的值：
        minView: 0,
        maxView: 1,
        minuteStep: 1,
    }).change(function(e) {
        if ($("#arMode").select2('val') == 'everyday') {
            everyDayTime();
        } else {
            neartime();
        }
        $(".datatime").text($(this).val())
        $("#ar_ymd").val($("#ar_ymd").val().substring(0, 10) + " " + $(this).val())
    }).click(function(e) {
        e.currentTarget.blur();
    })
    $("#ar_ymd").datetimepicker({
        format: "yyyy-mm-dd hh:ii",
        todayBtn: true, //打开底部今天按钮,false为关闭
        autoclose: true, // 选择日期后关闭
        todayHighlight: true, //高亮显示当前日期
        language: 'zh-CN', //显示语言为中文
        startDate: new Date(), //限制时间范围
        minuteStep: 1,
    }).change(function() {
        //获取小时与分钟
        var t = $(this).val().substring(11, 16);
        $("#wh-time").val(t);
    }).click(function(e) {
        e.currentTarget.blur();
    })
}
/*************************************************
 Function:
 Description:  设置自动维护配置到设备端
 **************************************************/
function SetAutoMaintenanceCfg() {
    var arMode = $("#arMode").select2("val")
    var strEnable;
    var strMode;
    if (arMode == "disable") {
        strEnable = "false";
        strMode = "";
    } else if (arMode == "everyday") {
        strEnable = "true";
        strMode = "everyday";
    } else if (arMode == "everyweek") {
        strEnable = "true";
        strMode = "everyweek";
    } else if (arMode == "once") {
        strEnable = "true";
        strMode = "once";
    }
    var elarr = $("input[name='Wpaln']");
    var arWeekPlanMask = '';
    for (var i = 0; i < 7; i++) {
        if (elarr[i].checked) {
            arWeekPlanMask += '1'
        } else {
            arWeekPlanMask += '0'
        };
    }
    if (arWeekPlanMask === "0000000") {
        $.optionBootoast($.i18n.prop("i18n-systemmanit-msg"), "danger");
        return;
    }
    var save_hm = $("#ar_ymd").val();
    if (arMode == "everyweek") {
        if (elarr[new Date().getDay()].checked) {
            var data = $("#newdata").text() + " " + $("#hour").text();
            var settime = new Date(data)
            var nowtime = new Date()
            if (settime.getTime() < nowtime.getTime()) {
                $.optionBootoast($.i18n.prop("i18n-systemmanit-msg"), "danger");
                return;
            }
        }
    }
    // console.log('elarr',elarr);
    // let index = new Date().getDay()
    // console.log('index',index);
    // console.log('save_hm',save_hm);
    var y = save_hm.substring(0, 4),
        ms = save_hm.substring(5, 7),
        d = save_hm.substring(8, 10),
        h = save_hm.substring(11, 13),
        m = save_hm.substring(14, 16)
    var MaintenanceTime = y + ms + d + "T" + h + m + "00";
    var cyXml = gs_xml_doc;
    $(cyXml).find('AutoMaintenance').eq(0).find('Enable').eq(0).text(strEnable);
    $(cyXml).find('AutoMaintenance').eq(0).find('Mode').eq(0).text(strMode);
    $(cyXml).find('AutoMaintenance').eq(0).find('WeekDayMask').eq(0).text(arWeekPlanMask);
    $(cyXml).find('AutoMaintenance').eq(0).find('MaintemanceTime').eq(0).text(MaintenanceTime);
    //保存
    var cyURL = config.baseUrl + "/System/DeviceAutoMaintenance";
    $.ajax({
        type: "PUT",
        url: cyURL,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr)
            getautomaintenancecfgfromdevice()
        }
    });

}

function neardate() {
    // 获取当前电脑系统时间
    var now = new Date();
    var currentHour = now.getHours();
    var currentMinute = now.getMinutes();
    // 获取输入框的小时和分钟
    var inputHour = parseInt($("#wh-time").val().split(":")[0]);
    var inputMinute = parseInt($("#wh-time").val().split(":")[1]);
    var selectedDays = [];
    var arr = $("input[name='Wpaln']");
    for (let index = 0; index < arr.length; index++) {
        if (arr[index].checked) {
            selectedDays.push(index);
        }
    }
    if (currentHour > inputHour || (currentHour == inputHour && currentMinute > inputMinute)) {
        //维护时间小于当天 那么就不包括今天从后找
        var now = new Date();
        var today = now.getDay();
        var nextSelectedDay;
        for (var i = 1; i <= 7; i++) {
            var nextDay = (today + i) % 7;
            if (selectedDays.indexOf(nextDay) != -1) {
                nextSelectedDay = nextDay;
                break;
            }
        }
        var now = new Date();
        var today = now.getDay();
        var dayDifference = (nextSelectedDay >= today) ? nextSelectedDay - today : 7 - (today - nextSelectedDay);
        if (dayDifference == 0) {
            dayDifference = 7
        }
        $("#newdata").text(getSelectedDate(dayDifference));
    } else { //维护时间大于当天小时与分钟 那就选中今天
        $("#newdata").text(getSelectedDate(0));
    }
}

function everyDayTime() {
    var now = new Date();
    var currentHour = now.getHours();
    var currentMinute = now.getMinutes();
    // 获取输入框的小时和分钟
    var inputHour = parseInt($("#wh-time").val().split(":")[0]);
    var inputMinute = parseInt($("#wh-time").val().split(":")[1]);
    if (currentHour > inputHour || (currentHour == inputHour && currentMinute > inputMinute)) {
        // 维护时间小于当天 那就选中第二天
        $("#newdata").text(getSelectedDate(1));

    } else { // 维护时间大于当天 那就选中当天
        $("#newdata").text(getSelectedDate(0));
    }
}

function getSelectedDate(days) {
    var currentDate = new Date(); // 获取当前日期
    currentDate.setDate(currentDate.getDate() + days); // 增加天数
    var year = currentDate.getFullYear(); // 获取年份
    var month = currentDate.getMonth() + 1; // 获取月份（注意：月份从0开始，需要+1）
    var date = currentDate.getDate(); // 获取日期
    var formattedDate = year + '-' + (month < 10 ? "0" + month : month) + '-' + (date < 10 ? "0" + date : date); // 格式化日期，这里使用yyyy-mm-dd的格式
    return formattedDate;

}

function getSpeTime(timeStr) {
    // timeStr是毫秒值
    // 获取年份
    var year = new Date(timeStr).getFullYear();
    //获取月份，获取的月份比实际小1，所以需要+1
    var month = new Date(timeStr).getMonth() + 1;
    //获取日
    var date = new Date(timeStr).getDate();
    //获取时
    month = month < 10 ? '0' + month : month;
    date = date < 10 ? '0' + date : date;
    return year + "-" + month + "-" + date

}

function neartime() {
    var arr = $("input[name='Wpaln']");
    var newdata = new Date().getDay() //获取今天日期对应的周几  5
    var index = 0
    for (index = 0; index < 7; index++) {
        var data = (newdata + index) % 7
        if (arr[data].checked) {
            break;
        };
    };
    if (index < 7) {
        if (index == 0) { //当天周期被选中
            //判断小时是否大于当前小时
            neardate();
        } else {
            var currenttime = new Date().getTime() + (60 * 60 * 24 * 1000) * index;
            $("#newdata").text(getSpeTime(currenttime));
        };
        $(".datatime").show();
    } else {
        $("#newdata").text($.i18n.prop("i18n-systemmanit-msg")); //清零时间设置非法
        $(".datatime").hide();
    }
}
/*************************************************
 Function:
 Description:  从设备端获取自动维护的数据
 **************************************************/
function getautomaintenancecfgfromdevice() {
    $.ajax({
        url: config.baseUrl + "/System/DeviceAutoMaintenance",
        type: "GET",
        async: true,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            //获取数据成功之后，刷新界面
            gs_xml_doc = xmlDoc;
            //初始化数据
            var strEnable = $(xmlDoc).find('AutoMaintenance').eq(0).find('Enable').eq(0).text();
            var strMode = $(xmlDoc).find('AutoMaintenance').eq(0).find('Mode').eq(0).text();
            var strWeekDayMask = $(xmlDoc).find('AutoMaintenance').eq(0).find('WeekDayMask').eq(0).text();
            var strMaintemanceTime = $(xmlDoc).find('AutoMaintenance').eq(0).find('MaintemanceTime').eq(0).text();
            //界面显示
            if (strEnable == "false") {
                $("#arMode").select2("val", "disable");
            } else if (strEnable == "true") {
                $("#arMode").select2("val", strMode);
            }
            var strWeekDayMaskarr = strWeekDayMask.split("");
            for (var index = 0; index < strWeekDayMaskarr.length; index++) {
                if (strWeekDayMaskarr[index] == "1") {
                    $("input[name='Wpaln']").eq(index).prop('checked', true);
                } else {
                    $("input[name='ChannS']").eq(index).prop('checked', false);
                }
            }
            var date_year = strMaintemanceTime.toString().substring(0, 4);
            var date_mon = strMaintemanceTime.toString().substring(4, 6);
            var date_day = strMaintemanceTime.toString().substring(6, 8);
            var date_hour = strMaintemanceTime.toString().substring(9, 11);
            var date_min = strMaintemanceTime.toString().substring(11, 13);
            //渲染维护时间 与单次维护时间
            $("#wh-time").val(date_hour + ":" + date_min);
            $("#hour").text(date_hour + ":" + date_min);
            if (date_year == '0000') {
                var now = new Date();
                var currentHour = now.getHours();
                var currentMinute = now.getMinutes();
                // 获取输入框的小时和分钟
                var inputHour = date_hour;
                var inputMinute = date_min;
                if (currentHour > inputHour || (currentHour == inputHour && currentMinute > inputMinute)) {
                    // 维护时间小于当天 那就选中第二天
                    $("#ar_ymd").val(getSelectedDate(1) + " " + date_hour + ":" + date_min);

                } else { // 维护时间大于当天 那就选中当天
                    $("#ar_ymd").val(getSelectedDate(0) + " " + date_hour + ":" + date_min);
                }
            } else {
                $("#ar_ymd").val(date_year + "-" + date_mon + "-" + date_day + " " + date_hour + ":" + date_min);
            }
            MaintenanceModeChanngeEvent() //改变维护模式显示隐藏
                // 根据周算出下次维护时间
                // neartime();


        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}
/*************************************************
 Function:
 Description:  维护模式更改事件
 **************************************************/
function MaintenanceModeChanngeEvent() {
    if ($("#arMode").select2("val") == "disable") {
        $("#trWeekPlan").hide();
        $("#trMaintenanceTime").hide();
        $("#trNextMaintenanceTime").hide();
    } else if ($("#arMode").select2("val") == "everyweek") {
        $("#trWeekPlan").show();
        $("#trMaintenanceTime").show();
        $("#ar_ymd").hide();
        $('.datetimepicker-hours .table-condensed thead').css('display', 'none');
        $('.datetimepicker-hours .table-condensed').css('width', '100%')
        $('.datetimepicker-minutes .table-condensed thead').css('display', 'none');
        $('.datetimepicker-minutes .table-condensed').css('width', '100%')
        $("#wh-time").show();
        $("#trNextMaintenanceTime").show();
        neartime()
    } else if ($("#arMode").select2("val") == "everyday") {
        $("#trWeekPlan").hide();
        $("#trMaintenanceTime").show();
        $("#ar_ymd").hide();
        $('.datetimepicker-hours .table-condensed thead').css('display', 'none');
        $('.datetimepicker-hours .table-condensed').css('width', '100%')
        $('.datetimepicker-minutes .table-condensed thead').css('display', 'none');
        $('.datetimepicker-minutes .table-condensed').css('width', '100%')
        $("#wh-time").show();
        $("#trNextMaintenanceTime").show();
        //对比当前日期是几点
        everyDayTime();
        $(".datatime").show();
        $("#hour").text($("#wh-time").val());
    } else if ($("#arMode").select2("val") == "once") {
        $("#trWeekPlan").hide();
        $("#trMaintenanceTime").show();
        $("#ar_ymd").show();
        $('.datetimepicker-hours .table-condensed thead').css('display', 'none');
        $('.datetimepicker-hours .table-condensed').css('width', '100%')
        $('.datetimepicker-minutes .table-condensed thead').css('display', 'none');
        $('.datetimepicker-minutes .table-condensed').css('width', '100%')
        $("#wh-time").hide();
        $("#trNextMaintenanceTime").hide();
    }
}

/*************************************************
 Function:        setDefault
 Description:     简单恢复
 *************************************************/
function setDefault() {
    if ("admin" == config.user || config.user == "super_admin") {
        nvese = 1
        document.getElementById("codesh").innerHTML = $.i18n.prop("i18n-restore-to-default-state");
        $("#myModalt").modal('show');
    } else {
        $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
    }

}

function restoreDefault() {
    if ("admin" == config.user || config.user == "super_admin") {
        nvese = 2
        document.getElementById("codesh").innerHTML = $.i18n.prop("i18n-restore-to-factory-settings");
        $("#myModalt").modal('show');
    } else {
        $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
    }

}

function changewHo() {
    if (nvese == 2) {
        $("#myModalt").modal('hide');
        var cyXml = "";
        var cyURL = config.baseUrl + "/System/FactoryDefaultV2";
        $.ajax({
            type: "PUT",
            url: cyURL,
            processData: false,
            data: cyXml,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            complete: function(xhr, textStatus) {
                SaveState(xhr);
            }
        });
    } else if (nvese == 1) {
        $("#myModalt").modal('hide');
        var cyXml = "";
        var cyURL = config.baseUrl + "/System/FactoryDefault";
        $.ajax({
            type: "PUT",
            url: cyURL,
            processData: false,
            data: cyXml,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            complete: function(xhr, textStatus) {
                SaveState(xhr);
            }
        });

    } else if (nvese == 3) {
        $("#myModalt").modal('hide');
        var cyXml = "";
        var cyURL = config.baseUrl + "/System/Reboot";
        $.ajax({
            type: "PUT",
            url: cyURL,
            processData: false,
            data: cyXml,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("If-Modified-Since", "0");
            },
            complete: function(xhr, textStatus) {
                SaveState(xhr);
                // var xmlDoc = xhr.responseXML;
                // var state = $(xmlDoc).find('statusCode').eq(0).text();
                // if ("0" == state) {
                //     $.optionBootoast($.i18n.prop("i18n-systemmanit-msg1"), "success");
                // } else {
                //     $.optionBootoast($.i18n.prop("i18n-systemmanit-msg2"), "danger");
                // }
            }
        });
    }
}

function setReboot() {
    if ("admin" == config.user || config.user == "super_admin") {
        nvese = 3
        document.getElementById("codesh").innerHTML = $.i18n.prop("i18n-restart-device");
        $("#myModalt").modal('show');
    } else {
        $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
    }

}

function isAllSeclect() {
    var elarr = $("input[name='Wpaln']");
    var arWeekPlanMask = '';
    for (var i = 0; i < 7; i++) {
        if (elarr[i].checked) {
            arWeekPlanMask += '1'
        } else {
            arWeekPlanMask += '0'
        };
    }
    return arWeekPlanMask;
}