/**
 * Created by R06326 on 2017/8/24.
 */
define(function(require, exports, module) {
    require('countdown');

    var Promise = window.require('bluebird');
    var co = window.require('co');
    var fs = window.require('fs');
    var xlsx = window.require("node-xlsx");

    var global = require("../../js/global");
    var jGlobal = require("./oneUpgradeGlobal");
    var path = window.require("path");
    var jsUtil = window.require('../../common/js/jsUtil');

    var apBatchUpgrade = window.require('../../common/js/apBatchUpgrade');

    var INTERVAL = 20000; // AP升级时尝试重连的时间间隔
    var RECONNECTTIMES = 50; // AP升级时尝试重连的最多次数

    var upgradingFlag = true; // 正在升级中的标志

    function showUpgradeResultTable() {
        // 胖AP列表
        $('#table_upgradeResult').bootstrapTable({
            data: []
        });
        $(".fixed-table-body").addClass('custom-scroll');

        var infos = jGlobal.oneUpgrade.discoverResult;
        var upgradeResultList = [],
            tmpSuccess = [],
            tmpFailed = [],
            tmpNoNeed = [],
            tmpWait = [];
        for (var i = 0; i < infos.length; i++) {
            var upgradeResult = {};
            upgradeResult.deviceName = infos[i].deviceInfo.hostname;
            upgradeResult.ipAddress = infos[i].host;
            upgradeResult.deviceSn = infos[i].deviceInfo.seriaNo;
            upgradeResult.deviceModel = infos[i].deviceInfo.deviceModel;
            upgradeResult.hardVersion = infos[i].deviceInfo.hardVer;
            upgradeResult.softVersion = infos[i].deviceInfo.softVer;
            upgradeResult.status = infos[i].updateInfo.status;
            if (upgradeResult.status == 'success') {
                upgradeResult.upgradeResult = '升级成功';
                tmpSuccess.push(upgradeResult);
            } else if (upgradeResult.status == 'failed') {
                upgradeResult.upgradeResult = '升级失败。原因：' + infos[i].updateInfo.msg;
                tmpFailed.push(upgradeResult);
            } else if (upgradeResult.status == 'noNeed') {
                upgradeResult.upgradeResult = '无需升级';
                tmpNoNeed.push(upgradeResult);
            } else if (upgradeResult.status == 'wait') {
                upgradeResult.upgradeResult = '连接不上设备，无法判断升级状态。';
                tmpWait.push(upgradeResult);
            }
        }
        upgradeResultList = tmpFailed.concat(tmpWait, tmpSuccess, tmpNoNeed);

        // 加载表格
        var client_h = document.documentElement.clientHeight;
        var head_h = $(".main_menu").height();
        var body_h = client_h - head_h;
        $('#table_upgradeResult').bootstrapTable('load', upgradeResultList);
        $('#table_upgradeResult').bootstrapTable('resetView', {height : body_h - 60});
    }

    function upgradeResultStyle(value, row) {
        if (row.status == "success" || row.status == "noNeed") {
            return '<text>' + value + '</text>';
        } else {
            return '<text style="color: #FA4664;">' + value + '</text>';
        }
    }

    function init() {
        initWindowEvent();
        initVariable();
        initEvent();
        initDom();
        initGlobalEvent();

        function initWindowEvent() {
            window.upgradeResultStyle = upgradeResultStyle;
        }
        function initVariable() {
            upgradingFlag = true;
        }
        function initEvent() {
            co(function* () {
                var infos = jGlobal.oneUpgrade.discoverResult;
                var totalApCnt = 0;
                for (var i = 0; i < infos.length; i++) {
                    if (infos[i].updateInfo.status == "wait") {
                        totalApCnt++;
                    }
                }
                $("#totalApCnt").text(totalApCnt);

                $("#upgradeApText").text('正在下发升级包…已下发到0台设备');
                yield apBatchUpgrade.upgrade(infos, 'cloud-11x-ap-bin', function (count) {
                    console.log('下发升级命令!当前已经下发', count, ' 台设备');
                    $("#upgradeApText").text('正在下发升级包…已下发到' + count + '台设备');
                });



                // 传到云端
                yield apBatchUpgrade.uploadDatas(infos);

                // sleep 70秒，防止设备upgrade后，还没开始重启，交换设备可能需要很长时间
                yield Promise.delay(70000);

                console.time('check');
                $("#upgradeApText").text('正在升级中…已升级0台设备');
                var checkedCount = 0;

                for (var i = 0; i < RECONNECTTIMES; i++) {
                    checkedCount += yield apBatchUpgrade.check(infos, 10, function (count, checkCnt) {
                        console.log('检测设备是否升级成功,目前检测了', count, '台,已确认了:', checkCnt, ' 台');
                    });

                    console.log('第[', i, ']次检验,确认了', checkedCount, '台设备');
                    $("#upgradeApText").text('正在升级中…已升级' + checkedCount + '台设备');

                    var hasWait = false;
                    infos.forEach(function (item) {
                        console.log(item.updateInfo);
                        if (item.updateInfo.status == 'wait') {
                            hasWait = true;
                        }
                    });
                    if (!hasWait) {
                        break;
                    }
                    yield Promise.delay(INTERVAL);
                }
                console.timeEnd('check');

                $("#upgradeProgressDiv").hide();
                $("#upgradeResultDiv").show();

                upgradingFlag = false;
                showUpgradeResultTable();
            });
            
            $("#exportFatAp").click(function () {
                var tbHeaders = ["设备名称", "设备ip", "设备序列号", "设备型号", "硬件版本", "当前软件版本", "升级结果"];
                var folder = path.join(jsUtil.getDataPath(), 'apUpgradeLog');
                var prefix = 'apUpgradeResult_';
                var contents = [];
                var upgradeResult = $("#table_upgradeResult").bootstrapTable('getData');
                for (var i = 0; i < upgradeResult.length; i++) {
                    contents.push([upgradeResult[i].deviceName, upgradeResult[i].ipAddress, upgradeResult[i].deviceSn, upgradeResult[i].deviceModel,
                        upgradeResult[i].hardVersion, upgradeResult[i].softVersion, upgradeResult[i].upgradeResult]);
                }
                jsUtil.toExcel(tbHeaders, contents, folder, prefix);
                jsUtil.openDir(folder);
            });

            $('#exportMaccDevices').click(function () {
                var tbHeaders = ['SN', '设备名称'];
                var folder = path.join(jsUtil.getDataPath(), 'apUpgradeLog');
                var prefix = 'maccResult_';
                var upgradeResult = $("#table_upgradeResult").bootstrapTable('getData');
                for (var i = 0; i < upgradeResult.length; i++) {
                    contents.push(upgradeResult[i].deviceSn, '');
                }
                jsUtil.toExcel(tbHeaders, contents, folder, prefix);
                jsUtil.openDir(folder);

            });

            $("#exportFailFatAp").click(function () {
                var tbHeaders = ["设备名称", "设备ip", "设备序列号", "设备型号", "硬件版本", "当前软件版本", "升级结果"];
                var folder = path.join(jsUtil.getDataPath(), 'apUpgradeLog');
                var prefix = 'apUpgradeFailResult_';
                var contents = [];
                var upgradeResult = $("#table_upgradeResult").bootstrapTable('getData');
                for (var i = 0; i < upgradeResult.length; i++) {
                    if (upgradeResult[i].status == "success" || upgradeResult[i].status == "noNeed") {
                        continue;
                    }

                    contents.push([upgradeResult[i].deviceName, upgradeResult[i].ipAddress, upgradeResult[i].deviceSn, upgradeResult[i].deviceModel,
                        upgradeResult[i].hardVersion, upgradeResult[i].softVersion, upgradeResult[i].upgradeResult]);
                }
                jsUtil.toExcel(tbHeaders, contents, folder, prefix);
                jsUtil.openDir(folder);
            });

            // 返回
            $(".back").click(function() {
                var curElement = ".main_content", nextPageUrl = "./oneUpgrade/html/oneUpgradeMenu.html";
                global.enterPageCallback(curElement, nextPageUrl);
            });
        }
        function initDom() {

        }
        function initGlobalEvent() {
            global.exitPageCallback.exitFun = function () {
                if (upgradingFlag) {
                    alert(undefined, "正在升级中，请稍候…");
                    return false;
                }
                return true;
            }
        }
    }
    exports.init = init;
});