/**
 * Created by R06326 on 2017/8/23.
 */
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 binMgr = window.require('../../common/js/binMgr');

    function gotoUpgradeFatAp() {
        var curElement = ".main_content", nextPageUrl = "./oneUpgrade/html/fatApUpgrade.html";
        global.enterPageCallback(curElement, nextPageUrl);
    }
    
    function init() {
        initWindowEvent();
        initVariable();
        initTable();
        initEvent();
        initDom();
        resize();
        initGlobalEvent();

        function initWindowEvent() {

        }
        function initVariable() {

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

            var recommndResult = jGlobal.oneUpgrade.recommndResult.connectInfos;
            var needCnt = 0;    // 需要升级的AP的数量
            var fatApList = [];
            for (var i = 0; i < recommndResult.length; i++) {
                var fatAp = {};
                fatAp.ipAddress = recommndResult[i].host;
                fatAp.deviceSn = recommndResult[i].deviceInfo.seriaNo;
                fatAp.deviceModel = recommndResult[i].deviceInfo.deviceModel;
                fatAp.hardVersion = recommndResult[i].deviceInfo.hardVer;
                fatAp.softVersion = recommndResult[i].deviceInfo.softVer;
                if (recommndResult[i].updateInfo.status == "wait") {
                    needCnt++;
                    fatAp.recommendVersion = recommndResult[i].updateInfo.recommandSoftVer;
                } else {
                    fatAp.recommendVersion = '无需升级';
                }
                fatApList.push(fatAp);
            }

            $("#totalCnt").text(recommndResult.length);
            $("#needCnt").text(needCnt);
            $('#table_fatAp').bootstrapTable('load', fatApList);
        }
        function initEvent() {
            $("#startFatApUpgrade").click(function () {
                if (parseInt($("#needCnt").text()) == 0) {
                    alert(undefined, '当前没有需要升级的设备！');
                    return;
                }

                co(function* () {
                    var versionMap = jGlobal.oneUpgrade.recommndResult.versionMap;

                    $("#totalText").text(versionMap.size);
                    $("#downloadBinModal").modal('show');

                    yield binMgr.downloadBins(versionMap, path.join(jsUtil.getDataPath(), '/upgradeInfo/cloud-11x-ap-bin'), function (successNum) {
                        console.log('当前成功下载:', successNum, '个bin');
                        $("#successText").text(successNum);
                    });

                    $("#downloadBinModal").modal('hide');
                    setTimeout(function () {
                        $("#selectBeforeUpgradeModal .modal-body").text("全部推荐版本均已下载完成。请选择升级的方式：");
                        $("#selectBeforeUpgradeModal").modal('show');
                    }, 300);
                })
                    .catch(function (e) {
                        console.error(e);
                        $("#downloadBinModal").modal('hide');
                        alert(undefined, '下载推荐版本失败,请稍后重试');
                    });
            });

            // 立即升级
            $("#selectBeforeUpgradeModal .immediateUpgrade").click(function () {
                setTimeout(function () {
                    gotoUpgradeFatAp();
                }, 300);
            });

            // 定时升级对话框
            $('#scheduleModal').on('show.bs.modal', function() {
                $("#hour").val("");
                $("#minite").val("");
                $("#scheduleModal #cancel").hide();
                $("#scheduleModal .close").show();
                $("#scheduleModal #confirm").show();
            });

            $("#scheduleModal #confirm").click(function() {
                //输入合法性检查
                var hour = $("#hour").val();
                var minite = $("#minite").val();

                if (hour == "" && minite == "") {
                    alert(undefined, '请输入重启时间！');
                    return;
                }
                if (hour != "") {
                    var ex = /^\d+$/;
                    if (!ex.test(hour)) {
                        alert(undefined, '请输入整数！');
                        return;
                    }
                }
                if (minite != "") {
                    var ex = /^\d+$/;
                    if (!ex.test(minite)) {
                        alert(undefined, '请输入整数！');
                        return;
                    }
                }
                if (hour < 0 || minite < 0 || minite > 59) {
                    alert(undefined, '输入不合法！请重新输入。');
                    return;
                }
                if (hour >= 24) {
                    alert(undefined, '定时不能超过24小时！');
                    return;
                }

                // 布局样式
                $("#scheduleModal .close").hide();
                $("#scheduleModal #confirm").hide();
                $("#scheduleModal #cancel").show();

                // 倒计时
                if (hour == "") hour = 0;
                if (minite == "") minite = 0;

                var now = new Date();
                var countTo = (hour * 60 * 60 * 1000) + (minite * 60 * 1000) + now.valueOf();

                $('.timer').countdown(countTo, function(event) {
                    var $this = $(this);
                    switch(event.type) {
                        case "seconds":
                        case "minutes":
                        case "hours":
                        case "daysLeft":
                            $this.find('span.' + event.type).html(event.value);
                            break;
                        case "finished":
                            $('#scheduleModal').modal('hide');
                            setTimeout(function () {
                                gotoUpgradeFatAp();
                            }, 300);
                            break;
                    }
                });
            });

            $("#scheduleModal #cancel").click(function() {
                // 布局样式
                $("#scheduleModal #cancel").hide();
                $("#scheduleModal .close").show();
                $("#scheduleModal #confirm").show();

                // 没有提供取消接口，人为将定时器置为0
                $('.timer').countdown(0, function(event) {
                    var $this = $(this);
                    switch(event.type) {
                        case "seconds":
                        case "minutes":
                        case "hours":
                        case "daysLeft":
                            $this.find('span.' + event.type).html(event.value);
                            break;
                        case "finished":
                            break;
                    }
                });
            });

            $("#exportFatAp").click(function () {
                var tbHeaders = ["设备ip", "设备序列号", "设备型号", "硬件版本", "软件版本", "推荐版本"];
                var folder = path.join(jsUtil.getDataPath(), 'apUpgradeLog');
                var prefix = 'devicelist_';
                var contents = [];
                var fatApList = $("#table_fatAp").bootstrapTable('getData');
                for (var i = 0; i < fatApList.length; i++) {
                    contents.push([fatApList[i].ipAddress, fatApList[i].deviceSn, fatApList[i].deviceModel,
                        fatApList[i].hardVersion, fatApList[i].softVersion, fatApList[i].recommendVersion]);
                }
                jsUtil.toExcel(tbHeaders, contents, folder, prefix);
                jsUtil.openDir(folder);
            });

            $('#exportMaccDevices').click(function () {
                var tbHeaders = ['SN', '设备名称'];
                var folder = path.join(jsUtil.getDataPath(), 'apUpgradeLog');
                var prefix = 'macc_';
                var contents = [];
                var fatApList = $("#table_fatAp").bootstrapTable('getData');
                for (var i = 0; i < fatApList.length; i++) {
                    contents.push([fatApList[i].deviceSn,'']);
                }
                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() {
            $('#downloadBinModal').modal({
                backdrop: 'static',
                show: false,
                keyboard: false
            });

            $("#selectBeforeUpgradeModal").modal({
                backdrop: 'static',
                show: false,
                keyboard: false
            });

            $("#scheduleModal").modal({
                backdrop: 'static',
                show: false,
                keyboard: false
            });
        }
        function resize() {
            var client_h = document.documentElement.clientHeight;
            var head_h = $(".main_menu").height();
            var body_h = client_h - head_h;

            $('#table_fatAp').bootstrapTable('resetView', {height : body_h - 120});
        }
        function initGlobalEvent() {
            global.exitPageCallback.exitFun = function () {
                return true;
            }
        }
    }
    exports.init = init;
});