var a = 'handler/UserAdminHandler.ashx';
var i = "Modules/html/UserForm.html";
$(function() {
    var W = {
        width: $(window).width(),
        height: $(window).height()
    };
    b.init(W);
    x.init();
    autoResize({
        dataGrid: '#userlist',
        gridType: 'datagrid',
        callback: e.bindGrid,
        height: 35,
        width: 230
    });
    $('#a_add').click(P.AddUser);
    $('#a_edit').click(P.EditUser);
    $('#a_delete').click(P.DeleteUser);
    $('#a_editpassword').click(P.SetUserPassword);
    $('#a_refresh').click(function() {
        $('#userlist').datagrid('reload')
    });
    $('#a_search').click(function() {
        search.go('userlist')
    });
    $('#a_export').click(function() {
        var X = new ExportExcel('userlist');
        X.go('PIUSER', 'SORTCODE')
    });
    $(window).resize(function() {
        W = {
            width: $(window).width(),
            height: $(window).height()
        };
        b.resize(W)
    })
});
var b = {
    init: function(W) {
        $('#layout').width(W.width - 4).height(W.height - 4).layout();
        var X = $('#layout').layout('panel', 'center');
        X.panel({
            onResize: function(Y, Z) {
                $('#userlist').datagrid('resize', {
                    width: Y - 6,
                    height: Z - 36
                })
            }
        })
    },
    resize: function(W) {
        b.init(W);
        $('#layout').layout('resize')
    }
};
var x = {
    init: function() {
        $('#organizeTree').tree({
            lines: true,
            url: 'handler/OrganizeAdminHander.ashx?action=treedata',
            animate: true,
            onLoadSuccess: function(W, X) {
                $('body').data('depData', X)
            },
            onClick: function(W) {
                var X = W.id;
                $('#userlist').datagrid('load', {
                    organizeId: X
                })
            }
        })
    },
    data: function(W) {
        var X = JSON.stringify($('body').data('depData'));
        if (W === '1') {
            X = '[{"id":0,"text":"请选择组织机构"},' + X.substr(1)
        };
        return JSON.parse(X)
    }
};
var j;
var e = {
    bindGrid: function(W) {
        j = $('#userlist').datagrid({
            url: a + "?action=GetUserPageDTByDepartmentId",
            title: "系统用户列表",
            loadMsg: "正在加载用户数据，请稍等...",
            iconCls: 'icon icon-list',
            width: W.width,
            height: W.height,
            rownumbers: true,
            striped: true,
            idfield: 'ID',
            singleSelect: true,
            pagination: true,
            pageSize: 20,
            pageList: [20, 10, 30, 50],
            checkOnSelect: true,
            rowStyler: function(X, Y) {
                if (Y.ENABLED <= 0) {
                    return 'color:#999;';
                }
            },
            frozenColumns: [[{
                field: 'ck',
                checkbox: true,
                rowspan: 2
            },
            {
                title: '编号',
                field: 'CODE',
                width: 150,
                rowspan: 2
            },
            {
                title: '登录名',
                field: 'USERNAME',
                width: 150,
                sortable: true,
                rowspan: 2
            },
            {
                title: '用户名',
                field: 'REALNAME',
                width: 150,
                rowspan: 2
            }]],
            columns: [[{
                title: '有效',
                field: 'ENABLED',
                width: 30,
                rowspan: 2,
                formatter: function(X, Y, Z) {
                    if (Y.USERNAME != 'Administrator') {
                        return '<img style="cursor:pointer" title="设置用户的可用性（启用或禁用）" onclick="javascript:SetUserEnabled(' + "'" + Y.ID + "'" + ',' + X + ')" src="/css/icon/bullet_' + (X ? "tick.png": "minus.png") + '" />'
                    }
                }
            },
            {
                title: '性别',
                field: 'GENDER',
                width: 30,
                rowspan: 2,
                formatter: function(X, Y, Z) {
                    if (Y.GENDER === '男') {
                        return '<img src="/css/icon/user_b.png" alt="男" title="男" />'
                    } else if (Y.GENDER === '女') {
                        return '<img src="/css/icon/user_green.png" alt="女" title="女" />'
                    } else {
                        return '<img src="/css/icon/question_button.png" alt="性别未知" title="未设置性别" />'
                    }
                }
            },
            {
                title: '联系方式',
                colspan: 2
            },
            {
                title: '组织机构信息',
                colspan: 5
            },
            {
                title: '登录信息',
                colspan: 3
            },
            {
                title: '描述',
                field: 'DESCRIPTION',
                width: 300,
                rowspan: 2
            }], [{
                title: '邮箱地址',
                field: 'EMAIL',
                width: 150,
                rowspan: 1
            },
            {
                title: '手机号码',
                field: 'MOBILE',
                width: 100,
                rowspan: 1
            },
            {
                title: '所在单位/公司',
                field: 'COMPANYNAME',
                width: 100,
                rowspan: 1
            },
            {
                title: '所在子公司',
                field: 'SUBCOMPANYNAME',
                width: 100,
                rowspan: 1
            },
            {
                title: '所在部门',
                field: 'DEPARTMENTNAME',
                width: 100,
                rowspan: 1
            },
            {
                title: '所在子部门',
                field: 'SUBDEPARTMENTNAME',
                width: 100,
                rowspan: 1
            },
            {
                title: '所在工作组',
                field: 'WORKGROUPNAME',
                width: 100,
                rowspan: 1
            },
            {
                title: '上次登录时间',
                field: 'PREVIOUSVISIT',
                width: 150,
                sortable: true,
                rowspan: 1
            },
            {
                title: '登录次数',
                field: 'LOGONCOUNT',
                width: 60,
                sortable: true,
                rowspan: 1
            },
            {
                title: 'IP地址',
                field: 'IPADDRESS',
                width: 80,
                sortable: true,
                rowspan: 1
            }]]
        })
    },
    reload: function() {
        j.datagrid('reload')
    },
    getSelectedRow: function() {
        return j.datagrid('getSelected')
    }
};
var imgcheckbox = function(W, X, Y) {
    return W ? '<img src="/css/icon/bullet_tick.png" alt="正常" title="正常" />': '<img src="/css/icon/bullet_minus.png" alt="禁用" title="禁用" />'
};
var date2str = function(W, X, Y) {
    if (W) return $D(W).strftime("%Y-%m-%d");
    else return ''
};
var P = {
    AddUser: function() {
        if ($(this).linkbutton('options').disabled == true) {
            return false
        };
        var W = top.$.hDialog({
            href: i,
            title: '添加用户',
            width: 610,
            height: 640,
            iconCls: 'icon-user_add',
            onLoad: function() {
                s.bindCategory('txtGender', 'Gender');
                s.bindCategory('txtRoleId', 'undefined');
                s.bindCategory('txtCompanyName', 'Company');
                s.bindCategory('txtSubCompanyName', 'SubCompany');
                s.bindCategory('txtDepartmentName', 'Department');
                s.bindCategory('txtSubDepartmentName', 'SubDepartment');
                s.bindCategory('txtWorkgroupName', 'Workgroup');
                top.$('#chkEnabled').attr("checked", true);
                top.$('#txtDescription').val("");
                top.$('#txtUserName').focus()
            },
            submit: function() {
                if (top.$('#uiform').validate().form()) {
                    var X = top.$('#txtRoleId').combobox('getValue');
                    var Y = top.$('#txtCompanyName').combobox('getValue');
                    var Z = top.$('#txtSubCompanyName').combobox('getValue');
                    var a0 = top.$('#txtDepartmentName').combobox('getValue');
                    var a1 = top.$('#txtSubDepartmentName').combobox('getValue');
                    var a2 = top.$('#txtWorkgroupName').combobox('getValue');
                    var a3 = top.$('#txtCompanyName').combobox('getText');
                    var a4 = top.$('#txtSubCompanyName').combobox('getText');
                    var a5 = top.$('#txtDepartmentName').combobox('getText');
                    var a6 = top.$('#txtSubDepartmentName').combobox('getText');
                    var a7 = top.$('#txtWorkgroupName').combobox('getText');
                    var a8 = top.$('#uiform').serialize() + '&action=add';
                    a8 = a8 + '&vRoleId=' + X + '&vCompanyId=' + Y + '&vSubCompanyId=' + Z + '&vDepartmentId=' + a0 + '&vSubDepartmentId=' + a1 + '&vWorkgroupId=' + a2;
                    a8 = a8 + '&vCompanyName=' + a3 + '&vSubCompanyName=' + a4 + '&vDepartmentName=' + a5 + '&vSubDepartmentName=' + a6 + '&vWorkgroupName=' + a7;
                    $.ajaxjson('handler/UserAdminHandler.ashx', a8, 
                    function(a9) {
                        if (a9.Success) {
                            msg.ok(a9.Message);
                            W.dialog('close');
                            e.reload()
                        } else {
                            MessageOrRedirect(a9)
                        }
                    })
                } else {
                    msg.warning('请输入用户名称。');
                    top.$('#txtUserName').focus()
                }
            }
        });
        return false
    },
    EditUser: function() {
        if ($(this).linkbutton('options').disabled == true) {
            return false
        };
        var W = e.getSelectedRow();
        if (W != null) {
            if (W.USERNAME != '' && W.USERNAME == 'Administrator' && curUserinfo.username != 'Administrator') {
                $.messager.alert('警告提示', '你不能修改超级管理员用户！', 'warning');
                return false
            };
            var X = top.$.hDialog({
                href: i,
                width: 610,
                height: 640,
                title: '修改用户',
                iconCls: 'icon-user_edit',
                onLoad: function() {
                    s.bindCategory('txtGender', 'Gender');
                    s.bindCategory('txtRoleId', 'undefined');
                    s.bindCategory('txtCompanyName', 'Company');
                    s.bindCategory('txtSubCompanyName', 'SubCompany');
                    s.bindCategory('txtDepartmentName', 'Department');
                    s.bindCategory('txtSubDepartmentName', 'SubDepartment');
                    s.bindCategory('txtWorkgroupName', 'Workgroup');
                    var Y = 'action=GetEntity&KeyId=' + W.ID;
                    $.ajaxjson('handler/UserAdminHandler.ashx', Y, 
                    function(Z) {
                        if (Z) {
                            top.$('#txtUserName').val(Z.UserName);
                            top.$('#txtRealName').val(Z.RealName);
                            top.$('#txtCode').val(Z.Code);
                            top.$('#txtUserPassword').after('******').remove();
                            top.$('#txtGender').combobox('setValue', Z.Gender);
                            top.$('#txtMobile').val(Z.Mobile);
                            top.$('#txtBirthday').val(Z.Birthday);
                            top.$('#txtTelephone').val(Z.Telephone);
                            top.$('#txtDuty').val(Z.Duty);
                            top.$('#txtQICQ').val(Z.Qicq);
                            top.$('#txtTitle').val(Z.Title);
                            top.$('#txtEmail').val(Z.Email);
                            top.$('#txtRoleId').combobox('setValue', Z.RoleId);
                            top.$('#txtCompanyName').combobox('setValue', Z.CompanyId);
                            top.$('#txtSubCompanyName').combobox('setValue', Z.SubCompanyId);
                            top.$('#txtDepartmentName').combobox('setValue', Z.DepartmentId);
                            top.$('#txtSubDepartmentName').combobox('setValue', Z.SubDepartmentId);
                            top.$('#txtWorkgroupName').combobox('setValue', Z.WorkgroupId);
                            top.$('#txtHomeAddress').val(Z.Homeaddress);
                            top.$('#txtDescription').val(Z.Description);
                            top.$('#chkEnabled').attr("checked", Z.Enabled == "1")
                        }
                    })
                },
                submit: function() {
                    if (top.$('#uiform').validate().form()) {
                        var Y = top.$('#txtRoleId').combobox('getValue');
                        var Z = top.$('#txtCompanyName').combobox('getValue');
                        var a0 = top.$('#txtSubCompanyName').combobox('getValue');
                        var a1 = top.$('#txtDepartmentName').combobox('getValue');
                        var a2 = top.$('#txtSubDepartmentName').combobox('getValue');
                        var a3 = top.$('#txtWorkgroupName').combobox('getValue');
                        var a4 = top.$('#txtCompanyName').combobox('getText');
                        var a5 = top.$('#txtSubCompanyName').combobox('getText');
                        var a6 = top.$('#txtDepartmentName').combobox('getText');
                        var a7 = top.$('#txtSubDepartmentName').combobox('getText');
                        var a8 = top.$('#txtWorkgroupName').combobox('getText');
                        var a9 = top.$('#uiform').serialize() + '&action=edit&id=' + W.ID;
                        a9 = a9 + '&vRoleId=' + Y + '&vCompanyId=' + Z + '&vSubCompanyId=' + a0 + '&vDepartmentId=' + a1 + '&vSubDepartmentId=' + a2 + '&vWorkgroupId=' + a3;
                        a9 = a9 + '&vCompanyName=' + a4 + '&vSubCompanyName=' + a5 + '&vDepartmentName=' + a6 + '&vSubDepartmentName=' + a7 + '&vWorkgroupName=' + a8;
                        $.ajaxjson('handler/UserAdminHandler.ashx', a9, 
                        function(b0) {
                            if (b0.Success) {
                                msg.ok(b0.Message);
                                X.dialog('close');
                                e.reload()
                            } else {
                                MessageOrRedirect(b0)
                            }
                        })
                    }
                }
            })
        } else {
            msg.warning('请选择待修改的用户。');
            return false
        };
        return false
    },
    DeleteUser: function() {
        if ($(this).linkbutton('options').disabled == true) {
            return false
        };
        var W = e.getSelectedRow();
        if (W) {
            if (W.USERNAME != '' && W.USERNAME == 'Administrator') {
                msg.warning('不能删除超级管理员！');
                return false
            };
            if (W.ID != '' && W.ID == curUserinfo.id) {
                msg.warning('不能删除当前登录用户！');
                return false
            };
            $.messager.confirm('询问提示', '确认要删除用户【' + W.REALNAME + '】吗？', 
            function(X) {
                if (X) {
                    $.ajaxjson(a, 'action=delete&id=' + W.ID, 
                    function(Y) {
                        if (Y.Data > 0) {
                            msg.ok('所选用户删除成功！');
                            e.reload()
                        } else {
                            MessageOrRedirect(Y)
                        }
                    })
                }
            })
        } else {
            msg.warning('请选择要删除的用户。');
            return false
        };
        return false
    },
    SetUserPassword: function() {
        if ($(this).linkbutton('options').disabled == true) {
            return false
        };
        var W = e.getSelectedRow();
        if (W != null) {
            var X = top.$.hDialog({
                content: Q,
                width: 300,
                height: 160,
                title: '设置用户密码',
                iconCls: 'icon-key',
                submit: function() {
                    if (top.$('#txtNewPassword').validatebox('isValid')) {
                        $.ajaxjson(a, "action=setpassword&id=" + W.ID + '&password=' + top.$('#txtNewPassword').val(), 
                        function(Y) {
                            if (Y.Data > 0) {
                                msg.ok('密码修改成功，请牢记新密码！');
                                e.reload();
                                X.dialog('close')
                            } else {
                                MessageOrRedirect(Y)
                            }
                        })
                    } else {
                        msg.warning('新密码不能为空～！');
                        top.$('#txtNewPassword').focus()
                    }
                }
            });
            top.$('#loginname').text(W.USERNAME + ' | ' + W.REALNAME);
            top.$('#txtNewPassword').validatebox();
            top.$('#txtNewPassword').focus()
        } else {
            msg.warning('请选择要修改密码的用户。');
            return false
        };
        return false
    }
};
var s = {
    bindCategory: function(W, X) {
        if (W === '' || X === '') {
            return false
        };
        if (W === 'txtGender') {
            top.$('#' + W).combobox({
                url: 'Modules/handler/DataItemAdminHandler.ashx?action=GetCategory&categorycode=' + X,
                method: 'get',
                valueField: 'ITEMVALUE',
                textField: 'ITEMNAME',
                editable: false,
                panelHeight: 'auto'
            })
        };
        if (W === 'txtRoleId') {
            top.$('#' + W).combobox({
                url: 'Modules/handler/RoleAdminHandler.ashx?action=GetEnabledRoleList',
                method: 'get',
                valueField: 'ID',
                textField: 'REALNAME',
                editable: false,
                panelHeight: 'auto'
            })
        };
        if (W === 'txtCompanyName' || W === 'txtSubCompanyName' || W === 'txtDepartmentName' || W === 'txtSubDepartmentName' || W === 'txtWorkgroupName') {
            top.$('#' + W).combobox({
                url: 'Modules/handler/OrganizeAdminHander.ashx?action=GetOrganizeByCategory&OrganizeCategory=' + X,
                method: 'get',
                valueField: 'ID',
                textField: 'FULLNAME',
                editable: false,
                panelHeight: 'auto'
            })
        };
        return false
    }
};
function SetUserEnabled(W, X) {
    var Y = 'action=SetUserEnabled&KeyId=' + W + '&isenabled=' + X;
    $.ajaxjson(a, Y, 
    function(Z) {
        if (Z.Success) {
            e.reload()
        } else {
            MessageOrRedirect(Z)
        }
    })
};
var Q = '<table class="grid" id="epform">';
Q += '<tr><td>登录名：</td><td><span id="loginname"></span></td></tr>';
Q += '<tr><td>新密码：</td><td><input  validType="safepass"  required="true" id="txtNewPassword" name="password" type="password" class="txt03" /></td></tr>';
Q += '</table>';