from flask import Flask, redirect, url_for
from flask_login import LoginManager
from flask_migrate import Migrate
from scripts.models import db, User, Device, WorkOrder, WorkOrderHandling, ManualWorkOrder
from config import Config
from views.auth import init_auth_routes
from views.work_order import init_work_order_routes
from views.statistics import init_statistics_routes
from views.history import init_history_routes
from views.manual import init_manual_routes
from views.device import init_device_routes
from views.about import init_about_routes
from views.dashboard import init_dashboard_routes
from views.user import init_user_routes
import logging
from logging.handlers import RotatingFileHandler
import os
from utils.error_handlers import ErrorHandler

def create_app():
    # 创建应用实例
    app = Flask(__name__)
    app.config.from_object(Config)

    # 配置日志记录
    if not os.path.exists('logs'):
        os.makedirs('logs')
    
    # 创建日志处理器，设置最大文件大小为10MB，保留5个备份文件
    file_handler = RotatingFileHandler(
        'logs/app.log',
        maxBytes=10*1024*1024,  # 10MB
        backupCount=5,
        encoding='utf-8'
    )
    
    # 设置日志格式
    formatter = logging.Formatter(
        '%(asctime)s %(levelname)s: %(message)s',
        '%Y-%m-%d %H:%M:%S'
    )
    file_handler.setFormatter(formatter)
    
    # 设置日志级别
    file_handler.setLevel(logging.INFO)
    app.logger.addHandler(file_handler)
    app.logger.setLevel(logging.INFO)
    app.logger.info('应用启动')

    # 初始化数据库
    db.init_app(app)
    migrate = Migrate(app, db)

    # 初始化异常处理器
    error_handler = ErrorHandler(app)
    
    # 初始化登录管理器
    login_manager = LoginManager()
    login_manager.init_app(app)
    login_manager.login_view = 'login'

    @login_manager.user_loader
    def load_user(user_id):
        try:
            return db.session.get(User, user_id)
        except Exception as e:
            app.logger.error(f"加载用户时出错: {str(e)}")
            return None

    # 注册路由
    @app.route('/')
    def index():
        return redirect(url_for('dashboard'))

    # 初始化各模块路由
    init_auth_routes(app)
    init_work_order_routes(app)
    init_statistics_routes(app)
    init_history_routes(app)
    init_manual_routes(app)
    init_device_routes(app)
    init_about_routes(app)
    init_dashboard_routes(app)
    init_user_routes(app)

    return app

app = create_app()

if __name__ == '__main__':
    with app.app_context():
        try:
            db.create_all()
            app.logger.info("数据库表创建成功")
        except Exception as e:
            app.logger.error(f"创建数据库表时出错: {str(e)}")
    app.run(host='0.0.0.0', port=18019, debug=True)