define(function (require, exports, module) {
    var global = require("../../js/global");
    var cjImport = window.require('../../common/js/cjImport');

    function clearContent() {
        $("#srcContent").val('');
        $("#dstContent").val('');
    }

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

        function initPageStatistic() {
            statRecordEle("cj#cj");
        }
        function initVariable() {

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

            $("#isEditTelnet").change(function () {
                $(this).next().toggle();
            });

            $("#import").click(function () {
                var apartmentName = $.trim($("#apartmentName").val());
                if (apartmentName == "") {
                    alert(undefined, "请输入公寓名称！");
                    return;
                }
                var roomNum = $("#srcContent").val();
                if (roomNum == "") {
                    alert(undefined, "请输入房间号！");
                    return;
                }

                var gatewayHost = $('#gateway').val();
                if (gatewayHost == '') {
                    alert(undefined, "请输入AP连接的网关IP，注意到现场后，这个网关IP可能需要再次下发,此时重新再运行一遍工具就好");
                    return;
                }

                var disableEWeb = ($('#disableEWeb').is(':checked') == true);
                console.log('disableEWeb:', disableEWeb);

                if ($("#isEditTelnet").is(':checked')) {
                    var telnetUser = $.trim($('#telnetUser').val());
                    var telnetPwd = $.trim($('#telnetPwd').val());
                    if ((telnetUser != '' && telnetPwd == '') || (telnetUser == '' && telnetPwd != '')) {
                        alert(undefined, 'telnet用户名和密码不能同时为空！');
                        return;
                    }
                    if (telnetPwd != '' && (/^[0-9a-zA-Z]*$/g).test(telnetPwd) == false) {
                        alert(undefined, 'telnet密码只能输入字母或数字！！');
                        return;
                    }
                }

                $("#dstContent").empty();

                // 开始导入
                var params = {};
                params.pGroupId = global.userMgrIns.getUserInfo().groupId;
                params.locationName = apartmentName;
                params.groupType = "LOCATION";
                params.netType = "BUILDING";
                params.gatewayHost = gatewayHost;
                params.info = {};
                params.ssidList = roomNum.split(/\r?\n/).filter(function (value, index) {
                    if ($.trim(value) != '') {
                        return $.trim(value);
                    }
                });
                params.groupNameList = params.ssidList.map(function (value, index) {
                    return apartmentName + $.trim(value);
                });

                params.disableEWeb = disableEWeb;
                if (telnetUser && telnetPwd) {
                    params.telnetUser = telnetUser;
                    params.telnetPassword = telnetPwd;
                }

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

                // 进度处理函数
                var _processFunc = function (count) {
                    /* 更新连接设备进度条 */
                    var execNum = count.successNum + count.failNum;
                    var percent = Math.floor((execNum / count.totalNum) * 100);
                    $("#progress_import").text(percent + '%');
                    $("#progressBar_import").css('width', percent + '%');
                }

                cjImport.import(params, _processFunc, function (err, res) {
                    if (err != null) {
                        $("#dlg_importProgress").modal('hide');
                        alert(undefined, err.toString());
                    }

                    // 显示导入结果
                    var str = '共创建' + res.count.totalNum + '个网点（房间号），成功：' + res.count.successNum + '个，失败' + (res.count.totalNum - res.count.successNum) + '个\n\n';
                    if (res.failArray && res.failArray.length > 0) {
                        str += '失败的网点（房间号）为：\n';
                        for (var i = 0; i < res.failArray.length; i++) {
                            str += res.failArray[i] + '\n';
                        }
                    }
                    if (res.failChannelArray && res.failChannelArray.length > 0) {
                        str += '创建成功，但自动岔开信道失败的网点（房间号）为：\n';
                        for (var i = 0; i < res.failChannelArray.length; i++) {
                            str += res.failChannelArray[i] + '\n';
                        }
                    }
                    $("#dstContent").text(str);

                    // 更新进度条
                    $("#progress_import").text('100%');
                    $("#progressBar_import").css('width', '100%');
                    $("#dlg_importProgress").modal('hide');
                });
            });

            $("#clear").click(function () {
                clearContent();
            });
        }
        function initDom() {
            $("#srcContent").attr("placeholder", "输入多个房间号名称，每行一个（可从excel表中复制黏贴进来）\n如：\n\n1101\n1102\n1103");
            $('#dlg_importProgress').modal({
                backdrop: 'static',
                show: false,
                keyboard: false
            });
            // 是否显示修改telnet
            if ($("#isEditTelnet").is(':checked')) {
                $("#isEditTelnet").next().show();
            } else {
                $("#isEditTelnet").next().hide();
            }
        }
        function resize() {

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

    exports.init = init;
});