"""
  @author: LinTao
  @time: 2022/10/3 16:27
  @desc: 用户控制器
"""

import hashlib
import re

from flask import Blueprint, make_response, session, request, redirect, url_for, jsonify

from common.redisdb import redis_connect
from common.utility import ImageCode, gen_email_code
from module.credit import Credit
from module.users import Users
import json
from datetime import datetime

user = Blueprint('user', __name__)


@user.route('/vcode')
def vcode():
    code, bstring = ImageCode().get_code()
    response = make_response(bstring)
    response.headers['Content-Type'] = 'image/jpeg'
    session['vcode'] = code.lower()
    return response


@user.route('/ecode', methods=['POST'])
def ecode():
    email = request.form.get('email')
    if not re.match('^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$', email):
        return 'email-invalid'

    # code = gen_email_code()
    code = "1q2w3e"  # 测试时写死，不发送邮件
    try:
        # send_email(email, code)
        session['ecode'] = code  # 将邮箱验证码保存在session中
        return 'send-pass'
    except:
        return 'send-fail'


@user.route('/user', methods=['POST'])
def register():
    user = Users()
    username = request.form.get('username').strip()
    password = request.form.get('password').strip()
    ecode = request.form.get('ecode').strip()

    # if ecode != session.get('ecode'):  # 检验邮箱验证码(从session取值有问题，暂时搁置)
    if ecode != "1q2w3e":  # 检验邮箱验证码
        return 'ecode-error'
    elif not re.match('^.+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$', username) or len(password) < 5:  # 验证邮箱地址的正确性和密码的有效性
        return 'up-invalid'
    elif len(user.find_by_username(username)) > 0:  # 验证用户是否已经注册
        return 'user-repeated'
    else:
        # 实现注册功能
        password = hashlib.md5(password.encode()).hexdigest()
        result = user.do_register(username, password)
        session['islogin'] = 'true'
        session['userid'] = result.userid
        session['username'] = username
        session['nickname'] = result.nickname
        session['role'] = result.role

        # 更新积分详情表
        Credit().insert_credit(type='用户注册', target=0, credit=50)
        return 'reg-pass'


@user.route('/login', methods=['POST'])
def login():
    user = Users()
    username = request.form.get('username').strip()
    password = request.form.get('password').strip()
    vcode = request.form.get('vcode').lower().strip()

    if vcode != session.get('vcode') and vcode != "0000":  # 检验图片验证码，为postman测试方便，加上万能图片验证码“0000”
        return 'vcode-error'
    else:
        # 实现登录功能
        password = hashlib.md5(password.encode()).hexdigest()
        result = user.find_by_username(username)

        if len(result) == 1 and result[0].password == password:
            session['islogin'] = 'true'
            session['userid'] = result[0].userid
            session['username'] = username
            session['nickname'] = result[0].nickname
            session['role'] = result[0].role

            # 更新积分详情表
            Credit().insert_credit(type='正常登录', target=0, credit=1)
            user.update_credit(1)

            # 将Cookie写入浏览器
            response = make_response('login-pass')
            response.set_cookie('username', username, max_age=30*24*3600)
            response.set_cookie('password', password, max_age=30*24*3600)
            return response
        else:
            return 'login-fail'


@user.route('/logout')
def logout():
    # 清空session和Cookie，页面跳转
    session.clear()

    response = make_response('注销并进行重定向', 302)  # 302状态码表示重定向

    # 两种重定向的方法
    # response.headers['Location'] = '/'
    response.headers['Location'] = url_for('index.home')  # 另一种方式

    # 两种清除cookie的方式
    response.delete_cookie('username')
    response.set_cookie('password', '', max_age=0)

    return response


@user.route('/redis/code', methods=['POST'])
def redis_code():
    username = request.form.get('username').strip()
    code = gen_email_code()
    red = redis_connect()
    red.set(username, code)
    red.expire(username, 30)  # 设置有效期为30秒
    return 'done'


@user.route('/redis/reg', methods=['POST'])
def redis_reg():
    username = request.form.get('username').strip()
    password = request.form.get('password').strip()
    ecode = request.form.get('ecode').strip()
    try:
        red = redis_connect()
        code = red.get(username).lower()
        if code == ecode:
            return '验证码正确'
        else:
            return '验证码错误'
    except:
        return '验证码已经失效'


# @user.route('/redis/login', methods=['POST'])
# def redis_login():
#     red = redis_connect()
#     username = request.form.get('username').strip()
#     password = request.form.get('password').strip()
#     password = hashlib.md5(password.encode()).hexdigest()
#
#     result = red.get('users')
#
#     list = eval(result)
#     # list = json.loads(result)
#
#     for row in list:
#         if row['username'] == username:
#             if row['password'] == password:
#                 return '用户密码正确，登录成功'
#
#     return '登录失败'


# @user.route('/redis/login', methods=['POST'])
# def redis_login():
#     red = redis_connect()
#     username = request.form.get('username').strip()
#     password = request.form.get('password').strip()
#     password = hashlib.md5(password.encode()).hexdigest()
#
#     try:
#         result = red.get(username)
#         if password == result:
#             return '登录成功'
#         else:
#             return '登录失败'
#     except:
#         return '用户名不存在'


@user.route('/redis/login', methods=['POST'])
def redis_login():
    red = redis_connect()
    username = request.form.get('username').strip()
    password = request.form.get('password').strip()
    password = hashlib.md5(password.encode()).hexdigest()

    try:
        result = red.hget('users_hash', username)
        user = eval(result)
        if password == user['password']:
            return '登录成功'
        else:
            return '登录失败'
    except:
        return '用户名不存在'


@user.route('/loginfo')
def loginfo():
    # 没有登录，则直接响应一个空的JSON给前端，用于前端判断
    if session.get('islogin') is None:
        return jsonify(None)
    else:
        dict = {}
        dict['islogin'] = session.get('islogin')
        dict['userid'] = session.get('userid')
        dict['username'] = session.get('username')
        dict['nickname'] = session.get('nickname')
        dict['role'] = session.get('role')
        return jsonify(dict)
