'''
@Author: hua
@Date: 2019-04-14 14:06:14
@description: 
@LastEditors: hua
@LastEditTime: 2020-05-23 19:37:02
'''
from app.Model.Article import Article
from app.Vendor.Decorator import validator
from app.Vendor.ReturnData import ReturnData
from sqlalchemy.sql.expression import func

#列表，params禁止使用函数
@validator(name="limit", rules={'required': True,'type': 'string'}, msg= {'required': u'限定是必须的','type': u'限定必须是字符串'}, default=10)
@validator(name="tuijian", rules={'required': True}, msg= {'required': u'推荐是必须的'}, default=0)
@validator(name="orderby", rules={'required': True,'type': 'string',}, msg= {'required': u'排序是必须的','type': u'排序是字符串'})
async def index(request, **k):
    params = k['params']
    filters = {
        Article.tuijian == params['tuijian'],
        Article.delete_time == 0,
        Article.status == 0
    }
    if 'type_id' in params.keys():
       filters.add(Article.type_id == params['type_id'])
    if 'keyword' in params.keys():
        filters.add(Article.keywords.like('%'+params['keyword']+'%'))
    if 'rand' == params['orderby']:
        orderby =  func.rand()
    else:
        orderby = params['orderby'] 
    res = Article().getList(filters, orderby, (), 0, params['limit'])
    return await ReturnData.success(request, res)