from aiohttp import web
from app.Model.Article import Article
from app.Model.Tag import Tag
from app.Model.Taglist import Taglist
from app.Service.ArticleService import ArticleService
from app.Service.TaglistService import TaglistService
from  sqlalchemy.sql.expression import func
import aiohttp_jinja2
import time

@aiohttp_jinja2.template('index/tag/detail.html')
async def detail(request, **k):
    id = int(request.match_info['id'])
    data = dict()
    filters = {
        Taglist.tag_id == id
    }
    post = Tag().getOne(filters, Tag.add_time.desc())
    data['post'] = post
    pagesize = 11
    offset = 0
    filters.add(Article.delete_time == 0)
    filters.add(Article.status == 0)
    res = TaglistService().getJoinList(filters, Article.update_time.desc(), (), offset, pagesize)
    data['list'] = res['list']
    totalpage = int(res['count']/pagesize)
    data['totalpage'] = totalpage
    #最新文章
    filters = {
        Article.delete_time == 0,
        Article.status      == 0
    }
    relate_zuixin_list = Article().getAll(filters, Article.update_time.desc(), (), 5)
    data['relate_zuixin_list'] = relate_zuixin_list

    #随机文章
    filters = {
        Article.delete_time == 0,
        Article.status      == 0
    }
    relate_rand_list = Article().getAll(filters, func.rand(), (), 5)
    data['relate_rand_list'] = relate_rand_list
    #标签
    filters = {
        Tag.status      == 0
    }
    tag_list = Tag().getAll(filters, Tag.id.desc(), (), 10)
    data['tag_list'] = tag_list

    return data