'''
@Author: hua
@Date: 2019-05-05 09:02:32
@LastEditors: hua
@LastEditTime: 2019-05-14 09:18:35
'''
from aiohttp import web
from app import dBSession
from app.Model.Admin import Admin
from app.Model.AdminRole import AdminRole
from app.Service.AdminService import AdminService
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/admin/index.html')
async def index(request, **k):
    params = request.query
    data = dict()
    if 'keyword' in params.keys():
       filters = {Admin.name.like('%'+params['keyword']+'%')}
       res = Admin().getList(filters, Admin.id.desc(), ())
    else:
       res = Admin().getList({}, Admin.id.desc(), ())
    data['page'] = res['page']
    data['list'] = res['list']
    return data 

#添加
@aiohttp_jinja2.template('fladmin/admin/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 = AdminService().add(request, params)   
    return res
          
#添加
@aiohttp_jinja2.template('fladmin/admin/add.html')
async def addByGet(request, **k):
    params = request.query
    data = dict()
    data['rolelist'] = AdminRole().getAll({}, AdminRole.id.asc())
    return data
    
#修改
@aiohttp_jinja2.template('fladmin/admin/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 = {
        Admin.id == params['id']
    }  
    res = AdminService().edit(request, params, filters)
    return res
        
#修改
@aiohttp_jinja2.template('fladmin/admin/edit.html')
async def editByGet(request, **k):
    params = request.query
    data = dict()
    filters = {
        Admin.id == params['id']
    }
    data['id'] = params['id'] 
    data['post'] =  Admin().getOne(filters, Admin.id.desc())
    data['rolelist'] = AdminRole().getAll({}, AdminRole.id.asc())
    return data

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