'''
@Author: hua
@Date: 2019-04-17 10:04:38
@LastEditors: hua
@LastEditTime: 2019-05-14 08:54:18
'''
from aiohttp import web
from aiohttp_session import get_session, new_session
from app.Vendor.Captcha import validate_picture
from app.Vendor.ReturnData import ReturnData
from app.Vendor.Decorator import validator
from app.Service.AdminService import AdminService
from app import cache
from app.Vendor.Code import Code 
from app.Vendor.tempDef import backStatus
import aiohttp_jinja2
from io import BytesIO

@aiohttp_jinja2.template('fladmin/login/index.html')
async def index(request, **k):
    session = await get_session(request)
    url = request.scheme+'://'+ request.host
    if 'admin_info' in session.keys():
        return web.Response(status=302, headers={'Location':url+'/fladmin/index/index'})
    return {}
    

""" 登陆处理页面 """
@validator(name="name", rules={'required': True,'type': 'string'}, msg= {'required': u'账户是必须的','type': u'账户必须是字符串'})
@validator(name="pwd", rules={'required': True,'type': 'string'}, msg= {'required': u'密码是必须的','type': u'密码必须是字符串'})
@validator(name="captcha", rules={'required': True,'type': 'string'}, msg= {'required': u'验证码是必须的','type': u'验证码必须是字符串'})
async def dologin(request, **k):
    # 将验证码字符串储存在session中
    params = k['params']
    if cache.get('image') is None:
        return backStatus(request,  '验证码错误', 0)
    if params['captcha'].lower() != cache.get('image').lower():
        return backStatus(request,  '验证码错误')#await ReturnData().error(request, '验证码错误')
    res = AdminService().login(params)
    if res['code'] == Code.SUCCESS:
        session = await new_session(request)
        session['admin_info'] = res['data']
        url = request.scheme+'://'+ request.host
        return  web.Response(status=302, headers={'Location':url+'/fladmin/index/index'})
    return backStatus(request, '账户不存在', 0)


""" 获取验证码 """
async def getCode(request):
    image, data = validate_picture()
    # 将验证码图片以二进制形式写入在内存中，防止将图片都放在文件夹中，占用大量磁盘
    buf = BytesIO()
    image.save(buf, 'jpeg')
    # 将验证码字符串储存在session中
    cache.set('image', data)
    # 把二进制作为response发回前端，并设置首部字段
    headers = dict()
    headers['Content-Type'] = 'image/gif'
    return web.Response(status=200, headers=headers, body=buf.getvalue())


""" 退出登录 """
async def loginout(request):
    session = await get_session(request)
    if not session.new:
        session.invalidate()
    url = request.scheme+'://'+ request.host
    return web.Response(status=302, headers={'Location':url+'/fladmin/Login'})


