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

from services.log_helper import LogHelper,OperationType,OperationModule
from services.service_user import UserService

UserService = UserService()

auth_bp = Blueprint('auth', __name__, template_folder='templates')

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():

    # UserService.default_user()
    # 如果用户已登录，重定向到首页
    if 'user_id' in session:
        return redirect(url_for('project.index'))

    if request.method == 'POST':
        keyword = request.form.get('keyword')
        password = request.form.get('password')

        # 调用UserService进行用户验证
        user, message = UserService.login(keyword, password)

        if user:
            # 登录成功，保存用户信息到session
            session['user_id'] = user.id
            session['username'] = user.username
            # next_page = request.args.get('next')
            # if next_page:
            #     return jsonify({'success': True,'redirect_url':next_page})
            return jsonify({'success': True})

            # # 获取next参数，如果存在则重定向到该页面
            # if next_page:
            #     return redirect(next_page)
            # return redirect(url_for('project.index'))
        else:
            # 登录失败，显示错误信息
            return jsonify({'success': False,'error': message})

    return render_template('auth/login.html')

@auth_bp.route('/update_user_password', methods=['POST'])
def update_user_password():
    data = request.get_json()
    old_password = data.get('old_password')
    new_password = data.get('new_password')
    user_id = session.get('user_id')
    if user_id:
        success, message = UserService.update_password(user_id, old_password, new_password)
        return jsonify({'success': success, 'error': message})
    else:
        return jsonify({'success': False, 'error': '用户未登录'})

@auth_bp.route('/logout', methods=['GET','POST'])
def logout():
    # 清除session中的用户信息
    username = session.get('username')
    session.pop('user_id', None)
    session.pop('username', None)
    LogHelper.log_success(OperationType.LOGIN, OperationModule.ACCOUNT, '用户退出登录',username=username)
    return redirect(url_for('auth.login'))