var gs_xml_doc, user = config.user,
    pwd = config.password;
var qrcode_height = 150;
var qrcode_width = 150;
var time = null,
    overtime = 0;
var gs_str_app_download = new Array(2);
var gs_os_platform = [""];
var p2p_status = [{
    state: 'offline',
    result: $.i18n.prop('i18n-p2p-offline')
}, {
    state: 'internet-ready',
    result: $.i18n.prop('i18n-p2p-internet-ready')
}, {
    state: 'intranet-ready',
    result: $.i18n.prop('i18n-p2p-intranet-ready')
}, {
    state: 'Network-Unreachable',
    result: $.i18n.prop('i18n-p2p-network-unreachable')
}, {
    state: 'Invalid-UUID',
    result: $.i18n.prop('i18n-p2p-invalid-uid')
}, {
    state: 'NotFoundServer',
    result: $.i18n.prop('i18n-p2p-found-error')
}];
$(document).ready(function() {
    getP2PInfo();
    $('#p2pEnable').change(function() {
        if ($(this).is(":checked")) {
            $(".p2pId").show();
        } else {
            $(".p2pId").hide();
            $("#p2p-code").hide();
        }
        showQrcode();
    });
    $("#p2pSave").click(function() {
        if ("admin" == user || "super_admin" == user) {
            setP2PInfo();
        } else {
            $.optionBootoast($.i18n.prop('i18n-propoe'), "danger")
        }
    });
    $("#getdid").click(function() { //获取did
        setApplyDI();
    });
});

function setApplyDI() {
    var cyXml = "<ApplyDIDManulCfg><RequestUrl></RequestUrl></ApplyDIDManulCfg>";
    var cyURL = config.baseUrl + "/System/ApplyDIDManul";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: true,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xhr, textStatus) {
            $.MaskUtil.mask($.i18n.prop("i18n-p2p-mask-msg"));
            time = setInterval(function() {
                overtime++;
                if (overtime > 10) {
                    $.MaskUtil.unmask();
                    clearInterval(time);
                    time = null;
                    overtime = 0;
                    $.optionBootoast($.i18n.prop('i18n-p2p-did-error'), "danger")
                };
                searchDid();
            }, 1000);
        },
        error: function(xhr, textStatus, errorThrown) {}


    });
}

function searchDid() {
    $.ajax({
        url: config.baseUrl + "/Network/P2PV2",
        type: "get",
        async: true,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            var DidGetStatus = $(xmlDoc).find('P2PList').eq(0).find('P2P').eq(0).find('DidGetStatus').text();
            if (DidGetStatus == "OK") {
                $.MaskUtil.unmask();
                clearInterval(time);
                time = null;
                overtime = 0;
                var p2puid = $(xmlDoc).find('P2PList').eq(0).find('P2P').eq(0).find('UUID').text();
                $("#p2pUUID").val(p2puid.split(",")[0]);
                showUlkAppQrcode();
                showP2PQrcode();
                $(".tablep2pQrcode").show();
                $("#getdid").hide();
            } else if (DidGetStatus == "Fail") {
                var errCode = $(xmlDoc).find('P2PList').eq(0).find('P2P').eq(0).find('ErrCode').text();
                if (errCode == "201") {
                    errorPrompt($.i18n.prop('i18n-p2p-msgcehad'));
                }
                if (errCode == "1009") {
                    errorPrompt($.i18n.prop('i18n-p2p-msgcehad1'));
                }
                if (errCode == "1089") {
                    errorPrompt($.i18n.prop('i18n-p2p-msgcehad2'));
                }
                if (errCode == "1117") {
                    errorPrompt($.i18n.prop('i18n-p2p-msgcehad3'));
                }
                if (errCode == "1077") {
                    errorPrompt($.i18n.prop('i18n-p2p-msgcehad4'));
                }
                if (errCode == "1114") {
                    errorPrompt($.i18n.prop('i18n-p2p-msgcehad5'));
                }
            } else if (DidGetStatus == "NetWorkErr") {
                errorPrompt($.i18n.prop('i18n-p2p-msgcehad6'));
            } else if (DidGetStatus == "Refuse") {
                errorPrompt($.i18n.prop('i18n-p2p-msgcehad7'));
            }
        },
        error: function(xhr, textStatus, errorThrown) {

        }
    });
}

function errorPrompt(msg) {
    $.MaskUtil.unmask();
    clearInterval(time);
    time = null;
    overtime = 0;
    $(".tablep2pQrcode").hide();
    $.optionBootoast(msg, "danger");
}

function getP2PInfo() {
    $.ajax({
        url: config.baseUrl + "/Network/P2PV2",
        type: "get",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            gs_xml_doc = xmlDoc;
            var nFindFlag = 0;
            var p2pList = $(xmlDoc).find('P2PList').eq(0).find('P2P').length;
            for (var index = 0; index < p2pList; index++) {
                var p2pProtocolName = $(xmlDoc).find('P2PList').eq(0).find('P2P').eq(index).find('P2PProtocolName').text();
                var enable = $(xmlDoc).find('P2PList').eq(0).find('P2P').eq(index).find('Enable').text();
                if (p2pProtocolName == "tutk" && enable == "true") { //表示找到了一个使能的开关
                    $('#p2pEnable').prop('checked', true)
                    nFindFlag = 1;
                    break;
                }
            }
            if (nFindFlag == 0) { //没有找到，那么就设置为Disable
                $('#p2pEnable').prop('checked', false)
            }
            if ($('#p2pEnable').is(":checked")) {
                $(".p2pId").show();
            } else {
                $(".p2pId").hide();
                $("#p2p-code").hide();
            }
            var p2puid = $(xmlDoc).find('P2P').eq(0).find('UUID').eq(0).text();
            $('#p2pUUID').val(p2puid.split(",")[0]);
            if ($("#p2pUUID").val() != "") {
                $("#getdid").hide();
            } else {
                $("#getdid").show();

            }
            var p2pStatus = $(xmlDoc).find('P2P').eq(0).find('Status').eq(0).text();
            for (var i = 0; i < p2p_status.length; i++) {
                if (p2pStatus == p2p_status[i].state) {
                    $('#p2pStatus').val(p2p_status[i].result);
                }
            }
            gs_str_app_download[0] = $(xmlDoc).find('P2P').eq(0).find('AndroidAppDownload').eq(0).text();
            showQrcode();
        },
        error: function(xhr, textStatus, errorThrown) {}
    });
}

function showQrcode() {
    if ($("#p2pEnable").is(':checked') && $("#p2pUUID").val() !== "") { //显示二维码
        showP2PQrcode();
        showTutkAppQrcode();
        $(".tablep2pQrcode").show();
    } else {
        $(".tablep2pQrcode").hide();
    }
}

function showP2PQrcode() {
    $("#p2pQrcode").empty();
    new QRCode("p2pQrcode", {
        text: $("#p2pUUID").val(),
        width: qrcode_width,
        height: qrcode_height,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });
}

function showUlkAppQrcode() {
    $("#APPQrcode").empty();
    new QRCode("APPQrcode", {
        text: gs_str_app_download[0],
        width: qrcode_width,
        height: qrcode_height,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
    });
}

function setP2PInfo() {
    for (var i = 0; i < 2; i++) {
        $(gs_xml_doc).find('P2PList').eq(0).find('P2P').eq(i).find('Enable').eq(0).text('false');
    }
    $(gs_xml_doc).find('P2PList').eq(0).find('P2P').eq(0).find('Enable').eq(0).text($("#p2pEnable").is(":checked"));
    var cyXml = gs_xml_doc;
    var cyURL = config.baseUrl + "/Network/P2PV2";
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: true,
        processData: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr, textStatus) {
            SaveState(xhr)
        }
    });
}

function showTutkAppQrcode() {
    for (var i = 0; i < gs_os_platform.length; i++) {
        $("#" + gs_os_platform[i] + "APPQrcode").empty();

        new QRCode(gs_os_platform[i] + "APPQrcode", {
            text: gs_str_app_download[i],
            width: qrcode_width,
            height: qrcode_height,
            colorDark: "#000000",
            colorLight: "#ffffff",
            correctLevel: QRCode.CorrectLevel.H
        });
    }
}

function getModeVal() {
    return $("#p2pEnable").is(":checked") ? 1 : 0;
}
