from flask import *
from flask import Blueprint

from func import decryption
import db.fz_data, db.user ,app_conf, time


conf = app_conf.conf()

page_bp = Blueprint("page_bp", __name__)


@page_bp.route("/show", methods=["GET"])
def showTable():
    if request.cookies.get("user") == None:
        return redirect("/login")
    data = db.fz_data.LoadFzData()
    return render_template("tables.html", data=data)


@page_bp.route("/", methods=["GET"])
def index():
    if request.cookies.get("user") == None:
        return redirect("/login")
    total = [0, 0, 0]
    total[0] = db.fz_data.total()
    data = db.fz_data.LoadFzData()
    for i in data:
        w_time = time.mktime(time.strptime(i[4], "%Y-%m-%d %H:%M:%S"))
        nowtime = time.time()
        if w_time + 60 * 60 * 24 * 7 > nowtime:
            total[1] += 1
        if w_time + 60 * 60 * 24 * 30 > nowtime:
            total[2] += 1
    return render_template("index.html", total=total)


@page_bp.route("/login", methods=["GET", "POST"])
def login():
    if request.method == "GET":
        return render_template("login.html")
    elif request.method == "POST":
        req_data = request.get_json()  # 使用 get_json 方法获取 JSON 数据
        
        if db.user.Check(req_data['username'], req_data['password']):
            jsondata = {
                "success": True,
                "message": "验证成功"
            }
            resp = jsonify(jsondata)
            if req_data.get('remember', False):  # 使用 get 方法获取键，默认值为 False
                resp.set_cookie("user", req_data['username'], max_age=60*60*24*365)
            else:
                resp.set_cookie("user", req_data['username'])
        else:
            jsondata = {
                "success": False,
                "message": "用户名或密码错误"
            }
            resp = jsonify(jsondata)
        
        return resp  # 返回 response 对象
    
@page_bp.route("/logout", methods=["GET"])
def logout():
    if request.method == "GET":
        resp = make_response(redirect("/login"))
        resp.delete_cookie("user")
        return resp
