var size_change_timeout = null;
var ws = null;
var mainpage = null;
//当页面加载完成
window.onload = function () {
    change_size();//页面组件尺寸字段调整
    InitWebsocket();//初始化websocket
    var back = JSON.parse(webui_hook_GetSetting("")); //重定向到易语言获取设置信息
    $("body").addClass("mdui-theme-primary-" + back.ThemeColor);
    $("body").addClass("mdui-theme-accent-" + back.AccentColor);
    window.isNight = false;//是否为夜间模式
    if (back.Night === "AllOpen") {
        //当夜间模式始终开启的情况下
        window.isNight = true;
        $("body").addClass("mdui-theme-layout-dark");
        mdui.mutation();
    } else if (back.Night === "FollowTime") {
        //当夜间模式设置为跟随时间情况下
        showNightChange();
        setInterval("showNightChange()", 30 * 60 * 1000);//三十分钟查询一次
    }
    //主题色设置完成后，调整加载层的背景色
    $("#loading_box").css("background-color", $("body").css("background-color"));
};

window.onresize = function () {
    change_size();
};
function showNightChange() {
    var myDate = new Date();
    var hour = myDate.getHours();
    if (hour >= 19 || hour < 7) {
        if (window.isNight === false) {
            window.isNight = true;
            $("body").addClass("mdui-theme-layout-dark");
            mdui.mutation();
            $("#loading_box").css("background-color", $("body").css("background-color"));
        }
        //晚上7点到早上7点夜间模式
    } else {
        if (window.isNight === true) {
            window.isNight = false;
            $("body").removeClass("mdui-theme-layout-dark");
            mdui.mutation();
            $("#loading_box").css("background-color", $("body").css("background-color"));
        }
    }
}
function change_size() {
    var bodyheight = $(window).height();
    var bodywidth = $(window).width();
    $("body").css("height", bodyheight - 2);
    $("body").css("width", bodywidth - 2);
    $("#loading").css("width", bodywidth - 2);
    var appbar_height = $("#appbar").height();
    var footbar_height = $("#footbar").height();
    var show_height = bodyheight - appbar_height - footbar_height;
    $("#mainpage").css("margin-top", 2);
    $("#mainpage").css("height", show_height - 45);
    $("#loading_box").css("height", show_height);
    $("#loading_box").css("width", bodywidth - 2);
    var loading_circle_top = (show_height + $("#footbar").height()) / 2 - $("#loading").height();
    $("#loading").css("margin-top", loading_circle_top + "px");
    if ($("#index_ad").height() > $("#index_no").height()) {
        $("#index_no").css("height", $("#index_ad").height() + "px");
    } else {
        $("#index_ad").css("height", $("#index_no").height() + "px");
    }
    clearTimeout(size_change_timeout);
    size_change_timeout = setTimeout(function () {
        webui_hook_window_size_change($("#appbar").height(), $("#appbar").width());
    }, 500);
}

function Loading_start() {
    $("#loading_box").show()
}

function Loading_stop() {
    //alert("隐藏");
    $("#loading_box").hide()
}

function showpage(name) {
    Loading_start();
    ws.send(JSON.stringify({"mod":"SetPutMainPage","status":false}));
	if(name == "main"){
        ws.send(JSON.stringify({"mod":"SetPutMainPage","status":true}));
	}
    $.ajax({
        url: "./pages/" + name + ".html",
        success: function (result) {
            $("#page_content").html(result);
        },
        error: function (res) {
            $("#page_content").html('<h2>出了点意外...</h2><br>请求页面：' + name +
                '<br>您似乎访问了不存在的页面...<br>也有可能是页面文件被强行删除了...<br>总之...这里发生了点意外导致无法显示您的页面');
        }
    });
}


function formatSeconds(duration) {
    duration = duration * 1000;
    let str = ''
    let days = '',
        hours = '',
        minutes = '',
        seconds = ''
    let day = 24 * 60 * 60 * 1000,
        hour = 60 * 60 * 1000,
        minute = 60 * 1000,
        second = 1000
    if (duration >= day) {
        days = Math.floor(duration / day) + '天'
        hours = Math.floor(duration % day / hour) + '小时'
    } else if (duration >= hour && duration < day) {
        hours = Math.floor(duration / hour) + '小时'
        minutes = Math.floor(duration % hour / minute) + '分钟'
    } else if (duration > minute && duration < hour) {
        minutes = Math.floor(duration / minute) + '分钟'
        seconds = Math.floor(duration % minute / second) + '秒'
    } else if (duration < minute) {
        seconds = Math.floor(duration / second) + '秒'
    }
    return days + hours + minutes + seconds

}

function pluginSet(type, pid, obj) {
    pid = pid.replace(/_/g, ".")
    if (type === 1) {
        //插件设置
        ws.send(JSON.stringify({
            "mod": "setPlugin",
            "pid": pid
        }));
    }
    if (type === 2) {
        ws.send(JSON.stringify({
            "mod": "reloadPlugin",
            "pid": pid
        }));
    }
    if (type === 3) {
        mdui.alert(webui_hook_getPluginDescribe(pid));
    }
    if (type === 4) {
        ws.send(JSON.stringify({
            "mod": "switchPlugin",
            "pid": pid,
            "status": +obj.checked
        }));
    }
    if (type === 5) {
        ws.send(JSON.stringify({
            "mod": "dropPlugin",
            "pid": pid,
            "status": +obj.checked
        }));
    }
}

function pluginListDo(type) {
    if (type === 1) {
        ws.send(JSON.stringify({
            "mod": "addPlugin"
        }));
    }
    if (type === 2) {
        mdui.dialog({
            title: '确认？',
            content: '确认需要启用所有插件？',
            buttons: [
                { text: '取消' },
                {
                    text: '确认',
                    onClick: function (inst) {
                        ws.send(JSON.stringify({
                            "mod": "openAllPlugin"
                        }));
                    }
                }
            ]
        });
    }
    if (type === 3) {
        mdui.dialog({
            title: '确认？',
            content: '确认需要禁用所有插件？',
            buttons: [
                { text: '取消' },
                {
                    text: '确认',
                    onClick: function (inst) {
                        ws.send(JSON.stringify({
                            "mod": "closeAllPlugin"
                        }));
                    }
                }
            ]
        });
    }
    if (type === 4) {
        mdui.dialog({
            title: '确认？',
            content: '确认需要重载所有插件？<br>注：重载部分插件极有可能导致框架崩溃',
            buttons: [
                { text: '取消' },
                {
                    text: '确认',
                    onClick: function (inst) {
                        ws.send(JSON.stringify({
                            "mod": "reloadAllPlugin"
                        }));
                    }
                }
            ]
        });
    }
}

//type 1为框架，2为其他
function SaveFormSet(type) {
    var inp = document.querySelectorAll('input');
    var back = {};
    for (var j = 0; j < inp.length; j++) {
        if (inp[j].type === "radio") {
            if (inp[j].checked === true) {
                back[inp[j].name] = $(inp[j]).val();
            }
        } else if (inp[j].type === "checkbox") {
            back[inp[j].name] = $(inp[j]).prop("checked");
        } else {
            back[inp[j].name] = $(inp[j]).val();
        }
    }
    webui_hook_SavaSetting(type, JSON.stringify(back));
    mdui.alert("保存成功！");
}

function LoadFormSet(id) {
    var back = JSON.parse(webui_hook_GetSetting(id));
    var inp = document.querySelectorAll('input');

    for (var j = 0; j < inp.length; j++) {
        if (inp[j].type === "radio") {
            if (back[inp[j].name] == inp[j].value) {
                $(inp[j]).attr("checked", true);
            }

        } else if (inp[j].type === "checkbox") {
            $(inp[j]).prop("checked", back[inp[j].name]);
        } else {
            $(inp[j]).val(back[inp[j].name]);
        }
    }
}
