# -*- coding: utf-8 -*-
from ladon.ladonizer import ladonize
from ladon.types.ladontype import LadonType
import json
from django.contrib.auth.models import get_hexdigest
from django.contrib.auth.models import Group
from django.contrib.auth.models import User
from django.contrib.auth.models import Permission
import random
import sys
from django.contrib.contenttypes.models import ContentType
from mysite import utils
from mysite import sql_utils as dbutils_api
from django.db.models.loading import get_app
from django.db import models
from base.models import AppOperation
from base.custom_model import AppPage
from base.translation import DataTranslation, _ugettext_ as _
from django.conf import settings
from base.middleware import threadlocals
import datetime
from time import time
RET_INFO={}
class PermissionService(object):
    u"""
    【权限操作】查询所有权限
    """
    @ladonize(str,rtype=str)
    def GetAllPermission(self,id):
        '''
        【权限操作】获取人事、考勤、消费相关权限
        @param id:参数一 角色ID
        @rtype: 返回信息
            -11-角色不存在
            0  -操作成功 返回值格式 {"app_label":{"models":[{"model":["model_name"],"permissions":[{"codename":".."},{"codename":".."},...]},{"model":["model_name"],"permissions":[{"codename":".."},{"codename":".."},...]},...],"app":"app_label"}}
        '''
        RET_INFO['op']='GetAllPermission'
        apps={}
        tmp_apps = [e for e in settings.INSTALLED_APPS if e not in settings.INVISIBLE_APPS]   #获取配置文件的APP
        app_names={'personnel':'人事','att':'考勤','pos':'消费','base':'系统设置','iclock':'设备','auth':'','django_extensions':'','dbapp':'','worktable':''}
        for application in tmp_apps:
            app_label=application.split(".")[-1]
            try:
                app_names[app_label]
                name=app_names[app_label]
            except:
                name=''
            apps[app_label]={           #初始化APP
                'app':app_label,
                'name':name,
                'models':[]
                }
        app_labels=['personnel','pos','att'] #选择要获取权限的APP
        queryset=Permission.objects.all()
        empty_app=[]
        check_perm=[]                  #角色权限集合
        """
        获取角色权限
        """
        if id!='':
            try:
                group=Group.objects.get(id__exact=id) #判断角色是否存在
            except:
                RET_INFO['ret']='-11'
                RET_INFO['id']=id
                RET_INFO['data']={}

                return json.dumps(RET_INFO)
            if group:
                permissions=group.permissions.all()
                if len(permissions)>0:
                    for perm in permissions:
                        check_perm.append(perm.codename)
        for app_label in apps.keys():
            app=get_app(app_label)
            empty_models=[]
            page_modes=[]
            for i in dir(app):
                app_menu=None
                try:
                    model=app.__getattribute__(i)
                    m={}
                    disabled_perm=[]
                    permissions=[]
                    if issubclass(model, models.Model) and (model._meta.app_label==app_label):  #判断model是否为继承于model.Model
                        admin=hasattr(model, "Admin") and model.Admin or None
                        if not model._meta.abstract:
                            m={'name': u"%(name)s"%{'name':model._meta.verbose_name}}
                            if admin:
                                if hasattr(admin,"disabled_perms"):               #获取屏蔽的权限
                                    disabled_perm=admin.disabled_perms
                            if (not admin or not hasattr(admin, "visible") or admin.visible):
                                app_menu=app_label
                                if hasattr(admin, "app_menu"):
                                    app_menu=admin.app_menu
                                if not model._meta.abstract:
                                    ct=ContentType.objects.get_for_model(model)   #根据model获取文档对象
                                    for perm in queryset.filter(content_type=ct): #循环该文档对象的全部权限
                                        permission={#'codename':'',
                                            'id':'',
                                            'name':''
                                            }
                                        if perm.codename not in disabled_perm:   #获取非屏蔽的权限
                                            permission['name']=perm.name
                                            permission['id']=perm.pk
                                            if perm.codename in check_perm:      #判断该权限是否在角色权限集合里
                                                permission['check']='checked'    #存在标识为checked
                                            #permission['codename']=perm.codename
                                            permissions.append(permission)
                    elif issubclass(model, AppOperation) and hasattr(model, 'view'):   #判断model是否为继承于AppOperation
                        if (not hasattr(model, 'visible') or getattr(model,'visible')):
                            m={'name':u"%(name)s"%{'name': hasattr(model, "verbose_name") and model.verbose_name or (u"%s"%_(model.__name__))}}
                            app_menu=app_label
                            if hasattr(model, "_app_menu"):
                                app_menu=model._app_menu
                            if hasattr(model,"_disabled_perms"):
                                disabled_perm=model._disabled_perms
                            if hasattr(model, '_parent_model'):
                                m['parent_model']=model._parent_model
                            ct = ContentType.objects.filter(app_label=app_label, model=model.__name__.lower())
                            for perm in queryset.filter(content_type=ct):
                                permission={#'codename':'',
                                    'id':'',
                                    'name':''}
                                if perm.codename not in disabled_perm:
                                    permission['name']=perm.name
                                    permission['id']=perm.pk
                                    #permission['codename']=perm.codename
                                    if perm.codename in check_perm:
                                        permission['check']='checked'
                                    permissions.append(permission)
                            if hasattr(model, 'add_model_permission'):
                                for elem in model.add_model_permission:
                                    ct=ContentType.objects.get_for_model(elem)
                                    #m['name']=model._meta.verbose_name
                                    for perm in queryset.filter(content_type=ct):  #循环该文档对象的全部权限
                                        permission={#'codename':'',
                                            'id':'',
                                            'name':''}
                                        if perm.codename not in disabled_perm:     #
                                            permission['name']=perm.name
                                            permission['id']=perm.pk
                                            if perm.codename in check_perm:
                                                permission['check']='checked'
                                            #permission['codename']=perm.codename
                                            permissions.append(permission)
                    elif issubclass(model, AppPage):  #判断model是否为继承于AppPage
                        app_menu = hasattr(model, 'app_menu') and model.app_menu or app_label
                        if (not hasattr(model, 'visible') or getattr(model,'visible')):
                            m={'name':u"%(name)s"%{'name': hasattr(model, "verbose_name") and model.verbose_name or (u"%s"%_(model.__name__))}}
                            if hasattr(model,"_disabled_perms"):
                                disabled_perm=model._disabled_perms
                            ct = ContentType.objects.filter(app_label=app_label, model=model.__name__.lower())
                            for perm in queryset.filter(content_type=ct):
                                permission={#'codename':'',
                                    'id':'',
                                    'name':''}
                                if perm.codename not in disabled_perm:
                                    permission['name']=perm.name
                                    permission['id']=perm.pk
                                    #permission['codename']=perm.codename
                                    if perm.codename in check_perm:
                                        permission['check']='checked'
                                    permissions.append(permission)
                            if hasattr(model, 'add_model_permission'):
                                for elem in model.add_model_permission:
                                    ct=ContentType.objects.get_for_model(elem)
                                    for perm in queryset.filter(content_type=ct):  #循环该文档对象的全部权限
                                        permission={#'codename':'',
                                            'id':'',
                                            'name':''}
                                        if perm.codename not in disabled_perm:     #
                                            permission['name']=perm.name
                                            permission['id']=perm.pk
                                            if perm.codename in check_perm:
                                                permission['check']='checked'
                                            permissions.append(permission)
                    if m:
                        m['model']=model.__name__.lower()
                    if permissions:
                        m['permissions']=permissions
                        if app_menu in app_labels:
                            apps[app_menu]['models'].append(m)
                except:
#                    import traceback; traceback.print_exc()
                    pass
            if len(apps[app_label]['models'])==0:
                empty_app.append(app_label)
        for app_index in empty_app: apps.pop(app_index)
        RET_INFO['ret']='0'
        RET_INFO['id']=id
        RET_INFO['op']='GetAllPermission'
        RET_INFO['data']=apps
        jsoninfo = json.dumps(RET_INFO)
        return jsoninfo

class GroupService(object):

    u"""
    【角色操作】包含更新，新增，删除角色等操作
    """
    @ladonize(str,str,str,rtype=str)
    def SetGroup(self,group_info,perm_info,operation):
        """
        更新/新增角色基本信息
        @param group_info: 参数一 角色信息JSON数据格式{"group_id":"角色ID","group_name":"角色名称"}
        @param perm_info: 参数二 权限信息JSON数据 格式{"permissions":[{"id":".."},..]}
        @param operation: 参数三 标识操作类型 'add':新增 'edit':编辑
        @rtype: 返回执行结果信息
             0  - 操作成功
            -11 - 角色不存在
            -21 - group_info数据错误
            -22 - 角色名称已经存在
            -23 - 权限添加失败
            -24 - 权限不存在
        """
        RET_INFO['op']='SetGroup'
        RET_INFO['data']={}
        try:
            group=utils.loads(group_info)           #格式化数据
            group_id=group['group_id']              #获取group_id
            group_name=group['group_name']          #获取group_name
        except:
            RET_INFO['ret']='-21'
            RET_INFO['id']=''
            return json.dumps(RET_INFO)
        if operation=='edit':
            from django.core.cache import cache
            try:
                g=Group.objects.get(id__exact=group_id)   #判断角色是否存在
            except:
                RET_INFO['ret']="-11"
                RET_INFO['id']=group_id
                RET_JSON_INFO=json.dumps(RET_INFO)
                return RET_JSON_INFO
            users = g.user_set.all()
            for user in users:
                cache.set('%s_cache_update' % user.username, user.username, 5*60)
                cache.delete('%s_perm_cache_update' % user.username)
            if g.name!=group_name:                  #判断角色名称是否修改
                group_checkname=Group.objects.filter(name__exact=group_name) #判断角色名称是否重复
                if group_checkname:
                    RET_INFO['ret']="-22"
                    RET_INFO['id']=group_id
                    RET_JSON_INFO=json.dumps(RET_INFO)
                    return RET_JSON_INFO
                else:
                    g.name=group_name
#                    g.save()
        if operation=='add':
            g=Group.objects.filter(name__exact=group_name)
            if g:
                RET_INFO['ret']="-11"
                RET_INFO['id']=group_id
                RET_JSON_INFO=json.dumps(RET_INFO)
                return RET_JSON_INFO
            else:
                g=Group(id=group_id,name=group_name)
                g.save()
        try:      #角色添加权限前先清空角色下的权限
            perms=g.permissions.all()
            if len(perms)>0:
                for perm in perms:
                    g.permissions.remove(perm)
            if perm_info:
                permissions=utils.loads(perm_info)      #格式化权限数据
                if permissions['permissions']:
                    for permission in permissions['permissions']: #循环获取权限数据，保存到角色的权限集合
                        id=permission['id']
                        try:
                            permission=Permission.objects.get(id__exact=id)  #判断该权限是否存在
                        except:
                            RET_INFO['ret']='-24'
                            RET_INFO['id']=id
                            return json.dumps(RET_INFO)
                        g.permissions.add(permission)
                    g.save()
            RET_INFO['ret']='0'
            RET_INFO['id']=group_id
        except:
            if operation=='add':
                g.delete()
            RET_INFO['ret']='-23'
            RET_INFO['id']=group_id
        RET_JSON_INFO=json.dumps(RET_INFO)
        return RET_JSON_INFO
    @ladonize(str,rtype=str)
    def DeleteGroup(self,ids):
        """
        删除角色
        @param ids: 参数一 角色ID id1,id2,id3...
        @rtype: 返回执行结果信息
              0 - 操作成功
            -11 - 角色不存在
            -25 - 删除角色权限失败
            -26 - 角色用户正在使用中
            -27 - ids数据有误
            -28 - 默认角色不能被删除
        """
        RET_INFO['op']='DeleteGroup'
        try:
            group_ids=ids.split(',')           #数据转换
        except:
            RET_INFO['ret']='-27'
            RET_INFO['id']=''
            return json.dumps(RET_INFO)
        group_set=set()
        for id in group_ids:
            if id=='1':
                RET_INFO['ret']='-28'           #默认角色不能被删除
                RET_INFO['id']='1'
                return json.dumps(RET_INFO)
            if id!='':
                try:
                    g=Group.objects.get(id__exact=id)     #判断角色是否存在
                except:
                    RET_INFO['ret']='-11'
                    RET_INFO['id']=id
                    RET_JSON_INFO=json.dumps(RET_INFO)
                    return RET_JSON_INFO
                users=g.user_set.all()                    #获取有该角色的全部用户
                if len(users)>0:                          #判断该角色下是否有用户，存在则不能删除
                    RET_INFO['ret']='-26'
                    RET_INFO['id']=id
                    return json.dumps(RET_INFO)
                group_set.add(g)

        for group in group_set:
            try:
                permissions=group.permissions.all()         #先删权限再删除用户
                for permission in permissions:
                    group.permissions.remove(permission)
                group.delete()
            except:
                RET_INFO['ret']='-25'
                RET_INFO['id']=group.id
                RET_JSON_INFO=json.dumps(RET_INFO)
                return RET_JSON_INFO
        RET_INFO['ret']='0'
        RET_INFO['id']=ids
        RET_JSON_INFO=json.dumps(RET_INFO)
        return RET_JSON_INFO
    @ladonize(str,rtype=str)
    def PermisssionsForGroup(self,id):
        """
        获取角色权限
        @param id: 参数一 角色ID
        @rtype: 返回执行结果信息
              0 - 操作成功
            -11 - 角色不存在
            -29 - 角色ID不能为空
            -30 - 权限获取失败
        """
        RET_INFO['op']='PermisssionsForGroup'
        RET_INFO['id']=id
        RET_INFO['data']={}
        check_perm=[]
        if id!='':
            try:
                group=Group.objects.get(id__exact=id)
            except:
                RET_INFO['ret']='-11'
                return json.dumps(RET_INFO)
            try:
                permissions=group.permissions.all()
                if len(permissions)>0:
                    for perm in permissions:
                        check_perm.append(perm.id)
                RET_INFO['data']=check_perm
                RET_INFO['ret']='0'
                return json.dumps(RET_INFO)
            except:
                RET_INFO['ret']='-30'
                return json.dumps(RET_INFO)
        RET_INFO['ret']='-29'
        return json.dumps(RET_INFO)

class UserService(object):
    u"""
    【用户操作】包含更新/新增，删除用户，修改密码等操作
    """
    @ladonize(str,str,rtype=str)
    def ChangePwd(self,username,password_info):
        """
        修改密码
        @param username: 参数一 用户名
        @param password_info: 参数二 密码信息 格式{"old_pwd":"原密码","new_pwd":"新密码"}
        @rtype: 返回执行结果信息
              0 - 操作成功
            -41 - 用户名为空
            -42 - 用户不存在
            -43 - password_info数据错误
            -44 - 新密码不能为空
        """
        RET_INFO['op']='DeleteUser'
        RET_INFO['data']={}
        if username!='':              #判断用户名是否为空
            try:
                user=User.objects.get(username__exact=username)  #判断用户是否存在
            except:
                RET_INFO['ret']='-42'
                RET_INFO['id']=username
                return json.dumps(RET_INFO)
        else:
            RET_INFO['ret']='-41'
            RET_INFO['id']=username
            return json.dumps(RET_INFO)
        try:
            pwd=utils.loads(password_info)       #格式化数据
            old_pwd=pwd['old_pwd']
            new_pwd=pwd['new_pwd']
        except:
            RET_INFO['ret']='-43'
            RET_INFO['id']=username
            return json.dumps(RET_INFO)

#        if user.check_password(old_pwd) or old_pwd==user.password:    #判断密码是否一致
        if new_pwd!='':                       #判断新密码是否为空
            user.set_password(new_pwd)
            super(User,user).save()
            RET_INFO['ret']='0'
            RET_INFO['id']=username
            return json.dumps(RET_INFO)
        else:
            RET_INFO['ret']='-44'
            RET_INFO['id']=username
            return json.dumps(RET_INFO)
#        else:
#            RET_INFO['ret']='-45'
#            RET_INFO['id']=username
#            return json.dumps(RET_INFO)
    @ladonize(str,str,rtype=str)
    def DeleteUser(self,usernames,current_username):
        """
        删除用户
        @param usernames: 参数一 用户ID 格式 username1,username2,username3
        @param current_username: 参数二 当前用户的用户名
        @rtype: 返回执行结果信息
            0-操作成功
            -46 - 删除用户不存在
            -47 - 当前用户不存在
            -48 - 用户不能删除自己
            -49 - 默认用户不能被删除
            -50 - usernames 信息有误
            -51 - 删除username不能为空
        """
        RET_INFO['op']='DeleteUser'
        RET_INFO['data']={}
        model_dept = sys.modules['mysite.personnel.models.model_dept']
        Department = getattr(model_dept,'Department')
        model_deptadmin = sys.modules['mysite.personnel.models.model_deptadmin']
        DeptAdmin = getattr(model_deptadmin,'DeptAdmin')
        model_area = sys.modules['mysite.personnel.models.model_area']
        Area = getattr(model_area,'Area')
        model_areaadmin = sys.modules['mysite.personnel.models.model_areaadmin']
        AreaAdmin = getattr(model_areaadmin,'AreaAdmin')
        current_user=User.objects.filter(username=current_username)
        if current_user is None:  #判断当前用户是否存在
            RET_INFO['ret']= '-47'
            RET_INFO['id']=current_username
            RET_JSON_INFO=json.dumps(RET_INFO)
            return RET_JSON_INFO
        try:
            usernames=usernames.split(',')
        except:
            RET_INFO['ret']= '-50'
            RET_INFO['id']=''
            return json.dumps(RET_INFO)

        if len(usernames)==0:
            RET_INFO['ret']= '-51'
            RET_INFO['id']=''
            return json.dumps(RET_INFO)
        users=User.objects.filter(username__in=usernames) #获取需删除用户
        if users.count()==len(usernames):       #判断删除对象是否与数据库存在对象一致
            for user in users:
                if user.id=='1' or user.id == '2':#默认用户不能被删除
                    RET_INFO['ret']= '-49'
                    RET_INFO['id']= ''
                    RET_JSON_INFO=json.dumps(RET_INFO)
                    return RET_JSON_INFO
                if user.username==current_username: #用户不能删除自己
                    RET_INFO['ret']= '-48'
                    RET_INFO['id']=user.username
                    RET_JSON_INFO=json.dumps(RET_INFO)
                    return RET_JSON_INFO
                groups=user.groups.all()
                deptadmins=DeptAdmin.objects.filter(user=user)
                areaadmins=AreaAdmin.objects.filter(user=user)
                if len(groups)>0:                     #移除用户所属的角色
                    for group in groups:
                        user.groups.remove(group)
                if len(deptadmins)>0:                  #移除用户所属的部门
                    for deptadmin in deptadmins:
                        DeptAdmin.objects.filter(pk=deptadmin.pk).delete()
                if len(areaadmins)>0:                  #移除用户所属区域
                    for areaadmin in areaadmins:
                        AreaAdmin.objects.filter(pk=areaadmin.pk).delete()
                user.delete()
                RET_INFO['ret']= '0'
                RET_INFO['id']=usernames
        else:
            RET_INFO['ret']= '-46'
            RET_INFO['id']=usernames
        return json.dumps(RET_INFO)
    @ladonize(str,str,str,rtype=str)
    def SetUser(self,user_info,group_info,operation):
        """
        新增/编辑用户
        @param user_info: 参数一 用户信息格式 {"id":"用户ID","is_resetPw":"是否重置密码","pwd":"确认密码","old_username":"原用户名(新增时为空)","username":"用户名","first_name":"名","last_name":"姓","password":"密码","is_staff":"是否是员工","is_superuser":"是否是超级管理员","email":"邮箱","depts":[{"dept_id":"部门ID1"},{"dept_id":"部门ID2"}],"areas":[{"area_id":"区域ID"}]}
        @param group_info: 参数二 角色名称集合的JSON数据 格式{"groups":[{"id":"角色ID"},...]}
        @param operation: 参数三 表示操作类型 'add':新增,'edit':编辑
        @rtype: 返回执行结果信息
              0 - 操作成功
            -52 - user_info数据错误
            -53 - 用户名已经存在
            -54 - 2次密码输入不一致
            -55 - 用户保存失败
            -56 - group_info数据错误
            -57 - 添加角色失败
            -58 - 添加授权部门，授权区域失败
            -59 - 编辑用户不存在
            -60 - 密码不能为空
            -61 - 授权区域不存在
            -62 - 授权部门不存在
        """
        RET_INFO['op']='SetUser'
        RET_INFO['data']={}
        model_dept = sys.modules['mysite.personnel.models.model_dept']
        Department = getattr(model_dept,'Department')
        model_deptadmin = sys.modules['mysite.personnel.models.model_deptadmin']
        model_areaadmin = sys.modules['mysite.personnel.models.model_areaadmin']
        DeptAdmin = getattr(model_deptadmin,'DeptAdmin')
        AreaAdmin = getattr(model_areaadmin,'AreaAdmin')
        model_area = sys.modules['mysite.personnel.models.model_area']
        Area = getattr(model_area,'Area')
        try:
            user_info=utils.loads(user_info)
            user_id=user_info['id']
            old_username=user_info['old_username']
            username=user_info['username']
            first_name=user_info['first_name']
            last_name=user_info['last_name']
            is_staff=user_info['is_staff']
            is_superuser=user_info['is_superuser']
            is_resetPw=user_info['is_resetPw']
            email=user_info['email']
            password=user_info['password']
            pwd=user_info['pwd']
            depts=user_info['depts']
            areas=user_info['areas']
        except:
            RET_INFO['ret']='-52'
            RET_INFO['id']=''
            RET_JSON_INFO=json.dumps(RET_INFO)
            return RET_JSON_INFO
        if is_staff=='1':          #判断职员状态
            is_staff=True
        else:
            is_staff=False
        if is_superuser=='1':      #判断超级用户状态
            is_superuser=True
        else:
            is_superuser=False
        if operation =='edit':#编辑用户
            from django.core.cache import cache
            cache.set('%s_cache_update' % username, username, 5*60)
            cache.delete('%s_perm_cache_update' % username)
            try:
                user=User.objects.get(username__exact=old_username)          #判断编辑用户是否存在
                if user.username!=username:   #判断用户名是否修改
                    check_user=User.objects.filter(username__exact=username)  #判断用户名是否重复
                    if check_user:
                        RET_INFO['ret']='-53'
                        RET_INFO['id']=user_id
                        RET_JSON_INFO=json.dumps(RET_INFO)
                        return RET_JSON_INFO
                user.username=username
                user.first_name
                user.last_name=last_name
                user.is_staff=is_staff
                user.is_superuser=is_superuser
                user.email=email
                '''
                判断是否重置密码
                '''
                if is_resetPw=='1':
                    if password=='':         #密码不能为空
                        RET_INFO['ret']='-60'
                        RET_INFO['id']=user_id
                        RET_JSON_INFO=json.dumps(RET_INFO)
                    if password==pwd:        #2次密码要一致
                        user.password=pwd
                        user.set_password(password)
                    else:
                        RET_INFO['ret']='-54'
                        RET_INFO['id']=user_id
                        RET_JSON_INFO=json.dumps(RET_INFO)
                        return RET_JSON_INFO
            except:
                RET_INFO['ret']='-59'
                RET_INFO['id']=user_id
                RET_JSON_INFO=json.dumps(RET_INFO)
                return RET_JSON_INFO
        elif operation=='add':#新增用户
            user_checkusername=User.objects.filter(username=username)  #判断用户名是否存在
            if user_checkusername:
                RET_INFO['ret']='-53'
                RET_INFO['id']=user_id
                RET_JSON_INFO=json.dumps(RET_INFO)
                return RET_JSON_INFO
            else:
                user=User(username=username,first_name=first_name,last_name=last_name,is_staff=is_staff,is_superuser=is_superuser,email=email,password=password)
                if password !='':            #密码不能为空
                    user.set_password(password)
                    user.save()
                else:
                    RET_INFO['ret']='-60'
                    RET_INFO['id']=user_id
                    RET_JSON_INFO=json.dumps(RET_INFO)
                    return RET_JSON_INFO
        deptadmins=DeptAdmin.objects.filter(user=user)  #获取用户的授权部门
        areaadmins=AreaAdmin.objects.filter(user=user)  #获取用户的授权区域
        try:
            '''
            如果是超级用户，清空所属角色，授权部门，授权区域
            '''
            if is_superuser:
                if user.groups:
                    user.groups=[]
                if len(deptadmins)>0:
                    for deptadmin in deptadmins:
                        DeptAdmin.objects.filter(pk=deptadmin.pk).delete()
                if len(areaadmins)>0:
                    for areaadmin in areaadmins:
                        AreaAdmin.objects.filter(pk=areaadmin.pk).delete()
                user.save()
                RET_INFO['ret']='0'
                RET_INFO['id']= user_id
                RET_JSON_INFO=json.dumps(RET_INFO)
                return RET_JSON_INFO
        except:
            RET_INFO['ret']='-55'
            RET_INFO['id']=user_id
            RET_JSON_INFO=json.dumps(RET_INFO)
            return RET_JSON_INFO
        '''
        添加角色前先清空原有的
        '''
        try:
            if user.groups:
                groups=user.groups.all()
                len(groups)
                for group in groups:
                    user.groups.remove(group)
            try:
                groups=utils.loads(group_info)
                for group in groups['groups']:
                    group_id=str(group['id'])
                    group=Group.objects.get(id__exact=group_id)
                    user.groups.add(group)
            except:
                RET_INFO['ret']='-56'
                RET_INFO['id']=''
                RET_JSON_INFO=json.dumps(RET_INFO)
                return RET_JSON_INFO
        except:
            if operation=='add':
                user.delete()
            RET_INFO['ret']='-57'
            RET_INFO['id']=''
            RET_JSON_INFO=json.dumps(RET_INFO)
            return RET_JSON_INFO
        #授权部门验证
        if depts:
            dept_ids=[dept['dept_id'] for dept in depts]
            dpts=Department.objects.filter(id__in=dept_ids)
            if dpts.count()!=len(dept_ids): #判断数据库中获取的是否与参数一致
                if operation=='add':
                    user.delete()
                RET_INFO['ret']='-62'
                RET_INFO['id']= user_id
                RET_JSON_INFO=json.dumps(RET_INFO)
                return RET_JSON_INFO
        #授权区域验证
        if areas:
            area_ids=[area['area_id'] for area in areas]
            ares=Area.objects.filter(id__in=area_ids)
            if ares.count()!=len(area_ids): #判断数据库中获取的是否与参数一致
                if operation=='add':
                    user.delete()
                RET_INFO['ret']='-61'
                RET_INFO['id']= user_id
                RET_JSON_INFO=json.dumps(RET_INFO)
                return RET_JSON_INFO
        '''
        更新用户授权部门，授权区域，先删除全部再逐一添加
        '''
        try:
            if len(deptadmins)>0:
                for deptadmin in deptadmins:
                    DeptAdmin.objects.filter(pk=deptadmin.pk).delete()
            if depts:
                for dept in dpts:
                    if dept:
                        DeptAdmin(user=user, dept=dept).save()
            if len(areaadmins)>0:
                for areaadmin in areaadmins:
                    AreaAdmin.objects.filter(pk=areaadmin.pk).delete()
            if areas:
                for area in ares:
                    if area:
                        AreaAdmin(user=user, area=area).save()
            user.save()
            RET_INFO['ret']='0'
            RET_INFO['id']= user_id
            RET_JSON_INFO=json.dumps(RET_INFO)
            return RET_JSON_INFO
        except:
            if operation=='add':
                user.delete()
            RET_INFO['ret']='-58'
            RET_INFO['id']=user_id
            RET_JSON_INFO=json.dumps(RET_INFO)
            return RET_JSON_INFO













