from aiohttp import web
from app.Model.Article import Article
from app.Model.Friendlink import Friendlink
from app.Model.Slide import Slide
from app.Model.Tag import Tag
from app.Vendor.Decorator import validator
from  sqlalchemy.sql.expression import func
import aiohttp_jinja2
import time

@aiohttp_jinja2.template('index/index/index.html')
#@validator(name="email", rules={'required': True,'type': 'string','minlength': 10,'maxlength': 20}, msg= {'required': u'邮箱是必须的','type': u'邮箱必须是字符串','minlength': u'邮箱必须大于10','maxlength': u'邮箱必须小于20'})
async def index(request, **k):
    data = dict()
    pagesize = 5
    offset = 0
    filters = {
        Article.status == 0,
        Article.delete_time == 0,
        Article.add_time < time.time(),
    }
    res = Article().getList(filters, Article.id.desc(), (), offset, pagesize)
    #查询文章列表
    data['list'] = res['list']
    totalpage = int(res['page']['count']/pagesize)
    data['totalpage'] = totalpage
    #推荐文章
    filters = {
        Article.status == 0,
        Article.delete_time == 0,
        Article.tuijian == 1,
        Article.add_time < time.time(),
    }
    relate_tuijian_list = Article().getList(filters, Article.update_time.desc(), ('id','content','title',), offset, pagesize)
    data['relate_tuijian_list'] = relate_tuijian_list['list']
    #随机文章
    filters = {
        Article.status == 0,
        Article.delete_time == 0,
        Article.add_time < time.time(),
    }
    relate_rand_list =  Article().getList(filters, func.rand(),(), offset, pagesize)
    data['relate_rand_list'] = relate_rand_list['list']
    #标签
    filters = {
         Tag.status == 0
    }
    relate_tag_list = Tag().getList(filters, Tag.id.desc(), (), offset, pagesize)
    data['relate_tag_list'] = relate_tag_list['list']
    #友情链接
    friendlink_list = Friendlink().getAll({}, Friendlink.id.desc(), (), 5);  
    data['friendlink_list'] = friendlink_list
    #轮播图
    filters = {
         Slide.status == 0
    }
    slide_list = Slide().getAll(filters, Slide.id.desc(), (), 5)
    data['slide_list'] = slide_list
    return data

#XML地图
@aiohttp_jinja2.template('index/index/sitemap.html')
async def sitemap(request, **k):
    data = dict()
    #最新文章
    filters = {
        Article.delete_time == 0,
        Article.status      == 0,
        Article.add_time    < time.time()
    }
    dataList = Article().getAll(filters, Article.update_time.desc(), (), 100)
    data['list'] = dataList
    return data
