var user = config.user,
    pwd = config.password;
var userinfos = "Basic " + $.cookie("userInfo");
var firmwareListXml,
    queryInfo = new Object(),
    timeflag = null,
    Upgrade = false;
var upgradeStatus = null,
    timeoutai = null,
    ajaxRequest = null,
    afType = null,
    countdownTimer = null;
$(document).ready(function() {
    getPTZPower();
    sessionStorage.removeItem("character");
    var deviceInfo = config.deviceInfo;
    if (config.deviceCap[0].cloudUpgrade == "false") {
        $("#myTab").find("li").eq(1).remove();
        $(".tab-content").find('div[role="tabpanel"]').eq(1).remove();
    }
    $("#myTab a").click(function(e) {
        e.preventDefault();
        $(this).tab("show");
        $("#filePath").val('');
        if ($(this).attr("aria-controls") == "local-upgrade") {
            afType = null;
            $("#upgradeTabel").text($.i18n.prop("i18n-local-upgrade"));
            $(".tab-pane").removeClass("active");
            $("#local-upgrade").addClass("active");
        } else if ($(this).attr("aria-controls") == "ai-upgrade") {
            afType = 30;
            $("#upgradeTabel").text($.i18n.prop("i18n-cloud-AI"));
            $(".tab-pane").removeClass("active");
            $("#local-upgrade").addClass("active");
        } else {
            var upgradeInfo = getCloudUpgradeInfo();
            afType = null;
            $("#deviceType").val(deviceInfo.DeviceTypeName);
            $("#softVer").val(deviceInfo.SoftWareVersion);
            $("#customerNumber").val(upgradeInfo.CustomerID);
            $("#customerVersion").val(upgradeInfo.CustomerVersionID);
            // 定义中英文语言映射
            var languageMap = {
                'SimpChinese': $.i18n.prop("i18n-language_zh"),
                'English': $.i18n.prop("i18n-language_en"),
                'Korean': $.i18n.prop("i18n-language_ko"),
                'Japanese': $.i18n.prop("i18n-language_ja"),
                'Italian': $.i18n.prop("i18n-language_it"),
                'Russian': $.i18n.prop("i18n-language_ru"),
                'Spanish': $.i18n.prop("i18n-language_es"),
                'Portuguese': $.i18n.prop("i18n-language_po"),
                'Persian': $.i18n.prop("i18n-language_fa"),
                'Arabic': $.i18n.prop("i18n-language_ar"),
                'Bulgarian':$.i18n.prop("i18n-language_lang1"),
                'TranChinese': $.i18n.prop("i18n-language_tw"),
                'Custom': $.i18n.prop("i18n-language_lang2"),
                'Croation': $.i18n.prop("i18n-language_lang3"),
                'Czech': $.i18n.prop("i18n-language_lang4"),
                'Danish': $.i18n.prop("i18n-language_lang5"),
                'Dutch': $.i18n.prop("i18n-language_lang6"),
                'German':$.i18n.prop("i18n-language_lang7"),
                'Estonian': $.i18n.prop("i18n-language_lang8"),
                'Finnish': $.i18n.prop("i18n-language_lang9"),
                'French': $.i18n.prop("i18n-language_lang10"),
                'Greek': $.i18n.prop("i18n-language_lang11"),
                'Hebrew': $.i18n.prop("i18n-language_lang12"),
                'Hungarian':$.i18n.prop("i18n-language_lang13"),
                'Latvian': $.i18n.prop("i18n-language_lang14"),
                'Lithuanian': $.i18n.prop("i18n-language_lang15"),
                'Norwegian':$.i18n.prop("i18n-language_lang16"),
                'Polish': $.i18n.prop("i18n-language_lang17"),
                'Romanian':$.i18n.prop("i18n-language_lang18"),
                'Slovak': $.i18n.prop("i18n-language_lang19"),
                'Slovenian': $.i18n.prop("i18n-language_lang20"),
                'Swedish': $.i18n.prop("i18n-language_lang21"),
                'Thai': $.i18n.prop("i18n-language_lang22"),
                'Turkish':$.i18n.prop("i18n-language_lang23"),
                'Vietnamese': $.i18n.prop("i18n-language_vn"),
                'Indonesian':$.i18n.prop("i18n-language_lang24"),
                'KoreanLanguage': $.i18n.prop("i18n-language_lang25"),
            };
            // CGI接口返回的语言字段
            var backendField = upgradeInfo.Language;
            // 获取对应的语言中文名
            var chineseName = languageMap[backendField] || $.i18n.prop("i18n-language_lang26");
            $("#cloudLanguage").val(chineseName);
        }
    });
    $("#getFilePath").change(function(e) {
        var filePath = $(this).val();
        $("#filePath").val(filePath);
    });
    //升级
    $("#upgradesave").click(function() {
        if ($("#filePath").val() != "") {
            if ("admin" == user || "super_admin" == user) {
                if (afType == 30) {
                    $("#aiupdatetime").css("color", "#3A77FE");
                    $("#aiversion").text($.i18n.prop("i18n-acquiring")).css("color", "#3A77FE");
                    $("#upgrading").text($.i18n.prop("i18n-upgrading")).css("color", "#3A77FE");
                }
                doUpload();
            } else {
                $.optionBootoast($.i18n.prop("i18n-propoe"), "danger");
            }
        } else {
            $.optionBootoast($.i18n.prop("i18n-upgrade-tip2"), "danger");
        }
    });
    $("#queryVersion").click(function(e) {
        e.preventDefault ? e.preventDefault() : e.returnValue = false;
        GetCloudUpgradeHost();
    });
    $("#queryUpgrade").click(function(e) {
        //开始升级
        downloadStart();
    });
    $("#close").click(function(e) {
        $("#upgradesave").attr("disabled", false);
        clearInterval(countdownTimer);
        countdownTimer = null;
        if (ajaxRequest) {
            ajaxRequest.abort();
            ajaxRequest = null;
            upgradeStatus = null;
            timeoutai = null;
        }
    });
});

// 云升级（客户编号、客户版本、语言）获取
function getCloudUpgradeInfo() {
    var upgradeInfo = {};
    $.ajax({
        type: "get",
        url: config.baseUrl + '/CloudUpdate/1/BasicInfo',
        dataType: 'XML',
        timeout: 15000,
        async: false,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc) {
            upgradeInfo.CustomerID = $(xmlDoc).find('DeviceUpdateBasicInfo').eq(0).find('CustomerID').eq(0).text();
            upgradeInfo.CustomerVersionID = $(xmlDoc).find('DeviceUpdateBasicInfo').eq(0).find('CustomerVersionID').eq(0).text();
            upgradeInfo.Language = $(xmlDoc).find('DeviceUpdateBasicInfo').eq(0).find('Language').eq(0).text();
        },
        error: function(data) {}
    });
    return upgradeInfo
}

// 获取ptz能力配置
function getPTZPower() {
    var cvurl = config.baseUrl + "/System/PTZCap";
    $.ajax({
        url: cvurl,
        type: "GET",
        async: true,
        timeout: 15000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc, textStatus, xhr) {
            var Version = $(xmlDoc).find("Channel").eq(0).find('AFProfessionPTZ').eq(0).find("Version").eq(0).text();
            Upgrade = $(xmlDoc).find("Channel").eq(0).find("Upgrade").eq(0).text();
            if (Version == "false" || Version == "") {
                // $("#myTab").find("li").eq(2).remove();
                // $(".tab-content").find('div[role="tabpanel"]').eq(2).remove();
                $("#aiUpgrade").hide();
            }
        },
        error: function(xhr, textStatus, errorThrown) {},
    });
}

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() {
    if (window.FormData) {
        $("#upgradesave").attr("disabled", true);
        var formData = new FormData();
        formData.append("username", user);
        formData.append("password", pwd);
        if (afType == 30) {
            formData.append("filetype", 30);
        }
        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) {
                    $("#upprogres").show();
                    var procentComplete = Math.ceil((event.loaded / event.total) * 100);
                    $("#percent")
                        .attr("style", "width:" + procentComplete + "%")
                        .html(procentComplete + "%");
                }
            };
            // 文件上传成功或是失败
            xhr.onreadystatechange = function(e) {
                if (this.readyState == 4) {
                    if (this.status == 200) {
                        if (afType == 30) {
                            var xmlDoc = new DOMParser().parseFromString(xhr.responseText, "text/xml");
                            var statusCode = $(xmlDoc).find("statusCode").text();
                            if (statusCode == 0) {
                                $("#myModal").modal("show");
                                $("#aiupdatetime").text("240s");
                                var totalSeconds = 240;
                                countdownTimer = setInterval(function() {
                                    totalSeconds--;
                                    $("#aiupdatetime").text(totalSeconds + "s");
                                    getUpgradeStatus();
                                    // $("#upgrading").text(upgradeStatus);
                                    if (totalSeconds < 0 || timeoutai == "timeout") {
                                        clearInterval(countdownTimer);
                                        countdownTimer = null;
                                        $("#aiupdatetime").text($.i18n.prop("i18n-upgrade-timeout")).css("color", "red");
                                        $("#aiversion").text($.i18n.prop("i18n-unknown")).css("color", "black");
                                        $("#upgrading").text($.i18n.prop("i18n-upgrade-failed")).css("color", "red");
                                    }
                                }, 1000);
                            } else {
                                $.optionBootoast($.i18n.prop("i18n-upgrade-failed"), "danger");
                            }
                        } else {
                            var xmlDoc = new DOMParser().parseFromString(xhr.responseText, "text/xml");
                            var statusCode = $(xmlDoc).find("statusCode").text();
                            if(statusCode=='0'){
                                $.optionBootoast($.i18n.prop("i18n-upgrade-success"), "success");
                            }else{
                                cloudUpgradeErrorCode(statusCode);
                            }
                           
                        }
                    } else {
                        $.optionBootoast($.i18n.prop("i18n-upgrade-failed"), "danger");
                    }
                    // $("#filePath").val("");
                    $("#upprogres").hide();
                }
                $("#upgradesave").attr("disabled", false);
            };
            xhr.open("POST", "/System/FirmwareUpgrade", true);
            // 定义上传完成后的回调函数
            xhr.onload = function() {};
            xhr.send(formData);
        }
    }
}

function getUpgradeStatus() {
    ajaxRequest = $.ajax({
        url: config.baseUrl + "/System/AFBoardUpgradeStatus",
        type: "get",
        async: false,
        timeout: 180000,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("If-Modified-Since", "0");
        },
        success: function(xmlDoc) {
            var status = $(xmlDoc).find("AFBoardUpgradeStatus").eq(0).find("Status").eq(0).text();
            if (status == "success") {
                //升级成功”，停止超时计时，从设备获取AF机芯版本号显示出来；
                clearInterval(countdownTimer);
                countdownTimer = null;
                if (Upgrade == "true") {
                    var deviceInfo = getDeviceInfo();
                    $("#aiupdatetime").text($.i18n.prop("i18n-pause")).css("color", "black");
                    $("#aiversion").text(deviceInfo.AFBoardVersion).css("color", "black");
                    $("#upgrading").text($.i18n.prop("i18n-upgradsuc")).css("color", "black");
                } else {
                    $("#aiupdatetime").css("color", "black");
                    $("#aiversion").text($.i18n.prop("i18n-cannot-version")).css("color", "black");
                    $("#upgrading").text($.i18n.prop("i18n-upgradsuc")).css("color", "black");
                }
            } else if (status == "timeout" || status == "fail") { //“升级失败”、“升级超时”，停止超时计时；
                clearInterval(countdownTimer);
                countdownTimer = null;
                $("#aiupdatetime").text($.i18n.prop("i18n-upgrade-timeout")).css("color", "black");
                $("#aiversion").text($.i18n.prop("i18n-unknown")).css("color", "black");
                $("#upgrading").text($.i18n.prop("i18n-upgradfail")).css("color", "red");
            } else if (status == "idle") {
                clearInterval(countdownTimer);
                countdownTimer = null;
                $("#aiupdatetime").text($.i18n.prop("i18n-pause")).css("color", "black");
                $("#aiversion").text($.i18n.prop("i18n-unknown")).css("color", "black");
                $("#upgrading").text($.i18n.prop("i18n-equipment-idle")).css("color", "red");
            } else { //升级中

            }
        },
        error: function(xhr, status, error) {
            if (status == "timeout") {
                timeoutai = "timeout";
            }
        },
    });
}

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 '-1858535417':
            return $.optionBootoast($.i18n.prop("i18n-cloud-msg32"), "danger");
        default:
            return $.optionBootoast($.i18n.prop("i18n-facecode4"), "danger");
        
    }

}