/**
 * Created with JetBrains WebStorm.
 * User: Cmma
 * Date: 7/22/14
 * Time: 3:53 PM
 * To change this template use File | Settings | File Templates.
 */
define(function (require, exports) {

    var userSvc = require('../../../../../../../share/assert/js/usersvc').userSvc;
    var userLogin = require('./userlogin').userLogin;

    function UserLoginDlg() {

        this.showDialog = function (callback) {
            createDlg().done(function (dlg) {
                userLogin.init();

                dlg.find(".submit_btn").bind('click', function () {
                    var userName = userLogin.getUserName();
                    var password = userLogin.getPassword();
                    if (userName == "") {
                        userLogin.setErrorMsg("请输入用户名");
                        return;
                    }
                    if (password == "") {
                        userLogin.setErrorMsg("请输入密码");
                        return;
                    }
                    userSvc.login(userName, password, function (errCode) {
                        if (errCode == 1) {
                            dlg.modal('hide');
                            setTimeout(function () {
                                dlg.remove();
                                $("body").find(".modal-backdrop.fade.in").remove();
                            }, 500);
                            userLogin.setUserInfo();
                            callback();
                        }
                        else if (errCode == 0) {
                            userLogin.setErrorMsg("用户名或密码错误");
                        } else if (errCode == 401) {
                            userLogin.setErrorMsg("请联网后重试");
                        }
                        else {
                            userLogin.setErrorMsg("服务器错误");
                        }
                    });
                });

                dlg.find(".w_func_close").bind('click', function () {
                    dlg.modal('hide');
                    setTimeout(function () {
                        dlg.remove();
                        $("body").find(".modal-backdrop.fade.in").remove();
                    }, 500);
                });
                dlg.modal({show: true, keyboard: false, backdrop: "static"});
            });
        }
    }

    function createDlg() {
        if ($('#modal-content'))    $('#modal-content').remove();
        var def = jQuery.Deferred();
        seajs.use('editor/assert/js/plugins/table/dialogs/userlogin/userlogin.tpl', function (tpl) {
                var dlg = $(tpl);
                $('body').append(dlg);
                var clientHeight = document.body.clientHeight;
                dlg.find(".modal-content").css("margin-top", (clientHeight - 280) / 2);
                def.resolve(dlg);
            }
        );
        return def.promise();
    }

    exports.userLoginDlg = UserLoginDlg;

})