from aiohttp import web
from aiohttp_session import get_session
from app import dBSession
from app.Model.Article import Article
from app.Model.ArticleType import ArticleType
from app.Model.Taglist import Taglist
from app.Model.Tag import Tag
from app.Service.ArticleService import ArticleService
from app.Vendor.Decorator import validator
from app.Vendor.tempDef import sysconfig, backStatus
from  sqlalchemy.sql.expression import func
from app.Vendor.Code import Code
import aiohttp_jinja2
import time, jieba, json



@aiohttp_jinja2.template('fladmin/article/index.html')
@validator(name="page", rules={'type': 'string'}, msg= {'type': u'页码是字符串'}, default='0')
@validator(name="keyword", rules={'type': 'string'}, msg= {'type': u'关键字是字符串'}, default='')
@validator(name="type_id", rules={'type': 'string'}, msg= {'type': u'类型是字符串'}, default='')
async def index(request, **k):
    """ 暂时不写接收参数 """
    params = k['params']
    data = dict()
    filters = {Article.status == 0}
    if 'page' in params.keys():
        page = int(params['page'])
    if params['keyword'] != '':
       filters.add(Article.title.like('%'+params['keyword']+'%'))
    if params['type_id'] != '':
       filters.add(Article.type_id == params['type_id'])
    res = Article().getList(filters, Article.id.desc(), (), page)

    data['page'] = res['page']
    data['list'] = res['list']
    #分类列表
    article_type_list = ArticleType().tree_to_list(ArticleType().list_to_tree(), parent_id=0, temp=[])
    data['article_type_list'] = article_type_list
    return data

@aiohttp_jinja2.template('fladmin/article/add.html')
async def addByPost(request):
    params = dict()
    if  request.content_type == 'application/json':
        reqMultiDictValue = json.loads(str(await request.content.read(), encoding="utf-8"))
    elif request.content_type == 'application/x-www-form-urlencoded' or request.content_type == 'multipart/form-data':
        reqMultiDictValue = await  request.post()
    for k,v in reqMultiDictValue.items():
        params[k] = v
    if  params['litpic'].strip() !='':
        if params["description"].strip() =='':
            if  params['content'].strip() !='':
                params['description']= params["content"][1:20]#description
    if  params['update_time'].strip() !='':
        timeArray = time.strptime(params['update_time'], "%Y-%m-%d %H:%M:%S")
        params['update_time'] = int(time.mktime(timeArray))
    else:
        params['update_time'] = time.time()
    params['add_time'] = params['update_time']
    session = await get_session(request)
    params['user_id'] = session['admin_info']['id'] # 发布者id
    #关键词
    if params["keywords"].strip() !='':
        params['keywords'] = params['keywords'].replace("，",",")
    else:
        if  params["title"].strip() !='':

            title=params["title"]
            title=title.replace("，","")
            params['title']=title.replace(",","")
            params['keywords']=  ",".join(jieba.lcut(params['title'], cut_all=True)) #标题分词
    """ if(isset($_POST["dellink"]) && $_POST["dellink"]==1 && !empty($content)){
        $content=logic('Article')->replacelinks($content,array(sysconfig('CMS_BASEHOST')));
    } //删除非站内链接 """
    
    #提取第一个图片为缩略图
    """ if 'autolitpic' in params.keys() and 'litpic' not in params.keys():
        litpic = Article().getBodyFirstPic(content) """
    params.pop('autolitpic')
    params.pop('editorValue')
    tags = params.pop('tags')
    res = Article().add(params)
    if res==True:
        #Tag添加
        if tags.strip() !='':
            data2 = dict()
            tags = ','.split(tags.replace('，',','))
            for row in tags:       
                tagVal = Tag().getOne({Tag.name == row}, Tag.add_time.desc())
                if tagVal is None:
                    break
                else:  
                    tag_id = tagVal['id']
                if  tag_id:
                    data2['tag_id'] = tag_id
                    data2['article_id'] = id
                    Taglist().add(data2)
        return backStatus(request, '创建成功')
    return backStatus(request, '创建失败', 0)

@aiohttp_jinja2.template('fladmin/article/add.html')
async def addByGet(request):
    #type_id = request.match_info['type_id'].split('.')[0]
    data = dict()
    #data['type_id'] = type_id
    #分类列表
    article_type_list = ArticleType().tree_to_list(ArticleType().list_to_tree(), parent_id=0, temp=[])
    data['article_type_list'] = article_type_list
    return data

@aiohttp_jinja2.template('fladmin/article/edit.html')
async def editByPost(request):
        params = dict()
        if  request.content_type == 'application/json':
            reqMultiDictValue = json.loads(str(await request.content.read(), encoding="utf-8"))
        elif request.content_type == 'application/x-www-form-urlencoded' or request.content_type == 'multipart/form-data':
            reqMultiDictValue = await  request.post()
        for k,v in reqMultiDictValue.items():
            params[k] = v
        id=params['id']
     

        if params["description"].strip() =='':
            if  params['content'].strip() !='':
                params['description']= params["content"][1:20]#description
        if  params['update_time'].strip() !='':
            timeArray = time.strptime(params['update_time'].strip(' '), "%Y-%m-%d %H:%M:%S")
            params['update_time'] = int(time.mktime(timeArray))
        else:
            params['update_time'] = time.time()
        params['add_time'] = params['update_time']
        session = await get_session(request)
        params['user_id'] = session['admin_info']['id'] # 发布者id
        
        
        #关键词
        if params["keywords"].strip() !='':
            params['keywords'] = params['keywords'].replace("，",",")
        else:
            if  params["title"].strip() !='':
                title=params["title"]
                title=title.replace("，","")
                params['title']=title.replace(",","")
                params['keywords']=  ",".join(jieba.lcut(params['title'], cut_all=True)) #标题分词
        
        """ if(isset($_POST["dellink"]) && $_POST["dellink"]==1 && !empty($content)){$content=logic('Article')->replacelinks($content,array(sysconfig('CMS_BASEHOST')));} //删除非站内链接 """     
        #提取第一个图片为缩略图
        """ if(isset($_POST["autolitpic"]) && $_POST["autolitpic"] && empty($litpic))
        {
            $litpic = logic('Article')->getBodyFirstPic($content);
            if($litpic)
            {
                $_POST['litpic'] = $litpic;
            }
        } """
        params.pop('autolitpic')
        tags = params.pop('tags')
        res = Article().edit(params, {Article.id == id})
        if res==True:
            #Tag添加
            if tags.strip() !='':
                data2 = dict()
                tags = ','.split(tags.replace('，',','))
                for row in tags:       
                    tagVal = Tag().getOne({Tag.name == row}, Tag.add_time.desc())
                    if tagVal is None:
                        break
                    else:  
                        tag_id = tagVal['id']
                    if  tag_id:
                        data2['tag_id'] = tag_id
                        data2['article_id'] = id
                        Taglist().add(data2)
            return backStatus(request, '编辑成功')
        return backStatus(request, '编辑失败', 0)
    
@aiohttp_jinja2.template('fladmin/article/edit.html')
async def editByGet(request):
    params = request.query
    data = dict()
    if 'id' in params.keys():
        id = params['id']
    else:
        return backStatus(request, '参数错误') 
    filters = {
        Article.id == id
    }
    data['id'] = id
    post = Article().getOne(filters, Article.id.desc())
    data['post'] = post
    
    #Tag标签
    tags = ''
    filters = {
        Taglist.article_id == id
    }
    taglist = Taglist().getAll(filters, Taglist.id.desc())
    if taglist:
        tmp = []
        for k,y in taglist:
            filters = {
                Tag.id == v['tag_id']
            }
            tmp.append(Tag().getOne(filters)['name'])
        tags = ','.join(tmp) 
    data['tags'] = tags
    
    
    #栏目列表
    article_type_list = ArticleType().tree_to_list(ArticleType().list_to_tree(), parent_id=0, temp=[])
    data['article_type_list'] = article_type_list
    return data


#文章是否存在
@validator(name="title", rules={'type': 'string'}, msg= {'type': u'标题是字符串'})
@validator(name="id", rules={'type': 'string'}, msg= {'type': u'编号是字符串'})
async def articleexists(request, **k):
    params = k['params']
    filters = set()
    if  'title' in params.keys():
        filters.add(
            Article.title == params['title']
        )
    if 'id' in params.keys():
        filters.add(
            Article.id.in_(['NEQ', params['id']])
        )
    data = Article().getCount(filters)
    return web.json_response(data)

    
#删除
async def delete(request):
    params = request.query
    if 'id' in params.keys():
        id = params['id']
        if ',' in id:
            id = id.split(',')
    else:
        return backStatus(request, '参数错误') 
    if isinstance(id, list):
        res = Article().delete({Article.id.in_(id)})
    else:
        res = Article().delete({Article.id == id})
    if res:
        return backStatus(request, '删除成功')
    return backStatus(request, '删除失败', 0)

#文章推荐
async def recommendarc(request):
    params = request.query
    if 'id' in params.keys():
        id = params['id']
        if ',' in id:
            id = id.split(',')
    else:
        return backStatus(request, '参数错误') 
   
    data = {
        'tuijian': 1
    }
    res = Article().edit(data, {Article.id.in_(id)})
    if res:
        return backStatus(request,"推荐成功")
    return backStatus(request, '推荐失败！请重新提交', 0)


#文章重复列表
@aiohttp_jinja2.template('fladmin/article/repetarc.html')
async def repetarc(request):
    data = dict()
    sql_str = "select title,count(*) AS count from fl_article group by title HAVING count>1 order by count DESC"
    data_query = dBSession.execute(sql_str)
    data['list'] = data_query.fetchall()
    return data
    
    

	

        
    
    