define(function(require, exports, module) {
    'use strict';

    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 hzLauncher = window.require('../../common/js/hzLauncher');
    var path = window.require("path");
    var jsUtil = window.require('../../common/js/jsUtil');

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

        function initWindowEvent() {

        }

        function initPageStatistic() {
            window.statRecordEle("batchStart#batchStart");
        }

        function initVariable() {

        }

        function initEvent() {
            var failImportList = []; // 批量开局失败的设备列表
            var successNum = 0;

            // 配置（模拟macc登陆过程）
            var user = global.userMgrIns.getUserInfo();
            var maccHost = global.jsUtil.getPkgInfo().spec.info.maccHost;
            console.log('用户信息： ', user);
            hzLauncher.setConfig(maccHost, user.userName, user.password);

            $("#batchImport").click(function () {
                // 检测dns ip地址是否合法
                if ($("#isConfDns").is(':checked')) {
                    var dnsIp = $("#dnsText").val();
                    if (!window.isIpOk(dnsIp)) {
                        alert(undefined, "您输入dns ip地址格式不正确！");
                        return;
                    }
                }

                $("#importDeviceModal").modal('show');
            })

            $("#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的合法性
                    // console.error(excelObj[0]);
                    if (excelObj[0][1] != 'IP地址') {
                        alert(undefined, '不是合法的excel，请下载模板填写。');
                        return;
                    }

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

                    // 批量导入设备
                    batchImport(excelObjFilter);

                    $(this).val("");
                });
                selectConfFile.trigger('click');
            });

            $("#retry").click(function() {
                batchImport(failImportList);
            });

            $("#openFailLog").click(function() {
                global.jsUtil.openDir(jsUtil.getDataPath());
            });

            $("#isConfDns").click(function () {
                $("#dnsText").toggle();
            });
            
            function batchImport(excelObjFilter) {
                // 初始化数据
                $("#failContent").text("");
                $("#retry").hide();
                failImportList = [];
                successNum = 0;

                // 进度条初始化
                $("#progress_import").text('0%');
                $("#progressBar_import").css('width', '0%');
                $("#dlg_importProgress").modal('show');

                co(function* () {
                    for (var i = 0; i < excelObjFilter.length; i++) {
                        var deviceObj = {};

                        deviceObj.protocal = excelObjFilter[i][3] ? excelObjFilter[i][3] : 'SSH';
                        deviceObj.host = excelObjFilter[i][1];
                        deviceObj.port = excelObjFilter[i][9] ? excelObjFilter[i][9] : (deviceObj.protocal == 'telnet' ? 22 : 23);
                        deviceObj.username = excelObjFilter[i][6] ? excelObjFilter[i][6] : '';
                        deviceObj.password = excelObjFilter[i][7] ? excelObjFilter[i][7] : '';
                        deviceObj.enablePassword = excelObjFilter[i][8] ? excelObjFilter[i][8] : '';
                        deviceObj.encoding = 'GB2312';
                        if ($("#isConfDns").is(':checked')) {
                            deviceObj.nameServer = $("#dnsText").val();
                        } else {
                            deviceObj.nameServer = '';
                        }

                        if (!deviceObj.host) {
                            continue;
                        }

                        // 调用后台开局接口
                        console.log('第' + i + '行设备信息： ', deviceObj);

                        try {
                            var res = yield hzLauncher.launch(deviceObj, maccHost, {});
                            successNum++;
                            console.log('设备 ' + deviceObj.host + ' 开局成功');
                        } catch (e) {
                            var failExcelObjFilter = excelObjFilter[i];
                            var errMsg = '未知原因';
                            if (typeof e == 'string') {
                                errMsg = e;
                            } else if (typeof e == "object") {
                                errMsg = e.message ? e.message : "未知原因";
                            }
                            failExcelObjFilter[10] = errMsg;
                            failImportList.push(failExcelObjFilter);
                            console.error('设备 ' + deviceObj.host + ' 开局失败： ', e);
                        }

                        // 更新连接设备进度条
                        var percent = Math.floor(((i + 1) / (excelObjFilter.length)) * 100);
                        $("#progress_import").text(percent + '%');
                        $("#progressBar_import").css('width', percent + '%');

                        // 全部导入完成
                        if (i == (excelObjFilter.length - 1)) {
                            // 更新进度条
                            $("#progress_import").text('100%');
                            $("#progressBar_import").css('width', '100%');
                            $("#dlg_importProgress").modal('hide');

                            // 显示导入结果
                            var str = '共导入' + (excelObjFilter.length) + '台设备，成功：' + successNum + '台，失败' + (excelObjFilter.length - successNum) + '台\n\n';
                            if (failImportList.length > 0) {
                                $("#retry").show();

                                str += '失败的设备为：\n';
                                for (var i = 0; i < failImportList.length; i++) {
                                    str += failImportList[i][1] + " ( 失败原因: " + failImportList[i][10] + ' )\n';
                                }

                                try {
                                    // 将失败原因写入excel
                                    var errXlsxData = [];
                                    errXlsxData[0] = ["设备名称", "IP地址", "失败原因"];
                                    for (var i = 0; i < failImportList.length; i++) {
                                        errXlsxData[errXlsxData.length] = [failImportList[i][0], failImportList[i][1], failImportList[i][10]];
                                    }
                                    var buffer = xlsx.build([{data: errXlsxData}]);
                                    var timestamp = global.moment().format('YYYYMMDDHHmmss');
                                    var errXlsxPath = path.join(jsUtil.getDataPath(), timestamp + '.xlsx');
                                    fs.writeFileSync(errXlsxPath, buffer);

                                    // 打开失败原因
                                    setTimeout(function () {
                                        alert(undefined, "是否打开excel查看失败原因？", function () {
                                            global.jsUtil.openDir(errXlsxPath);
                                        }, true);
                                    }, 300);
                                } catch (e) {
                                    console.error(e);
                                    alert(undefined, e.toString());
                                    return;
                                }
                            }
                            $("#failContent").text(str);
                        }
                    }
                });
            }
        }

        function initDom() {
            $('#loadingConfModal').modal({
                backdrop: 'static',
                show: false
            });

            //添加下载模板路径
            var path = global.jsUtil.getRootPath() + '/db/device_import.xlsx';
            $("#downloadConfBtn").attr('href', path);
        }

        function resize() {

        }

        function initGlobalEvent() {
            global.exitPageCallback.exitFun = function() {
                return true;
            }
        }
    }
    exports.init = init;
});