var user = config.user,
    pwd = config.password;
var firmwareListXml, queryInfo = new Object(),
    timeflag = null;
$(document).ready(function() {
    sessionStorage.removeItem('character');
    var deviceInfo = config.deviceInfo;
    $('#myTab a').click(function(e) {
        e.preventDefault();
        $(this).tab('show');
        if ($(this).attr("aria-controls") == "cloud-upgrade") {
            $("#deviceType").text(deviceInfo.DeviceTypeName);
            $("#softVer").text(deviceInfo.SoftWareVersion);
        }
    });
    $("#getFilePath").change(function(e) {
        var filePath = $(this).val();
        $("#filePath").val(filePath);
    });
    //升级
    $("#upgradesave").click(function() {
        if ($("#filePath").val() != "") {
            if ("admin" == user || "super_admin" == user) {
                doUpload();
            } else {
                $.optionBootoast($.i18n.prop('i18n-propoe'), "danger");
            }
        } else {
            $.optionBootoast($.i18n.prop('i18n-upgrade-tip2'), "danger");
        }
    });
    $("#queryVersion").click(function(e) {
        GetCloudUpgradeHost();
    });
    $("#queryUpgrade").click(function(e) { //开始升级

        downloadStart();

    });

});

function GetCloudUpgradeHost() {
    $.ajax({
        url: "http://utilerp.p6sai.com:8090/UtilERP/device/h5CloudUpgradeHost", //正式
        type: "GET",
        dataType: 'jsonp',
        jsonp: "callbackName",
        jsonpCallback: "showData",
        success: function(xmlDoc, textStatus, xhr) {

        },
        error: function(xhr) {
            $.optionBootoast($.i18n.prop("i18n-p2p-msgcehad6"), "danger"); //查询失败
        }
    });
}

function showData(data) {
    if (data.code == '200') {
        queryInfo = data.data;
        queryVersion();
        queryList();
    } else {
        $.optionBootoast($.i18n.prop("i18n-query-failed"), "danger"); //查询失败
    }
}

function doUpload() {
    //检查是否支持FormData
    if (window.FormData) {
        $("#upgradesave").attr("disabled", true);
        var formData = new FormData();
        // 建立一个upload表单项，值为上传的文件
        formData.append('username', user);
        formData.append('password', pwd);
        formData.append('size', document.getElementById('getFilePath').files[0].size);
        formData.append('file', document.getElementById('getFilePath').files[0]);
        var xhr = new XMLHttpRequest();
        if (xhr.upload) {
            //上传中
            xhr.upload.onprogress = function(event) { //显示文件的上传进度
                if (event.lengthComputable) {
                    /// e.lengthComputable是一个布尔值,表示当前上传的资源是否有可计算的长度
                    // 计算出上传的进度
                    // e.loaded 已传输的字节
                    // e.total 需传输的总字节
                    $("#upprogres").show();
                    var procentComplete = Math.ceil((event.loaded / event.total) * 100);
                    $("#percent").attr("style", "width:" + procentComplete + "%").html(procentComplete + "%");
                }
            };
            // 文件上传成功或是失败
            xhr.onreadystatechange = function(e) {
                console.log(xhr, 'xhr');
                if (this.readyState == 4) {
                    if (this.status == 200) { //响应成功
                        var xmlDoc = new DOMParser().parseFromString(xhr.responseText, "text/xml");
                        var statusCode = $(xmlDoc).find('statusCode').text();
                        if (statusCode != 0) {
                            $.optionBootoast($.i18n.prop('i18n-upgrade-failed'), "danger");
                        } else {
                            $.optionBootoast($.i18n.prop('i18n-upgrade-success'), "success");
                        }
                    } else {
                        $.optionBootoast($.i18n.prop('i18n-upgrade-failed'), "danger");
                    }
                    $("#filePath").val("");
                    $("#upprogres").hide();
                }
            };
            xhr.open('POST', '/System/FirmwareUpgrade', true);
            // 定义上传完成后的回调函数
            xhr.onload = function() {

            };
            xhr.send(formData);
        }
    }
}

function queryVersion() {
    var cyURL = config.baseUrl + "/System/CloudUpgradeServerInfo";
    var cyXml = '<?xml version="1.0" encoding="utf-8"?><CloundUpgradeServer>' +
        '<Port>' + queryInfo.port + '</Port>' +
        '<HostIP>' + queryInfo.hostIp + '</HostIP>' +
        '<Username>' + config.user + '</Username>' +
        '<Password>' + config.password + '</Password>' +
        '<Protocol>' + queryInfo.protocol + '</Protocol>' +
        '<Path>' + queryInfo.path + '</Path>' +
        '</CloundUpgradeServer>';
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function() {

        }
    });
}

function queryList() {
    $.ajax({
        url: config.baseUrl + "/System/CloudUpgradeFirmwareList",
        type: "get",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc) {
            var errStatusCode = $(xmlDoc).find('ResponseStatus').eq(0).find('statusCode').text();
            if (errStatusCode) {
                cloudUpgradeErrorCode(errStatusCode);
            } else {
                firmwareListXml = xmlDoc;
                $('#ver-box').text($(xmlDoc).find('Firmware').find('Version').text());
                //解码语言.html()在ie中不支持，所以要么分开写两种，要么先转义后解析
                var encodedText = ($(xmlDoc).find('Firmware').find('Desc').text()).replace(/[<>]/g, function(m) { return { '<': '&lt;', '>': '&gt;' }[m]; });
                // 替换 &amp;lt;langCn&amp;gt; 和 &amp;lt;/langCn&amp;gt;
                var decodedText = encodedText.replace(/\&lt;\/?(langTw|langEn|langCn|langJa|langDe|langIt|langTr|langPl|langEs|langKo|langId|langVi|langFr|langPt|langCz|langGr|langPe|langHe|langAr|langTh|langRu)\&gt;/g, '');
                var desc = Base64.decode(decodedText);
                // 将换行符替换为 <br> 标签
                var htmlText = desc.replace(/\n/g, '<br>');
                $('#desc').html(htmlText);
                $('#queryVersion').hide();
                $('.isShowUpgrade').show();
            }
        }
    });
}

function downloadStart() {
    var character = randomString();
    sessionStorage.setItem('character', character);
    var FirmwareName = $(firmwareListXml).find('Firmware').find('Name').text();
    var UpgradeFileSize = $(firmwareListXml).find('Firmware').find('TotalSize').text();
    var cyURL = config.baseUrl + "/System/CloudUpgradeDownloadStart";
    var cyXml = '<?xml version="1.0" encoding="utf-8"?><Action>' +
        '<Passport>' + character + '</Passport>' +
        '<FirmwareName>' + FirmwareName + '</FirmwareName>' +
        '<AutoUpgrade>manual</AutoUpgrade>' +
        '<UpgradeFileSize>' + UpgradeFileSize + '</UpgradeFileSize>' +
        '<MD5></MD5>' +
        '</Action>';
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        data: cyXml,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr) {
            var xmlDoc = xhr.responseXML;
            var state = $(xmlDoc).find("statusCode").eq(0).text();
            if (state == 0) {
                $("#cloudUpprogres").show();
                timeflag = setInterval(downloadStatus, 500);
            } else {
                cloudUpgradeErrorCode(state);
            }
        }
    });
}

function downloadStatus() {
    $.ajax({
        url: config.baseUrl + "/System/CloudUpgradeDownloadStatus?Passport=" + sessionStorage.getItem("character"),
        type: "get",
        async: false,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc) {
            var Status = $(xmlDoc).find("Status").find("Status").text();
            var TotalSize = $(xmlDoc).find("Status").find("TotalSize").text();
            var SentSize = $(xmlDoc).find("Status").find("SentSize").text();
            // 获取进度条'
            if (Status == 1) { //0,空闲 1,正在下载 2,下载完成 3,下载失败
                var procentComplete = Math.ceil(SentSize / TotalSize * 100);

                $("#cloudPercent").attr("style", "width:" + procentComplete + "%").html(procentComplete + "%");
            }
            if (Status == 2 && TotalSize == SentSize) { //下载完成
                clearInterval(timeflag);
                timeflag = null;
                $.optionBootoast($.i18n.prop("i18n-upgrade-msg"), "success");
                $("#cloudUpprogres").hide();
                startUpgrade();

            }
            if (Status == 3) { //下载失败
                clearInterval(timeflag);
                timeflag = null;
                $.optionBootoast($.i18n.prop("i18n-download-failed"), "danger");
                $("#cloudUpprogres").hide();
            }
        },
        error: function() {
            clearInterval(timeflag);
            timeflag = null;
            $.optionBootoast($.i18n.prop("i18n-download-failed"), "danger");
            $("#cloudUpprogres").hide();
        }
    });
}

function startUpgrade() {
    var cyURL = config.baseUrl + "/System/CloudUpgradeStartUpgrade";
    var cyXml = '<?xml version="1.0" encoding="utf-8"?><Action>' +
        '<Passport>' + sessionStorage.getItem("character") + '</Passport>' +
        '</Action>';
    $.ajax({
        type: "PUT",
        url: cyURL,
        async: false,
        data: cyXml,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        complete: function(xhr) {
            var xmlDoc = xhr.responseXML;
            var state = $(xmlDoc).find("statusCode").eq(0).text();
            if (state == 0) {
                setTimeout(function() {
                    $.optionBootoast($.i18n.prop("i18n-upgrade-success"), "success"); //升级成功，请勿断电，请稍候重新登录
                }, 2000)
            } else {
                cloudUpgradeErrorCode(state);
            }
        }
    });
}
// 随机字符串方法   
function randomString() {
    var len = 32;
    var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';
    var maxPos = chars.length;
    var character = '';
    for (var i = 0; i < len; i++) {
        character += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return character;
}

function cloudUpgradeErrorCode(errCode) {
    switch (errCode) {
        case '18001':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg1"), "danger");
        case '18002':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg2"), "danger");
        case '18003':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg3"), "danger");
        case '18004':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg4"), "danger");
        case '18005':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg5"), "danger");
        case '18006':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg6"), "danger");
        case '18007':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg7"), "danger");
        case '18008':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg8"), "danger");
        case '18009':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg9"), "danger");
        case '18010':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg10"), "danger");
        case '18011':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg11"), "danger");
        case '18012':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg12"), "danger");
        case '18013':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg13"), "danger");
        case '18014':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg14"), "danger");
        case '18015':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg15"), "danger");
        case '18016':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg16"), "danger");
        case '18017':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg17"), "danger");
        case '18018':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg18"), "danger");
        case '18019':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg19"), "danger");
        case '18020':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg20"), "danger");
        case '18021':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg21"), "danger");
        case '18022':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg22"), "danger");
        case '18023':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg23"), "danger");
        case '18024':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg24"), "danger");
        case '18025':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg25"), "danger");
        case '18026':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg26"), "danger");
        case '18027':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg27"), "danger");
        case '18028':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg28"), "danger");
        case '18029':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg29"), "danger");
        case '18030':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg30"), "danger");
        case '18031':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg31"), "danger");
        case '18036':
            return $.optionBootoast($.i18n.prop("i18n-p2p-msgcehad6"), "danger");
        default:
            return $.optionBootoast($.i18n.prop("i18n-facecode4"), "danger");
    }

}