var el = {
    userName: '#username',
    accountName: '#accountname',
    role: '#role',
    purchaseGroupId: '#purchase_group_id',
    tb: '#tb',
    searchForm: '#searchForm',
    bodyHeight: document.documentElement.clientHeight
};

$(function () {
    loadGrid();
});


/**
 * 加载页面表格
 */
function loadGrid() {
    var searchHeight = $(el.searchForm).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);

    $(el.tb).datagrid({
        height: el.bodyHeight - searchHeight,
        url: g.ctx + 'pc/sys/user/list?userType=1',
        method: "GET",
        singleSelect: true,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList,
        rownumbers: true,

        columns: [[{
            field: 'ck', checkbox: true
        }, {
            field: 'username', title: XTJCGL.GYSYHGL_YHMC, width: 240
        }, {
            field: 'accountName', title: XTJCGL.GYSYHGL_YHZH, width: 100
        }, {
            field: 'deleteStatus', title: XTJCGL.GYSYHGL_ZHZT, width: 80, formatter: function (data) {
                if (data === '0') return XTJCGL.GYSYHGL_ZC; else return '<span style="color: red;">' + XTJCGL.GYSYHGL_JY + '</span>';
            }
        }, {
            field: 'phone', title: XTJCGL.GYSYHGL_DH, width: 110
        }, {
            field: 'email', title: 'EMAIL', width: 160
        },
            {
                field: 'dispatchRoles', title: '角色', width: 160
            }]],
        toolbar: [{
            text: XTJCGL.GYSYHGL_XZ, iconCls: 'icon-add', id: 'btn_add', handler: function () {
                addAccount()
            }
        }, '-', {
            text: XTJCGL.GYSYHGL_BJ, id: 'btn_edit', iconCls: 'icon-edit', handler: function () {
                editAccount();
            }
        }, '-', {
            id: 'btn_user_add', text: XTJCGL.GYSYHGL_FPJS, iconCls: 'icon-user-add', handler: function () {
                dispatchRole(0);
            }
        }, '-', {
            id: 'btn_lock', text: XTJCGL.GYSYHGL_JY, iconCls: 'icon-lock', handler: function () {
                delAccount(1);
            }
        }, '-', {
            id: 'btn_ok', text: XTJCGL.GYSYHGL_QY, iconCls: 'icon-ok', handler: function () {
                delAccount(2);
            }
        }, '-', {
            id: 'btn_reload', text: XTJCGL.GYSYHGL_CZMC, iconCls: 'icon-reload', handler: function () {
                RePassword();
            }
        }, '-', {
            id: 'btn_print', text: XTJCGL.GYSYHGL_DCSJ, iconCls: 'icon-print', handler: function () {
                topWin.location.href = g.ctx + 'pc/sys/user/export?userType=1&' + searchQueryParams()
            }
        }, '-', {
            id: 'btn_user_setup', text: XTJCGL.GYSYHGL_WMMDL, iconCls: 'icon-user-setup', handler: function () {
                noPwdLogin();
            }
        }, '-', {
            id: 'btn_user_stop', text: XTJCGL.GYSYHGL_ZHJS, iconCls: 'icon-user-stop', handler: function () {
                unlock();
            }
        }, '-', {
            id: 'btn_cshzzh', text: '初始化子账号', iconCls: 'icon-user-setup', handler: function () {
                createSupplierChild();
            }
        }],
        onLoadSuccess: function () {
            displayButtonByUserRole("supplier_user_manage");
            $(el.tb).datagrid('clearSelections');
        }
    });
}

/**
 * 初始化供应商子账号，仅初始化数据的时候使用
 */
function createSupplierChild() {
    var loadIdx = topWin.layer.load(1);
    $.ajax({
        url: g.ctx + 'pc/sys/user/initSupplierChildUser', type: 'POST', complete: function () {
            topWin.layer.close(loadIdx);
        }, success: function (d) {
            topWin.layer.alert(ALLCOMMON.CZCG, {icon: 1});
            $(el.tb).datagrid('load');
        }, error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    })
}

/**
 * 账号解锁
 */
function unlock() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert(XTJCGL.GYSYHGL_QXZYTJL, {icon: 0});
        return;
    }
    var accountName = row.accountName;
    $.ajax({
        url: g.ctx + 'pc/sys/user/unLock', type: 'POST', data: {username: accountName}, success: function (d) {
            topWin.layer.alert(ALLCOMMON.CZCG, {icon: 1});
            $(el.tb).datagrid('load');
        }, error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }
    })
}


/**
 * 无密码登录
 */
function noPwdLogin() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert(XTJCGL.GYSYHGL_QXZYTJL, {icon: 0});
        return;
    }
    var accountName = row.id;
    $.ajax({
        url: g.ctx + 'pc/sys/noPasswordLogin', type: 'POST', data: {userId: row.id}, success: function (data) {
            var btn = {};
            $.each(data, function (idx, itm) {
                btn[itm.resKey] = itm.btns
            });
            localStorage.setItem("btn", JSON.stringify(btn));
            topWin.window.location.href = g.ctx + 'home'
        }, error: function (data) {
            topWin.layer.alert(data.responseJSON.message, {icon: 2});
        }

    })
}

/**
 * 编辑
 */
function editAccount() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert(XTJCGL.GYSYHGL_QXZYTJL, {icon: 0});
        return;
    }

    var userEditDialog = openDialog('userEditDialog', g.ctx + 'pc/sys/user/edit?userType=1&id=' + row.id, {
        title: "编辑用户",
        width: '800px',
        height: '450px',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            userEditDialog.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.save, handler: function () {
                topWin.frames['userEditDialog'].saveUser(function () {
                    userEditDialog.dialog('close');
                    $(el.tb).datagrid('reload');
                });
            }
        }, {
            text: itablei8n.close, handler: function () {
                userEditDialog.dialog('close');
            }
        }]
    });


}


/**
 * 角色分配
 */
function dispatchRole() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert(XTJCGL.GYSYHGL_QXZYTJL, {icon: 0});
        return;
    }
    var userAddRoleDialog = openDialog('userAddRoleDialog', g.ctx + 'pc/sys/role/userRoleAdd?userId=' + row.id, {
        title: XTJCGL.GYSYHGL_FPJS,
        width: '420px',
        height: '400px',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            userAddRoleDialog.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.save, handler: function () {
                topWin.frames['userAddRoleDialog'].save(function () {
                    userAddRoleDialog.dialog('close');
                    $(el.tb).datagrid('reload');
                });
            }
        }, {
            text: itablei8n.close, handler: function () {
                userAddRoleDialog.dialog('close');
            }
        }]
    })
}

/**
 * 重置密码
 */
function RePassword() {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert(XTJCGL.GYSYHGL_QXZYTJL, {icon: 0});
        return;
    }

    topWin.layer.confirm(XTJCGL.GYSYHGL_QDYCZMM, function (index) {
        $.ajax({
            url: g.ctx + 'pc/sys/user/restPassword', method: 'post', data: {userId: row.id}, success: function () {
                topWin.layer.close(index);
                topWin.layer.msg(XTJCGL.GYSYHGL_BCCG, {icon: 1});
                $(el.tb).datagrid("load");
            }, error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    });
}


/**
 * 添加用户
 */
function addAccount() {
    var title = XTJCGL.GYSYHGL_XZ;
    if (gl_language === 'en') {
        title = "New User";
    }
    var userAddDialog = openDialog('userAddDialog', g.ctx + 'pc/sys/user/add?userType=1', {
        title: title,
        width: '800px',
        height: '450px',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            userAddDialog.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.save, handler: function () {
                topWin.frames['userAddDialog'].tijiao(function () {
                    userAddDialog.dialog('close');
                    $(el.tb).datagrid('reload');
                });
            }
        }, {
            text: itablei8n.close, handler: function () {
                userAddDialog.dialog('close');
            }
        }]
    });
}


/**
 * 删除用户
 *
 * @param mark
 */
function delAccount(mark) {
    var row = $(el.tb).datagrid('getSelected');
    if (!row) {
        topWin.layer.alert(XTJCGL.GYSYHGL_QXZYTJL, {icon: 0});
        return;
    }
    topWin.layer.confirm(XTJCGL.GYSYHGL_QDCZ + '?', function (index) {
        $.ajax({
            type: 'POST', url: g.ctx + 'pc/sys/user/updateStatus', data: {
                userId: row.id, status: mark
            }, success: function (res) {
                topWin.layer.close(index);
                topWin.layer.msg(XTJCGL.GYSYHGL_CZCG, {icon: 1});
                $(el.tb).datagrid('reload');
            }, error: function (data) {
                topWin.layer.alert(data.responseJSON.message, {icon: 2});
            }
        });
    })
}

/**
 * 重置查询条件
 */
function resetSearch() {
    $(el.userName).val('');
    $(el.accountName).val('');
    $(el.role).combobox('setValue', '');
    $(el.purchaseGroupId).combobox('setValue', '');
    $(el.tb).datagrid('options').queryParams = $(el.searchForm).serializeJson();
    $(el.tb).datagrid('load');
}