'''
@Author: hua
@Date: 2019-05-05 20:03:47
@LastEditors: hua
@LastEditTime: 2019-05-14 14:58:55
'''
from aiohttp import web
from app.Model.Tag import Tag
from app.Model.Taglist import Taglist
from app.Vendor.Decorator import validator
from app.Vendor.tempDef import sysconfig, backStatus, randomInt
from  sqlalchemy.sql.expression import func
from app.Vendor.Code import Code
import aiohttp_jinja2
import time, jieba, json,re

#列表
@aiohttp_jinja2.template('fladmin/tag/index.html')
async def index(request, **k):
    params = request.query
    data = dict()
    if 'keyword' in params.keys():
       filters = {Tag.name.like('%'+params['keyword']+'%')}
       res = Tag().getList(filters, Tag.id.desc(), ())
    else:
       res = Tag().getList({}, Tag.id.desc(), ())
    data['page'] = res['page']
    data['list'] = res['list']
    return data 
	
#添加
@aiohttp_jinja2.template('fladmin/tag/add.html')
async def addByPost(request, **k):
    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
    
    params['update_time'] = time.time()
    params['add_time'] = params['update_time'] 
    params['click'] = randomInt(500)#点击
    res = Tag().add(params)   
    if res==True:
        #添加Tag下的文章
        tagarc=""
        if params["tagarc"]:
            tagarc = params["tagarc"].replace("，",",")
            patt = re.compile(r'^\d*$')
            if patt.match(tagarc) == None:
                tagarc="";#Tag文章列表
        if tagarc!="":
            arr=tagarc.split(',')
            data2 = dict()
            for row in arr:
                data2['tag_id'] = res['data']
                data2['article_id'] = row
                Taglist().add(data2)
            return backStatus(request, '添加成功')
    return backStatus(request, '添加失败', 0)
     
         
#添加
@aiohttp_jinja2.template('fladmin/tag/add.html')
async def addByGet(request, **k):
    return {}
    
#修改
@aiohttp_jinja2.template('fladmin/tag/edit.html')
async def editByPost(request, **k):
    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
    filters = {
        Tag.id == params['id']
    }
    filters2 = {
        Taglist.tag_id == params['id']
    }
    params['update_time'] = time.time()
    
    tagarc=""
    if params["tagarc"]:
        tagarc = params["tagarc"].replace("，",",")
        ''' patt = re.compile(r'^\d*$')
        if patt.match(tagarc) == None:
            tagarc="";#Tag文章列表 '''
        params.pop("tagarc")
    res = Tag().edit(params, filters)
    if res == True:
        #获取该标签下的文章id
        posts = Taglist().getAll(filters2, Taglist.article_id.desc())
        article_id_list = ""
        if posts:
            for row in posts:
                article_id_list = article_id_list+','+str(row['article_id'])  
        article_id_list = article_id_list.strip(",")
        if tagarc!="" and  tagarc!=article_id_list:
            Taglist().delete(filters2)
            arr=tagarc.split(',')
            data2 = dict()
            for row in arr:
                data2['tag_id'] = params['id']
                data2['article_id'] = row
                Taglist().add(data2)
        
        elif tagarc=="":
            Taglist().delete(filters2) 
        return backStatus(request, '编辑成功')
    return backStatus(request, '编辑失败', 0)
    
    

@aiohttp_jinja2.template('fladmin/tag/edit.html')
async def editByGet(request, **k):
    params = request.query
    data = dict()
    filters = {
        Tag.id == params['id']
    }
    data['id'] = params['id']
   
    data['post'] = Tag().getOne(filters, Tag.id.desc())
    filters = {
        Taglist.tag_id == params['id']
    }
    #获取该标签下的文章id
    posts = Taglist().getAll(filters, Taglist.article_id.desc())
    article_id_list = ""
    if posts:
        for row in posts:
            article_id_list=article_id_list+','+str(row['article_id'])
    data['article_id_list'] = article_id_list.strip(",")
    return data

	
#删除
async def delete(request, **k):
    params = request.query
    filters = {
        Tag.id == params['id']
    }
    res = Tag().delete(filters)
    if res==True:
        return backStatus(request, '删除成功') 
    return backStatus(request, '删除失败', 0)