import json
from flask import Flask, render_template, request, jsonify
from flask_mysqldb import MySQL

app = Flask(__name__)

app.config['MYSQL_HOST'] = 'localhost'
app.config['MYSQL_USER'] = 'root'
app.config['MYSQL_PASSWORD'] = '123456'
app.config['MYSQL_DB'] = 'topic'
mysql = MySQL(app)

# 数据库改
# cursor = mysql.connection.cursor()
# cursor.execute('UPDATE users SET username = %s, password = %s WHERE id = %s', (username, password, user_id))
# mysql.connection.commit()
# cursor.close()

# 钩子函数,每次打开第一件做的事情
@app.before_first_request
def load_users():
    cursor = mysql.connection.cursor()
    cursor.execute('SELECT * FROM users')
    rows = cursor.fetchall()
    users = []
    for row in rows:
        user = {'id': row[0], 'username': row[1], 'password': row[2]}
        users.append(user)
    cursor.close()
    app.config['USERS'] = users
    # register.py['users'] = users

@app.route('/', methods=['GET', 'POST'])
def index():
    return render_template('index.html')
 
# 字典
users = [{'username': 'admin', 'password': 'asd123'}]  # https://blog.csdn.net/weixin_36380516/article/details/80008602

@app.route("/register", methods=['GET', 'POST'])
def register():
    if request.method == 'POST':                       # 为什么要写这个if判断是否POST方式。如果不加的话可能报错......因为网页跳转也在这个路由上实现
        username = request.form.get("username")       # POST方式
        password = request.form.get("password")
        repassword = request.form.get('repassword')
        # 连接数据库
        cursor = mysql.connection.cursor()
        # 判断有无重名
        for i in users:
            if i['username'] == username:
                return '用户名已被注册'
        # 判断俩次密码是否一致
        if password == repassword and password != '' and username != '':
            user = {'username': username, 'password': password}
            # 写入show
            users.append(user)
            # 下面三句是把信息写入数据库
            cursor.execute('INSERT INTO users (username, password) VALUES (%s, %s)', (username, password))
            mysql.connection.commit()
            cursor.close()
            return "注册成功"
        return "俩次密码不一致,或未输入密码"
    return render_template('register.html')

# @app.route('/search')
# def search():
#     for i in users:
#         if i['username'] == 'aa':
#             return '用户名已被注册'
#         return "未注册"

@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        l_username = request.form.get("l_username")
        l_password = request.form.get("l_password")
        # try:
        for i in users:
            # if i['username'] != l_username:
            #     return "用户名未注册"
            if i['username'] == l_username and i['password'] == l_password:
                return "登录成功"
            if i['username'] == l_username and i['password'] != l_password:
                return "密码输入错误"
            # print(i, len(users))
        return "用户名未注册"
    return render_template('login.html')

@app.route('/show')
def show():
    print(users[0]['username'])
    json_str = json.dumps(users)  # 将python数据结构转换为JSON
    print(json_str)
    return json_str

if __name__ == '__main__':
    app.run(debug=True, port=8000,use_reloader=False)

    # if request.method == 'POST':
    #     username = request.form['username']
    #     password = request.form['password']
    #     cursor = mysql.connection.cursor()
    #     cursor.execute('INSERT INTO users (username, password) VALUES (%s, %s)', (username, password))
    #     mysql.connection.commit()
    #     cursor.close()
    #     return 'Successfully registered!'
    # else:
    #     return render_template('register.html')