//#import $owl_mall_u:services/modelService.jsx
//#import $owl_orgs:services/modelService.jsx
//#import $owl_org_member:services/modelService.jsx
//#import @owl:utils/PermissionUtil.jsx

var pluginId = "addToOrgMemberPlugin";

function main(){
    var params = JSON.parse($body);
    var data = params.data;
    var id = params.id;
    
    
    try{
        checkBackendPluginPermission(pluginId);
    }catch(errmsg){
        var ret = {
            state:"err",
            msg:errmsg
        }
        out.print(JSON.stringify(ret));
        return;
    }
        
    var mobile = data.mobile;
    var admin = owl_mall_uService.getUniqueObj('mobile',mobile);
    if(!admin){
        admin = owl_mall_uService.getUniqueObj('loginId',mobile);
    }
    if(!admin){
        admin = owl_mall_uService.getUniqueObj('email',mobile);
    }
    if(!admin){
        var ret = {
            state:"err",
            msg:"用户不存在"
        }
        out.print(JSON.stringify(ret));
        return;
    }
    
    // 检查用户是否已存在于org_user中
    var existingOrgMember = owl_org_memberService.getUniqueObj('userId',admin.id);
    if(existingOrgMember){
        var ret = {
            state:"err",
            msg:"会员已经存在,请勿重复添加"
        }
        out.print(JSON.stringify(ret));
        return;
    }

    var env = checklogin();
    var orgId = env.orgId;
    var org = owl_orgsService.get(orgId);
    if(!org){
        var ret = {
            state:"err",
            msg:"组织不存在"
        }
        out.print(JSON.stringify(ret));
        return;
    }

    // 创建org_user记录
    var orgUser = {
        userId: admin.id,
        name: admin.name || admin.loginId,
        orgId:org.id,
        orgName:org.name,
        loginId: admin.loginId,
        realName: admin.realName,
        nickName: admin.nickName,
        mobile: admin.mobile,
        email: admin.email,
        isEnable: 1,
        orgId:env.orgId,
        _orgId:env.orgId,
        _orgIds:env.orgIds || [env.orgId]
    };

    owl_org_memberService.add(orgUser);
    
    var ret = {
        state:"ok",
        msg:"操作成功,请过几秒后刷新。"
    }
    out.print(JSON.stringify(ret));
}
main();
