from django.shortcuts import render, redirect
from django.http import HttpResponse, JsonResponse
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.core import serializers
from django.db.models import Q

import json
import markdown

from .models import ArticlePost, ArticleColumn
from .form import ArticlePostForm
from comment.models import Comment
from comment.forms import CommentPost


# 视图函数
def home(request):
    articles = ArticlePost.objects.all()[0:][:20]
    context = {'articles': articles}
    return render(request, 'article/home.html', context)


def article_list(request):
    search = request.GET.get('search')
    order = request.GET.get('order')
    tag = request.GET.get('tag')
    column = request.GET.get('column')
    articles = ArticlePost.objects.all()
    articles, search = get_articles_ordered(articles, order, search, column, tag)
    # 分页，暂时关闭
    # paginator = Paginator(article_list, 4)
    # page = request.GET.get('page')
    articles = articles[0:][:10]
    context = {'articles': articles, 'order': order, 'search': search, 'column': column, 'tag': tag, }
    return render(request, 'article/articles.html', context)


def get_articles_ordered(articles, order, search, column, tag):
    # 搜索查询集
    if search and search != 'None':
        articles = articles.filter(
            Q(title__icontains=search) |
            Q(body__icontains=search)
        )
    else:
        search = ''
    # 分类查询集
    if column is not None and column.isdigit():
        articles = articles.filter(column=column)
    # 标签查询集
    if tag and tag != 'None':
        articles = articles.filter(tags__name__in=[tag])
    # 排序
    if order == 'total_views':
        articles = articles.order_by('-total_views')
    return articles, search


def callajax(request):
    if request.method == 'POST':
        response_json = request.POST
        response_json = json.dumps(response_json)
        data = json.loads(response_json)
        counter = int(data['counter'])
        articles = ArticlePost.objects.all()
        if 'articles' in data['flag']:
            search = data['search']
            column = data['column']
            tag = data['tag']
            order = data['order']
            articles, search = get_articles_ordered(articles, order, search, column, tag)
        articles = articles[counter:][:10]
        if articles:
            context = {'articles': articles}
            if 'articles' in data['flag']:
                return render(request, 'article/order_call.html', context)
            else:
                return render(request, 'article/home_call.html', context)
        else:
            return HttpResponse('已经到底了')
    else:
        return HttpResponse('What?')


def article_detail(request, id):
    articles = ArticlePost.objects.get(id=id)
    comments = Comment.objects.filter(article=id)
    articles.total_views += 1
    articles.save(update_fields=['total_views'])
    md = markdown.Markdown(
        extensions=[
            'markdown.extensions.extra',
            'markdown.extensions.codehilite',
            'markdown.extensions.toc'
        ])
    articles.body = md.convert(articles.body)
    comment_form = CommentPost()
    toc_flag = True
    if 'li' not in md.toc:
        toc_flag = False
    context = {'article': articles, 'toc': md.toc, 'comments': comments, 'comment_form': comment_form,
               'toc_flag': toc_flag}
    return render(request, 'article/detail.html', context)


@login_required(login_url='/user/login/')
def article_create(request):
    if request.method == 'POST':
        article_post_form = ArticlePostForm(request.POST, request.FILES)
        # 判断提交的数据是否满足模型要求
        if article_post_form.is_valid():
            # 保存数据，但是暂时不提交到数据库中
            new_article = article_post_form.save(commit=False)
            new_article.author = User.objects.get(id=request.user.id)
            if request.POST['column'] != 'none':
                new_article.column = ArticleColumn.objects.get(id=request.POST['column'])
            # 将新文章保存到数据库中
            new_article.save()
            article_post_form.save_m2m()
            return redirect("article:article_list")
        # 如果数据不合法，返回错误信息
        else:
            return HttpResponse("表单有错误，请重新填写")
    # 如果用户请求获取数据
    else:
        # 创建表单类实例
        article_post_form = ArticlePostForm()
        columns = ArticleColumn.objects.all()
        context = {'article_post_form': article_post_form, 'columns': columns}
        # 返回模板
        return render(request, 'article/create.html', context)


def article_delete(request, id):
    article = ArticlePost.objects.get(id=id)
    article.delete()
    return redirect("article:article_list")


@login_required(login_url='/user/login/')
def article_safe_delete(request, id):
    if request.method == 'POST':
        article = ArticlePost.objects.get(id=id)
        if article.author == User.objects.get(id=request.user.id):
            article.delete()
            return redirect("article:article_list")
        else:
            return HttpResponse("你无权限进行此操作")
    else:
        return HttpResponse("仅允许POST请求")


@login_required(login_url='/user/login/')
def article_update(request, id):
    article = ArticlePost.objects.get(id=id)
    if article.author == User.objects.get(id=request.user.id):
        if request.method == 'POST':
            article_post_form = ArticlePostForm(data=request.POST)
            if article_post_form.is_valid():
                article.title = request.POST['title']
                article.body = request.POST['body']
                if request.POST['column'] != 'none':
                    article.column = ArticleColumn.objects.get(id=request.POST['column'])
                else:
                    article.column = None
                if request.FILES.get('avatar'):
                    article.avatar = request.FILES.get('avatar')
                article.tags.set(*request.POST.get('tags').split(','), clear=True)
                article.save()
                return redirect("article:article_detail", id=id)
            else:
                return HttpResponse("表单内容有误，请重新填写")
        else:
            article_post_form = ArticlePostForm()
            columns = ArticleColumn.objects.all()
            context = {'article': article, 'article_post_form': article_post_form, 'columns': columns,
                       'tags': ','.join([x for x in article.tags.names()])}
            return render(request, 'article/update.html', context)
    else:
        return HttpResponse("你无权进行此操作")
