/**
 * Created by R06326 on 2017/8/21.
 */
define(function(require, exports, module) {
    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 jsUtil = window.require('../../common/js/jsUtil');

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

    var LIMIT = 40; // 一次性发现多少个ip

    function validate() {
        // for (var i = 0; i < 4; i++) {
        //     var startIp = $("#startAddress .address-input:eq(" + i + ")").val();
        //     if (!startIp || isNaN(startIp) || startIp < 0 || startIp > 255) {
        //         alert(undefined, "请输入正确的ip地址！");
        //         return false;
        //     }
        // }
        //
        // var startLastIp = $("#startAddress .address-input:eq(3)").val();
        // var endLastIp = $("#endAddress .address-input:eq(3)").val();
        // if (!endLastIp || isNaN(endLastIp) || endLastIp < 0 || endLastIp > 255) {
        //     alert(undefined, "请输入正确的ip地址！");
        //     return false;
        // }
        // if (endLastIp - startLastIp < 0) {
        //     alert(undefined, "结束地址应大于起始地址！");
        //     return false;
        // }

        var startIp = $("#startAddress").val();
        var endIp = $("#endAddress").val();
        if(!window.isIpOk(startIp) || !window.isIpOk(endIp)) {
            alert(undefined, "您输入ip地址格式不正确。");
            return false;
        }

        var startIpArray = startIp.split('.');
        var endIpArray = endIp.split('.');
        for (var i = 0; i < 3; i++) {
            if (startIpArray[i] != endIpArray[i]) {
                alert(undefined, "只能检测同一网段内的ip地址！");
                return false;
            }
        }

        var startLastIp = startIpArray[3];
        var endLastIp = endIpArray[3];
        if (endLastIp - startLastIp < 0) {
            alert(undefined, "结束地址应大于起始地址！");
            return false;
        }

        // 端口号检测
        var port = $("#port").val();
        if (isNaN(port) || port < 1 || port > 65535) {
            alert(undefined, "端口号必须是1到65535之间的整数！");
            return false;
        }

        return true;
    }

    function discoverFatAp(connectInfos,deviceTypeList) {
        co(function* () {
            // 进度条显示
            $("#progress_discover").text('0%');
            $("#progressBar_discover").css('width', '0%');
            $("#dlg_discoverProgress").modal('show');

            console.time('搜索IP耗时:');
            var result = yield discovery.find11XDevices(connectInfos, deviceTypeList, ['fat','macc'], LIMIT, function (n1, n2) {
                console.log('当前已检测:', n1, ' 个IP地址', ' 已发现:', n2, ' 台设备');

                /* 更新连接设备进度条 */
                var percent = Math.floor((n1 / connectInfos.length) * 100);
                $("#progress_discover").text(percent + '%');
                $("#progressBar_discover").css('width', percent + '%');
            });
            console.log('搜索到的AP', result);
            console.timeEnd('搜索IP耗时:');

            var info = yield binMgr.getRecommandVersion(result);
            console.log('需要下载的文件有: ', info);
            console.log('搜索结果: ', result);

            jGlobal.oneUpgrade.discoverResult = result;
            jGlobal.oneUpgrade.recommndResult = info;

            $("#dlg_discoverProgress").modal('hide');
            setTimeout(function() {
                var curElement = ".main_content", nextPageUrl = "./oneUpgrade/html/fatApDownloadVersion.html";
                global.enterPageCallback(curElement, nextPageUrl);
            }, 300);
        });
    }

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

        function initWindowEvent() {

        }
        function initVariable() {

        }
        function initEvent() {
            // // 输入胖AP的地址范围
            // $("#startAddress .address-input").each(function (index, value) {
            //     if (index < 3) {
            //         $(this).keyup(function () {
            //             $("#endAddress .address-input:eq(" + index + ")").val($(this).val());
            //         });
            //     }
            // });
            
            // 发现胖AP
            $("#discover").click(function () {
                if (!validate()) {
                    return;
                }

                // var startIp0 = $("#startAddress .address-input:eq(0)").val();
                // var startIp1 = $("#startAddress .address-input:eq(1)").val();
                // var startIp2 = $("#startAddress .address-input:eq(2)").val();
                // var startIp3 = $("#startAddress .address-input:eq(3)").val();
                // var endIp3 = $("#endAddress .address-input:eq(3)").val();

                var startIpArray = $("#startAddress").val().split('.');
                var endIpArray = $("#endAddress").val().split('.');
                var connectInfos = [];
                for (var i = startIpArray[3]; i <= endIpArray[3]; i++) {
                    connectInfos.push(
                        {
                            protocal : 'telnet',
                            host : startIpArray[0] + '.' + startIpArray[1] + '.' + startIpArray[2] + '.' + i,
                            port : $("#port").val(),
                            username : $("#userName").val(),
                            password : $("#password").val(),
                            enablePassword : $("#enablePassword").val(),
                            encoding : 'GB2312',
                        }
                    );
                }
                
                var selectType = $('.selectType[name="selectType"]:checked').val();
                var deviceTypeList = [selectType];
                console.log('selectType:', selectType);
                discoverFatAp(connectInfos, deviceTypeList);
            });

            // 通过excel导入胖AP
            $("#batchImportModalBtn").click(function() {
                var selectConfFile = $('#selectConfFile');
                selectConfFile.unbind('change');
                selectConfFile.change(function(evt) {
                    var filePath = $(this).val();
                    console.log('华住批量导入设备excel路径： ', filePath);
                    try {
                        var obj = xlsx.parse(filePath);
                    } catch (e) {
                        console.error(e);
                        alert(undefined, e.toString());
                        return;
                    }

                    var excelObj = obj[0].data;
                    var excelObjFilter = [];
                    // console.log('excel内容: ', excelObj);

                    // 校验excel的合法性
                    if (excelObj[0][0] != 'IP地址') {
                        alert(undefined, '不是合法的excel，请下载模板填写。');
                        return;
                    }

                    excelObj.shift();
                    for (var k = 0; k < excelObj.length; k++) {
                        if (excelObj[k].length > 0) {
                            excelObjFilter.push(excelObj[k]);
                        }
                    }

                    // 批量导入胖AP
                    console.log("批量导入的设备: ", excelObjFilter);
                    var connectInfos = [];
                    for (var i = 0; i < excelObjFilter.length; i++) {
                        const item = excelObjFilter[i];
                        if (Array.isArray(item) && item.length >= 3) {
                            connectInfos.push(
                                {
                                    protocal: excelObjFilter[i][1],
                                    host: excelObjFilter[i][0],
                                    port: excelObjFilter[i][2],
                                    username: item.length >=4 ? item[3] : '',
                                    password: item.length >= 5 ? item[4] : '',
                                    enablePassword: item.length >= 6 ? item[5] : '',
                                    encoding: 'GB2312',
                                }
                            );
                        }

                    }
                    console.log('excel将要导入的设备:', connectInfos);
                    discoverFatAp(connectInfos,['AP','SWITCH']);

                    $(this).val("");
                });
                selectConfFile.trigger('click');
            });
        }
        function initDom() {
            $('#dlg_discoverProgress').modal({
                backdrop: 'static',
                show: false,
                keyboard: false
            });

            // 添加下载模板路径
            var path = global.jsUtil.getRootPath() + '/db/import_tpl.xlsx';
            $("#downloadConfBtn").attr('href', path);
        }
        function initGlobalEvent() {
            global.exitPageCallback.exitFun = function () {
                return true;
            }
        }
    }
    exports.init = init;
});