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

@aiohttp_jinja2.template('index/article/index.html')
@validator(name="page", rules={'type': 'string'}, msg= {'type': u'页号必须是字符串'}, default="1")
async def index(request, **k):
    data = dict()
    filters = set()
    title = ''
    offset = int(k['params']['page'])
    key = request.match_info['key']
    if key != None:
        arr_key = ArticleService().getArrByString(key)
    #分类id
    if 'f' in arr_key.keys() and int(arr_key['f']) > 0:
        type_id = arr_key['f']
        filters.add(Article.type_id == type_id)
        post = ArticleType().getOne({ArticleType.id == arr_key['f']}, ArticleType.add_time.desc())
        title = post['name']+'-'+sysconfig('CMS_WEBNAME')
        if post['seotitle']:
            title = post['seotitle']
        data['post'] = post
        #面包屑导航
        data['bread'] = ArticleService().get_article_type_path(type_id)

   
    filters.add(Article.status == 0)
    filters.add(Article.delete_time == 0)
    filters.add(Article.add_time < time.time())
    res = Article().getList(filters, Article.id.desc(), (), offset, 11)

    data['page'] = res['page']
    data['list'] = res['list']

    #推荐文章
    filters = {
        Article.status == 0,
        Article.delete_time == 0,
        Article.tuijian == 1,
        Article.add_time < time.time(),
    }
    relate_tuijian_list = Article().getAll(filters, Article.update_time.desc(), ('id','content','title',))
    data['relate_tuijian_list'] = relate_tuijian_list
    #随机文章
    filters = {
        Article.status == 0,
        Article.delete_time == 0,
        Article.add_time < time.time(),
    }
    relate_rand_list =  Article().getList(filters, func.rand(),(), 0, 5)
    data['relate_rand_list'] = relate_rand_list['list']
    #seo标题设置
    data['title'] =title
    return data

@aiohttp_jinja2.template('index/article/detail.html')
async def detail(request, **k):
    id = int(request.match_info['id'])
    data = dict()
    filters = {
        Article.id == id
    }
    post = Article().getOne(filters, Article.add_time.desc())
    data['post'] = post
    #$post['content'] = $this->getLogic()->replaceKeyword($post['content']);
    #最新文章
    filters = {
        Article.delete_time == 0,
        Article.status      == 0,
        Article.type_id     == post['type_id'],
        Article.id          < id-1,
    }
    relate_zuixin_list = Article().getAll(filters, Article.update_time.desc(), (), 5)
    if len(relate_zuixin_list) == 0:
        filters = {
            Article.delete_time == 0,
            Article.status      == 0,
            Article.type_id     == post['type_id']
        }
        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,
        Article.type_id     == post['type_id'],
        Article.add_time    < time.time()
    }
    relate_rand_list = Article().getAll(filters, func.rand(), (), 5)
    data['relate_rand_list'] = relate_rand_list
    #面包屑导航
    data['bread'] = ArticleService().get_article_type_path(post['type_id'])
    res = getPreviousNextArticle({'article_id':id})
    data['previous_article'] = res['previous_article']
    data['next_article'] = res['next_article']
    return data



"""
    获取文章上一篇，下一篇
    @param int param['article_id'] 当前文章id
    @return dict
"""
def getPreviousNextArticle(param):
    res = dict()
    post = dict()
    res['previous_article'] = []
    res['next_article'] = []
    fitlers = {
        Article.id == param['article_id']
    }
    post = Article().getOne(fitlers, Article.add_time.desc(),())
    if not post:
        return res
    res['previous_article'] = Article().getOne({Article.id < param['article_id'],Article.type_id == post['type_id']}, Article.id.desc(), ())
    filters = {
        Article.type_id == post['type_id'],
        Article.id > param['article_id']
    }
    res['next_article'] = Article().getOne(filters, Article.id.desc(), ())
    return res
