"""
  @author: LinTao
  @time: 2022/9/11 15:02
  @desc:
"""
import os

from flask import Blueprint, render_template, abort, jsonify

from common.redisdb import redis_connect
from module.article import Article
import math

index = Blueprint("index", __name__)


# @index.route('/')
# def home():
#     article = Article()
#     result = article.find_limit_with_users(0, 10)
#     total = math.ceil(article.get_total_count() / 10)  # 向上取整
#
#     last, most, recommended = article.find_last_most_recommended()
#
#     return render_template('index.html', result=result, total=total, page=1,
#                            last=last, most=most, recommended=recommended)


@index.route('/')
def home():
    # 判断是否存在该页面，如果存在则直接响应，否则正常查询数据库
    if os.path.exists('./template/index-static/index-1.html'):
       return render_template('index-static/index-1.html')

    # 下述代码跟之前保持不变，正常查询数据库
    article = Article()
    result = article.find_limit_with_users(0, 10)
    total = math.ceil(article.get_total_count() / 10)  # 向上取整
    content = render_template('index.html', result=result, total=total, page=1)

    # 如果是第一个用户访问，而静态文件不存在，则生成一个
    with open('./template/index-static/index-1.html', mode='w', encoding='utf-8') as file:
        file.write(content)

    return content


# @index.route('/page/<int:page>')
# def paginate(page):
#     start = (page - 1) * 10  # 1==>0
#     article = Article()
#     result = article.find_limit_with_users(start, 10)
#     total = math.ceil(article.get_total_count() / 10)   # 向上取整
#     return render_template('index.html', result=result, total=total, page=page)


@index.route('/page/<int:page>')
def paginate(page):
    # 判断是否存在该页面，如果存在则直接响应，否则正常查询数据库
    if os.path.exists(f'./template/index-static/index-{page}.html'):
        print('访问静态页面')
        return render_template(f'index-static/index-{page}.html')

    # 下述代码跟之前保持不变，正常查询数据库
    article = Article()
    result = article.find_limit_with_users(0, 10)
    total = math.ceil(article.get_total_count() / 10)  # 向上取整
    content = render_template('index.html', result=result, total=total, page=1)

    # 如果是第一个用户访问，而静态文件不存在，则生成一个
    with open(f'./template/index-static/index-{page}.html', mode='w', encoding='utf-8') as file:
        file.write(content)

    return content


@index.route('/type/<int:type>-<int:page>')
def classify(type, page):
    start = (page - 1) * 10
    article = Article()
    result = article.find_by_type(type, start, 10)
    total = math.ceil(article.get_count_by_type(type) / 10)
    return render_template('type.html', result=result, total=total, page=page, type=type)


@index.route('/search/<int:page>-<keyword>')
def search(page, keyword):
    keyword = keyword.strip()
    if (keyword is None) or (keyword == '') or ('%' in keyword) or (len(keyword) > 10):
        abort(404)  # 跳转到404页面

    start = (page - 1) * 10
    article = Article()
    result = article.find_by_headline(keyword, start, 10)
    total = math.ceil(article.get_count_by_headline(keyword) / 10)
    return render_template('search.html', result=result, page=page, total=total, keyword=keyword)


@index.route('/recommend')
def recommend():
    article = Article()
    last, most, recommended = article.find_last_most_recommended()
    list = []
    list.append(last)
    list.append(most)
    list.append(recommended)
    return jsonify(list)


# Redis 重构
@index.route('/redis')
def home_redis():
    red = redis_connect()

    # 获取有序集合 article 的总数量
    count = red.zcard('article')
    total = math.ceil(count / 10)

    # 利用 zrevrange 从有序集合中倒叙取 0-9 ，共10条数据
    result = red.zrevrange('article', 0, 9)
    # 由于加载进来的每一条数据是一个字符串，需要使用eval函数将其转换为字典
    article_list = []
    for row in result:
        article_list.append(eval(row))

    return render_template('index-redis.html', article_list=article_list, page=1, total=total)


@index.route('/redis/page/<int:page>')
def paginate_redis(page):
    pagesize = 10
    start = (page - 1) * pagesize
    red = redis_connect()

    # 获取有序集合 article 的总数量
    count = red.zcard('article')
    total = math.ceil(count / 10)

    # 利用 zrevrange 从有序集合中倒叙取 0-9 ，共10条数据
    result = red.zrevrange('article', start, start+pagesize-1)
    # 由于加载进来的每一条数据是一个字符串，需要使用eval函数将其转换为字典
    article_list = []
    for row in result:
        article_list.append(eval(row))

    return render_template('index-redis.html', article_list=article_list, page=page, total=total)


@index.route('/static')
def all_static():
    pagesize = 10
    article = Article()

    # 先计算一共有多少也，处理逻辑与分页接口一致
    total = math.ceil(article.get_total_count() / pagesize)

    # 遍历每一页的内容，从数据库中查询出来，渲染到对应页面中
    for page in range(1, total + 1):
        start = (page - 1) * pagesize
        result = article.find_limit_with_users(start, pagesize)

        # 将当前页面正常渲染，但不响应给前端，而是将渲染后的内容写入静态文件
        content = render_template('index-static.html', result=result, page=page, total=total)

        # 将渲染后的内容写入静态文件
        with open((f'./template/index-static/index-{page}.html'), mode='w', encoding='utf-8') as file:
            file.write(content)
    return '文章列表页面分页静态化处理完成'

