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 


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]    
    else:
        d['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


class RbacMenu(object):
    def __init__(self,company=None,cgroup=None,user=None,bootstraptreeview=False): 
        self.only_authorized=False        
        self.sys_menu_itmes=[]
        self.auth_menu_ids=[]
        self.bootstraptreeview=bootstraptreeview
        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
        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=cgroups_id)="+str(user.ancestor_id)+\
	                " and  cgroups_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 cgroups_id="+str(cgroup.id)+"),',')"  
            cur.execute(s)
            r=cur.fetchone()        
            if r[0]:
                self.auth_menu_ids=json.loads("["+r[0]+"]")   
        cur.close()

    def get_menu(self):
        return rbac_sys_menu(self.sys_menu_itmes,self.auth_menu_ids,self.only_authorized,self.bootstraptreeview)

 
@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)


