from django.shortcuts import render

# Create your views here.
from django.contrib.auth.decorators import login_required
from .models import *
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from .forms import *
from django.shortcuts import redirect
from django.db import connection
from company.models import Company,User,CGroup
import json
import time 

from django.contrib.auth.models import Group

def rbac_menu_items(item,sys_menu,auth_menu_ids=[],only_authorized=False):    
    d=item
    children=[]   
    if only_authorized:
        for i in sys_menu:      #用户登录菜单
            if i['parent_id']==d['id'] and i['id'] in auth_menu_ids:            
                children.append(i) 
    else:
        if auth_menu_ids:       #功能组别菜单
            for i in sys_menu:                
                if i['parent_id']==d['id']:
                    show=False
                    if i['id'] in auth_menu_ids:
                        show=True
                    i['show']=show
                    children.append(i) 
        else:
            for i in sys_menu:  #所有企业菜单
                if i['parent_id']==d['id']:            
                    children.append(i) 
    if children:
        d['children']=[rbac_menu_items(child,sys_menu,auth_menu_ids,only_authorized) for child in children]  
    return d 


def rbac_sys_menu(sys_menu,auth_menu_ids=[],only_authorized=False):
    menu_items=[]  
    sys_menu.sort(key=lambda x:x["priority"])
    
    if only_authorized:             #用户登录菜单
        for i in sys_menu:        
            if i['level']==1 and i['id'] in auth_menu_ids:          
                menu_items.append(rbac_menu_items(i,sys_menu,auth_menu_ids,only_authorized))  
    else:    
        if auth_menu_ids:   #功能组别菜单 
            for i in sys_menu:   
                if i['level']==1:                                   
                    show=False
                    if i['id'] in auth_menu_ids:
                        show=True
                    i['show']=show 
                    menu_items.append(rbac_menu_items(i,sys_menu,auth_menu_ids,only_authorized)) 
        else:               #所有企业菜单
            for i in sys_menu:   
                if i['level']==1:  
                    menu_items.append(rbac_menu_items(i,sys_menu,auth_menu_ids,only_authorized))  
    return menu_items

'''
def generate_menu(menu,parent_id,sys_menu,auth_menu_ids=[],only_authorized=False):     
    for i in sys_menu:    
        if i['parent_id']==parent_id:
            d=i 
            children=[]            
            if only_authorized:         #用户登录菜单
                for k in sys_menu:      
                    if k['parent_id']==d['id'] and k['id'] in auth_menu_ids:            
                        children.append(k) 
            else:                       
                if auth_menu_ids:       #功能组别菜单       
                    for k in sys_menu:                
                        if k['parent_id']==d['id']:
                            show=False
                            if k['id'] in auth_menu_ids:
                                show=True
                            k['show']=show
                            children.append(k) 
                else:                   #所有企业菜单
                    for k in sys_menu:  
                        if k['parent_id']==d['id']:            
                            children.append(k) 
            #if children:
            #    d['children']=generate_menu(menu,d['id'],sys_menu,auth_menu_ids,only_authorized)   
            #    #[rbac_menu_items(child,sys_menu,auth_menu_ids,only_authorized) for child in children] 
            d['children']=children
            for child in children:
                generate_menu(menu,child['id'],sys_menu,auth_menu_ids,only_authorized)
            
            menu.append(d) 
'''


class RbacMenu(object):
    def __init__(self,company=None,cgroup=None,user=None): 
        self.only_authorized=False        
        self.sys_menu_itmes=[]
        self.auth_menu_ids=[]       
        if user:
            self.only_authorized=True 
        cur=connection.cursor()
        sWhere=''
        if company:
            sWhere=" where case when jsonb_array_length(companys_only)=0 then true "+\
                "else companys_only@>'[{\"id\":\""+str(company.id)+"\"}]'::jsonb end"   
        elif cgroup:
            sWhere=" where case when jsonb_array_length(companys_only)=0 then true "+\
                "else companys_only@>'[{\"id\":\""+str(cgroup.company.id)+"\"}]'::jsonb end" 
        elif user:
            sWhere=" where case when jsonb_array_length(companys_only)=0 then true "+\
                "else companys_only@>'[{\"id\":\""+str(user.company.id)+"\"}]'::jsonb end" 
        s="select id,title,level,coalesce(icon,''),coalesce(url,''),coalesce(parent_id,0),coalesce(priority,0),coalesce(remark,'') "+\
            "from rbac_menu"+sWhere+" order by priority,id "
        cur.execute(s)
        for r in cur.fetchall():
            self.sys_menu_itmes.append({'id':r[0],'title':r[1],'level':r[2],'icon':r[3],'url':r[4],'parent_id':r[5],'priority':r[6],'remark':r[7]})        
        if user or cgroup:
            if user:
                s="select array_to_string(array(select json_array_elements_text(menus::json) menu_id FROM rbac_cgroupmenu "+\
                    "where (select company_id from company_cgroup where id=cgroup_id)="+str(user.ancestor_id)+\
	                " and  cgroup_id in ("+\
		            "select id from company_cgroup where group_id in (select group_id FROM company_user_groups where user_id="+str(user.id)+")"+\
	                ") group by menu_id),',')"
            else:
                s="select array_to_string(array(select json_array_elements_text(menus::json) FROM rbac_cgroupmenu "+\
                    "where cgroup_id="+str(cgroup.id)+"),',')"   
            cur.execute(s)
            r=cur.fetchone()        
            if r[0]:
                self.auth_menu_ids=json.loads("["+r[0]+"]") 
            else:
                self.auth_menu_ids=[0]
        cur.close()
    def get_menu(self):
        return rbac_sys_menu(self.sys_menu_itmes,self.auth_menu_ids,self.only_authorized)
        

 
@login_required
def list_menu(request,what):
    data={'e':'','data':[],'clmns':[]}
    u=request.user
    if u.id!=3506: #sys_admin
        data['e']
        return JsonResponse(data)
    if what=='menu':  
        m=RbacMenu()
        data=m.get_menu()
        return render(request,'rbac/list_menu.html', {'menuitems':data}) 
    return JsonResponse(data)


@login_required
def edit_menu(request,id=None):
    if id:
        obj=Menu.objects.get(id=int(id))
    else:
        obj=Menu()
    pid=request.GET.get('parent_id','')
    if pid:
        obj.parent_id=int(pid)
    is_saved=False
    if request.method == 'GET':           
        form = MenuForm(instance=obj)     
        companys=[]
        for c in Company.objects.filter(level_id=1).order_by('name'):
            companys.append([c.id,c.name])
    else:          
        delete=request.POST.get('delete','false')
        if delete=='true':   
            t=obj.title
            obj.delete()
            return  JsonResponse({'msg':t+'已删除'})

        form = MenuForm(request.POST, instance=obj)       
        if form.is_valid():            
            form.save()         
            is_saved=True
        return  redirect("/rbac/list/menu/")   

    return render(request, 'rbac/menu.html', {'form': form, 'is_saved':is_saved,'companys':companys})          



@login_required
def sync_groupmenu(request):
    data={'e':''}
    u=request.user
    if u.id!=3506: #sys_admin
        dat['e']='not authorized this operation'
        return JsonResponse(data)
    return JsonResponse(data)
    

@login_required
def rbac_action(request,what):
    data={'e':''}
    u=request.user    
    if what=='init_groupmenu':
        if u.id!=3506: #sys_admin
            data['e']='not authorized this operation'
            return JsonResponse(data)
        company_id=request.GET.get('company_id',None)
        return JsonResponse( init_groupmenu(company_id))
    elif what=='user_menu':
        u=User.objects.get(id=2)       
        m=RbacMenu(u.company,u)
        data=m.get_menu()    
        return JsonResponse(data,safe=False)
    elif what=='add_group':
        if request.method=='GET':
            cs=[]
            for c in Company.objects.filter(level_id=1).order_by('name'):
                cs.append([c.id,c.name])
            return render(request,'company/add_group.html',{'companys':cs})
        else:
            data={'e':''}
            r=json.loads(request.body)  
            name=r['name']
            company_ids=r['company_ids']
            remark=None
            if 'remark' in r:
                remark=r['remark']
            gs=Group.objects.filter(name=name)
            if gs:
                data['e']='功能组别 '+name+' 已存在'
                return JsonResponse(data)
            a=company_ids.split(',')
            if not a:
                data['e']='企业ID不能为空'
                return JsonResponse(data)
            g=Group(name=name)
            g.save()        
            for i in a:
                cg=CGroup(group_id=g.id,company_id=int(i),name=name,remark=remark)
                cg.save()
            return JsonResponse(data)
    elif what=='edit_companymenu':
        company_id=request.GET.get('company_id','')
        data={'e':'','sys_menu':[],'company_menu':[]}
        if company_id:
            sm=RbacMenu()
            data['sys_menu']=sm.get_menu()
            cm=CompanyMenu        
        else:
            data['e']='company id missing'

        return render(request,'rbac/company_menu.html',{})
