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

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


/**
 * 加载页面表格
 */
function loadGrid() {
    //采购组
    $("#contractPurchaseGroup").combobox({
        valueField: 'purchaseGroupCode',
        textField: 'codeWithDesc',
        limitToList: 'true',
        method: 'POST',
        prompt: '--- 请选择 ---',
        url: g.ctx + 'pc/sys/purchaseGroup/rest/listAll',
    });
    var searchHeight = $(el.searchForm).outerHeight();
    var pager = initGridPagerNew(el.bodyHeight - searchHeight, 37, 40);
    let singleSelect = true;
    if (select === 1 && single === 0) {
        singleSelect = false
    }
    let toolbar = ""
    if (select === 0) {
        toolbar = "#toolbar"
    }

    var formData = $("#searchForm").serializeJson();
    var supplierFlag = formData.supplierFlag;
    let url = g.ctx + 'pc/sys/user/list?userType=0&roleCodes=' + roleCodes
    if (supplierFlag == "1") {
        url = g.ctx + 'pc/sys/user/list?userType=0&roleCodes=' + roleCodes + "&purchaseGroupId=" + $("#purchaseGroupCode").val()
    }

    $(el.tb).datagrid({
        height: el.bodyHeight - searchHeight,
        url: url,
        method: "GET",
        singleSelect: singleSelect,
        pagination: true,
        pageSize: pager.pageSize,
        pageList: pager.pageList, // loadMsg: ALLCOMMON.LOADING,
        rownumbers: true,
        columns: [[{
            field: 'ck', checkbox: true
        }, {
            field: 'username', title: XTJCGL.GYSYHGL_YHMC, width: 120
        }, {
            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: 'deptName', title: '部门名称', width: 130
        }, {
            field: 'dispatchRoles', title: XTJCGL.GYSYHGL_YFPJS, width: 150
        }, {
            field: 'purchaseCount', title: XTJCGL.GYSYHGL_YFPCGZ, width: 150, formatter: function (value, row) {
                return '<a style="color: green" onclick="dispatchPurchasingGroup(' + row.id + ')">已分配 ' + value + '</a>';
            }
        }, {
            field: 'purchaseOrgCount', title: XTJCGL.GYSYHGL_YFPCGZZ, width: 150, formatter: function (value, row) {
                return '<a style="color: green" onclick="dispatchPurchaseOrg(' + row.id + ')">已分配 ' + value + '</a>';
            }
        },
        //     {
        //     field: 'xunjiaTypeCount', title: XTJCGL.GYSYHGL_YFPXJLB, width: 150, formatter: function (value, row) {
        //         return '<a style="color: green" onclick="dispatchXunjiaType(' + row.id + ')">已分配 ' + value + '</a>';
        //     }
        // }
        ]],
        toolbar: toolbar
    });
}


/**
 * 账号解锁
 */
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;
    }
    $.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 dispatchOrg(id) {

    if ('' === id) {
        var row = $(el.tb).datagrid('getSelected');
        if (!row) {
            topWin.layer.alert(XTJCGL.GYSYHGL_QXZYTJL, {icon: 0});
            return false;
        }

        id = row.id;
    }

    var dispatchOrgDialog = openDialog('dispatchOrg', g.ctx + 'pc/sys/org/userOrgAdd?userId=' + id, {
        title: '分配部门',
        width: '450px',
        height: '98%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            dispatchOrgDialog.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.save, handler: function () {
                topWin.frames['dispatchOrg'].page.save(function () {
                    topWin.layer.msg('数据保存成功', {icon: 1});
                    dispatchOrgDialog.dialog('close');
                    $(el.tb).datagrid('reload');
                });
            }
        }, {
            text: itablei8n.close, handler: function () {
                dispatchOrgDialog.dialog('close');
            }
        }]
    });
}

/**
 * 编辑
 */
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?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');
            }
        }]
    })
}


/**
 * 分配采购组
 *
 * @param id 用户ID
 */
function dispatchPurchasingGroup(id) {
    if ('' === id) {
        var row = $(el.tb).datagrid('getSelected');
        if (!row) {
            topWin.layer.alert(XTJCGL.GYSYHGL_QXZYTJL, {icon: 0});
            return;
        }
        id = row.id;
    }

    var dispatchPurchasingGroupDialog = openDialog('dispatchPurchasingGroup', g.ctx + 'pc/sys/purchaseGroup/userPurchaseGroupAdd?userId=' + id, {
        title: '分配采购组',
        width: '400px',
        height: '98%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            dispatchPurchasingGroupDialog.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.save, handler: function () {
                topWin.frames['dispatchPurchasingGroup'].page.save(function () {
                    topWin.layer.msg('数据保存成功', {icon: 1});
                    dispatchPurchasingGroupDialog.dialog('close');
                    $(el.tb).datagrid('reload');
                });
            }
        }, {
            text: itablei8n.close, handler: function () {
                dispatchPurchasingGroupDialog.dialog('close');
            }
        }]
    });
}

/**
 * 分配计划组
 *
 * @param id 用户ID
 */
function dispatchPlanGroup(id) {
    if ('' === id) {
        var row = $(el.tb).datagrid('getSelected');
        if (!row) {
            topWin.layer.alert(XTJCGL.GYSYHGL_QXZYTJL, {icon: 0});
            return;
        }
        id = row.id;
    }

    var dispatchPlanGroupDialog = openDialog('dispatchPlanGroup', g.ctx + 'user/dispatchPlanGroupUI?userId=' + id, {
        title: '分配计划组',
        width: '400px',
        height: '700px',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            dispatchPlanGroupDialog.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.save, handler: function () {
                topWin.frames['dispatchPlanGroup'].page.save(function () {
                    topWin.layer.msg('数据保存成功', {icon: 1});
                    dispatchPlanGroupDialog.dialog('close');
                    $(el.tb).datagrid('reload');
                });
            }
        }, {
            text: itablei8n.close, handler: function () {
                dispatchPlanGroupDialog.dialog('close');
            }
        }]
    });
}

/**
 * 分配工厂
 */
function dispatchFactory(id) {

    if ('' === id) {
        var row = $(el.tb).datagrid('getSelected');
        if (!row) {
            topWin.layer.alert(XTJCGL.GYSYHGL_QXZYTJL, {icon: 0});
            return false;
        }

        id = row.id;
    }

    var dispatchFactoryDialog = openDialog('dispatchFactory', g.ctx + 'pc/sys/factory/userFactoryAdd?userId=' + id, {
        title: '分配工厂',
        width: '420px',
        height: '98%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            dispatchFactoryDialog.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.save, iconCls: 'icon-save', handler: function () {
                topWin.frames['dispatchFactory'].page.save(function () {
                    topWin.layer.msg('数据保存成功', {icon: 1});
                    dispatchFactoryDialog.dialog('close');
                    $(el.tb).datagrid('reload');
                });
            }
        }, {
            text: itablei8n.close, iconCls: 'icon-cancel', handler: function () {
                dispatchFactoryDialog.dialog('close');
            }
        }]
    });
}

/**
 * 分配采购组织
 */
function dispatchPurchaseOrg(id) {

    if ('' === id) {
        var row = $(el.tb).datagrid('getSelected');
        if (!row) {
            topWin.layer.alert(XTJCGL.GYSYHGL_QXZYTJL, {icon: 0});
            return false;
        }

        id = row.id;
    }

    var dispatchPurchaseOrgDialog = openDialog('dispatchPurchaseOrg', g.ctx + 'pc/sys/purchaseOrg/userPurchaseOrgAdd?userId=' + id, {
        title: '分配采购组织',
        width: '420px',
        height: '98%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            dispatchPurchaseOrgDialog.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.save, iconCls: 'icon-save', handler: function () {
                topWin.frames['dispatchPurchaseOrg'].page.save(function () {
                    topWin.layer.msg('数据保存成功', {icon: 1});
                    dispatchPurchaseOrgDialog.dialog('close');
                    $(el.tb).datagrid('reload');
                });
            }
        }, {
            text: itablei8n.close, iconCls: 'icon-cancel', handler: function () {
                dispatchPurchaseOrgDialog.dialog('close');
            }
        }]
    });
}

/**
 * 分配询价类别
 */
function dispatchXunjiaType(id) {

    if ('' === id) {
        var row = $(el.tb).datagrid('getSelected');
        if (!row) {
            topWin.layer.alert(XTJCGL.GYSYHGL_QXZYTJL, {icon: 0});
            return false;
        }

        id = row.id;
    }

    var dispatchXunjiaTypeDialog = openDialog('dispatchXunjiaType', '/user/xunjiaType/dispatchPurchaseOrgUI?userId=' + id, {
        title: '分配询价类别',
        width: '420px',
        height: '98%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            dispatchXunjiaTypeDialog.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.save, iconCls: 'icon-save', handler: function () {
                topWin.frames['dispatchXunjiaType'].page.save(function () {
                    topWin.layer.msg('数据保存成功', {icon: 1});
                    dispatchXunjiaTypeDialog.dialog('close');
                    $(el.tb).datagrid('reload');
                });
            }
        }, {
            text: itablei8n.close, iconCls: 'icon-cancel', handler: function () {
                dispatchXunjiaTypeDialog.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', {
        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 syncEmployees() {
    topWin.layer.confirm("是否要同步员工", function (index) {
        topWin.layer.close(index);
        var load = topWin.layer.msg('数据同步中, 请耐心等待......', {icon: 16, time: 0, shade: 0.1});
        $.ajax({
            url: g.ctx + 'user/syncEmployees', method: 'post', success: function (data) {
                layer.close(load);
                topWin.layer.msg(data, {icon: 1, time: 500});
                $(el.tb).datagrid("load");
            }, error: function (data) {
                layer.close(load);
                parent.layer.msg(data.responseJSON, {icon: 2});
            }
        });
    });

}

/**
 * 查看用户分配的公司
 *
 * @param id 用户ID
 */
function showAssignDetail(id) {
    var allotCompany = openDialog('allotCompany', g.ctx + 'organization/listOrgUI?id=' + id, {
        title: '分配权限公司',
        width: '400px',
        height: '700px',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            allotCompany.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.save, handler: function () {
                topWin.frames['allotCompany'].page.save(function () {
                    topWin.layer.msg('数据保存成功', {icon: 1});
                    allotCompany.dialog('close');
                    $(el.tb).datagrid('reload');
                });
            }
        }, {
            text: itablei8n.close, handler: function () {
                allotCompany.dialog('close');
            }
        }]
    });
}

/**
 * 分配成本中心
 */
function dispatchBudgetCostCenter(id) {

    if ('' === id) {
        var row = $(el.tb).datagrid('getSelected');
        if (!row) {
            topWin.layer.alert(XTJCGL.GYSYHGL_QXZYTJL, {icon: 0});
            return false;
        }

        id = row.id;
    }

    var dispatchBudgetCostCenterDialog = openDialog('dispatchBudgetCostCenter', '/budgetCostCenter/dispatchBudgetCostCenterUI?userId=' + id, {
        title: '分配成本中心',
        width: '600px',
        height: '98%',
        cache: false,
        modal: true,
        border: false,
        draggable: false,
        shadow: false,
        onClose: function () {
            dispatchBudgetCostCenterDialog.dialog('destroy');
        },
        buttons: [{
            text: itablei8n.save, iconCls: 'icon-save', handler: function () {
                topWin.frames['dispatchBudgetCostCenter'].page.save(function () {
                    topWin.layer.msg('数据保存成功', {icon: 1});
                    dispatchBudgetCostCenterDialog.dialog('close');
                    $(el.tb).datagrid('reload');
                });
            }
        }, {
            text: itablei8n.close, iconCls: 'icon-cancel', handler: function () {
                dispatchBudgetCostCenterDialog.dialog('close');
            }
        }]
    });
}

function chooseRow(call) {
    var rows = $(el.tb).datagrid("getChecked")
    if (rows.length <= 0) {
        topWin.layer.msg("至少选中一条数据")
    }
    call(rows)
}

/**
 * 重置查询条件
 */
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');
}