import json
from flask import Flask, render_template, request, jsonify
from flask_mysqldb import MySQL
from flask_login import logout_user
import pymysql
from flask import Flask, render_template
from flask import Flask, jsonify
from flask import Flask, send_from_directory
from flask import Flask
from flask_cors import CORS
import requests
from flask import redirect
# 改密
# from flask_wtf import FlaskForm
# from wtforms import StringField, PasswordField, SubmitField
# from wtforms.validators import DataRequired, Length, EqualTo

app = Flask(__name__)
# CORS(app, resources={r"/*": {"origins": "http://127.0.0.1:5500"}})  

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

# 区分大小写,且users位置也区分
users = []
# 钩子函数,每次打开第一件做的事情
@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('/weiboindex.html')
# def weiboindex():
#     print(conn)
#     # 从数据库中读取数据
#     cursor = conn.cursor()
#     cursor.execute('SELECT * FROM weibo')
#     data = cursor.fetchall()
#     # print(data)
#     # #  获取查询结果
#     cursor.close()
#     # # 将数据传递给前台模板
#     # return data[0]
#     return render_template('weiboindex.html', data=data)

@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 "登录成功"
                print("login")
                # return redirect('http://127.0.0.1:5000/weiboindex.html')
                return render_template('weiboindex.html')    
                # return render_template('http://127.0.0.1:5000 ')  #TemplateNotFound                            
            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

CORS(app, resources={r"/*": {"origins": "http://127.0.0.1:5500"}})  
conn = pymysql.connect(host='localhost',user='root',password='123456',database='topic',charset='utf8mb4',  
    cursorclass=pymysql.cursors.DictCursor )
if conn:
    print('数据库连接成功!')
else:
    print('数据库连接失败!')
app2 = Flask(__name__)
@app2.route('/weiboindex.html')
def weiboindex():
    print(conn)
    # 从数据库中读取数据
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM weibo')
    data = cursor.fetchall()
    # print(data)
    # #  获取查询结果
    cursor.close()
    # # 将数据传递给前台模板
    # return data[0]
    return render_template('weiboindex.html', data=data)
    # resp = jsonify({'message': 'Welcome to somepage!'})
    # resp.headers['Access-Control-Allow-Origin'] = '*'
    # return resp

if __name__ == '__main__':
    app.run(debug=True, port=8000,use_reloader=False)
    app2.run(debug=True, port=5000,use_reloader=False)
   
    # 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')

# 改密
# @app.route('/change_password', methods=['GET', 'POST'])
# @login_required
# def change_password():
#     form = ChangePasswordForm()
#     if form.validate_on_submit():
#         if current_user.check_password(form.old_password.data):
#             current_user.set_password(form.new_password.data)
#             db.session.commit()
#             return 'Your password has been updated.'
#         else:
#             return 'Invalid old password'
#     return render_template('change_password.html', form=form)

# class User(UserMixin, db.Model):
#     __tablename__ = 'users'
#     id = db.Column(db.Integer, primary_key=True)
#     username = db.Column(db.String(64), index=True, unique=True)
#     password_hash = db.Column(db.String(128))

#     def set_password(self, password):
#         self.password_hash = generate_password_hash(password)

#     def check_password(self, password):
#         return check_password_hash(self.password_hash, password)
   
# 数据库改
# 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()
# 登出
# Flask-Login提供的 “logout_user” 函数,用户 ID 存储在 Flask-Login提供的 “current_user”,登出既删current_user
# @app.route('/logout')
# @login_required
# def logout():
#     logout_user()
#     return '你已登出.'
# 改密
# class ChangePasswordForm(FlaskForm):
#     old_password = PasswordField('Old Password', validators=[DataRequired()])
#     new_password = PasswordField('New Password', validators=[
#         DataRequired(),
#         Length(min=6, message='Password must be at least 6 characters.'),
#         EqualTo('confirm_password', message='Passwords must match.')
#     ])
#     confirm_password = PasswordField('Confirm Password', validators=[DataRequired()])
#     submit = SubmitField('Change Password')