from flask import Flask, render_template, request, redirect, url_for, flash, jsonify
from functions import add_user, delete_user, edit_user, get_user, classify_photos, search_photos
from models import db, User, Photo
import os
from flask_sqlalchemy import SQLAlchemy

# 初始化Flask应用
app = Flask(__name__)
app.secret_key = 'your_secret_key'

# 设置数据库配置
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'  # 修改为你的数据库URI
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False  # 禁用修改追踪

# 初始化SQLAlchemy
db.init_app(app)

# 创建数据库表
with app.app_context():
    db.create_all()

# 首页路由
@app.route('/')
def index():
    return render_template('index.html')

# 用户管理页面
@app.route('/user_management')
def user_management():
    users = User.query.all()
    return render_template('user_management.html', users=users)

@app.route('/get_encoding/<int:user_id>')
def get_encoding(user_id):
    user = User.query.get(user_id)
    return jsonify({"encoding": user.encoding if user and user.encoding else "无数据"})


# 添加用户
@app.route('/add_user', methods=['POST'])
def add_new_user():
    username = request.form['username']
    userphoto = request.files['userphoto']
    if add_user(username, userphoto):
        flash("用户添加成功", "success")
    else:
        flash("用户添加失败", "danger")
    return redirect(url_for('user_management'))

# 删除用户
@app.route('/delete_user/<int:user_id>', methods=['POST'])
def delete_existing_user(user_id):
    if delete_user(user_id):
        flash("用户删除成功", "success")
    else:
        flash("用户删除失败", "danger")
    return redirect(url_for('user_management'))

# 编辑用户
@app.route('/edit_user/<int:user_id>', methods=['GET', 'POST'])
def edit_existing_user(user_id):
    user = get_user(user_id)
    if request.method == 'POST':
        username = request.form['username']
        userphoto = request.files.get('userphoto')
        if edit_user(user_id, username, userphoto):
            flash("用户信息更新成功", "success")
        else:
            flash("更新失败", "danger")
        return redirect(url_for('user_management'))
    return render_template('edit_user.html', user=user)

# 照片上传页面
@app.route('/upload', methods=['GET', 'POST'])
def upload():
    if request.method == 'POST':
        photos = request.files.getlist('photos')
        classify_photos(photos)  # 调用分类处理函数
        return render_template('upload.html', photos=photos)
    return render_template('upload.html')


# 照片搜索
@app.route('/search', methods=['GET', 'POST'])
def search():
    if request.method == 'POST':
        name = request.form['name']
        date = request.form['date']
        photos = search_photos(name, date)
        return render_template('search.html', photos=photos)
    return render_template('search.html')

if __name__ == '__main__':
    app.run(debug=True)
