from aiohttp import web
from app import dBSession
from app.Model.AdminRole import AdminRole
from app.Model.Access import Access
from app.Model.Menu import Menu
from app.Vendor.Decorator import validator
from app.Vendor.tempDef import sysconfig, backStatus, randomInt
from  sqlalchemy.sql.expression import func
from app.Vendor.Code import Code
import aiohttp_jinja2
import time, json


#列表
@aiohttp_jinja2.template('fladmin/adminrole/index.html')
async def index(request, **k):
    params = request.query
    data = dict()
    if 'keyword' in params.keys():
       filters = {AdminRole.name.like('%'+params['keyword']+'%')}
       res = AdminRole().getList(filters, AdminRole.id.desc(), ())
    else:
       res = AdminRole().getList({}, AdminRole.id.desc(), ())
    data['page'] = res['page']
    data['list'] = res['list']
    return data 

#添加
@aiohttp_jinja2.template('fladmin/adminrole/add.html')
async def addByPost(request, **k):
    params = dict()
    if  request.content_type == 'application/json':
        reqMultiDictValue = json.loads(str(await request.content.read(), encoding="utf-8"))
    elif request.content_type == 'application/x-www-form-urlencoded' or request.content_type == 'multipart/form-data':
        reqMultiDictValue = await  request.post()
    for k,v in reqMultiDictValue.items():
        params[k] = v
    res = AdminRole().add(params)   
    if res:
        return backStatus(request, '添加成功')
    return backStatus(request, '添加失败', 0)
          
#添加
@aiohttp_jinja2.template('fladmin/adminrole/add.html')
async def addByGet(request, **k):
    return {}
    
#修改
@aiohttp_jinja2.template('fladmin/adminrole/edit.html')
async def editByPost(request, **k):
    params = dict()
    if  request.content_type == 'application/json':
        reqMultiDictValue = json.loads(str(await request.content.read(), encoding="utf-8"))
    elif request.content_type == 'application/x-www-form-urlencoded' or request.content_type == 'multipart/form-data':
        reqMultiDictValue = await  request.post()
    for k,v in reqMultiDictValue.items():
        params[k] = v
    filters = {
        AdminRole.id == params['id']
    }  
    res = AdminRole().edit(params, filters)
    if res==True:
        return backStatus(request, '编辑成功')
    return backStatus(request, '编辑失败', 0)
        
#修改
@aiohttp_jinja2.template('fladmin/adminrole/edit.html')
async def editByGet(request, **k):
    params = request.query
    data = dict()
    filters = {
        AdminRole.id == params['id']
    }
    data['id'] = params['id'] 
    data['post'] =  AdminRole().getOne(filters, AdminRole.id.desc())
    return data

#删除
async def delete(request, **k):
    params = request.query
    filters = {
        AdminRole.id == params['id']
    }
    res = AdminRole().delete(filters)
    if res==True:
        #删除权限
        filters = {
            Access.id == params['id']
        }
        Access().delete(filters)
        return backStatus(request, '删除成功') 
    return backStatus(request, '删除失败', 0)

#角色权限设置视图
@aiohttp_jinja2.template('fladmin/adminrole/permissions.html')
async def permissions(request, **k):
    params = request.query
    data = dict()
    menu = []
    if 'id' not in params.keys():
        return backStatus(request, '您访问的页面不存在或已被删除', 0)
    role_id  = params['id']
    filters = {
        Access.role_id == role_id
    }
    access = Access().getAll(filters, Access.id.desc())
    if access:
        for k, v in enumerate(access):
            menu.append(v['menu_id'])
    menus = Menu().category_tree(Menu().get_category(),0)
    if menus:
        for k, v in enumerate(menus):
            menus[k]['is_access'] = 0
            if menu and v['id'] in menu:
                menus[k]['is_access'] = 1
    data['menus'] = menus
    data['role_id'] = role_id
    return data
	
#角色权限设置
async def dopermissions(request, **k):
    params = dict()
    params['menuid'] = []
    if  request.content_type == 'application/json':
        reqMultiDictValue = json.loads(str(await request.content.read(), encoding="utf-8"))
    elif request.content_type == 'application/x-www-form-urlencoded' or request.content_type == 'multipart/form-data':
        reqMultiDictValue = await  request.post()
    for k,v in reqMultiDictValue.items():
        if k == 'menuid[]':
            params['menuid'].append(v)
        else:   
            params[k] = v
    menus = []

    if params['menuid'] and params['role_id']:
        for row in params['menuid']:      
            menus.append({
                'role_id': params['role_id'],
                'menu_id': row
            })
    if len(menus) == 0:
        return backStatus(request, '操作失败', 0)
    #先删除权限
    Access().delete({Access.role_id == params['role_id']})
    #添加权限
    for menu in menus:
        res = Access().add(menu)
        if res == False:
            return backStatus(request, '添加失败', 0)
    return backStatus(request, '添加成功') 
