from flask import render_template, request, flash, redirect, url_for
from flask_login import login_required, current_user
from scripts.models import db, WorkOrderHandling, ManualWorkOrder
from datetime import datetime

def init_history_routes(app):
    @app.route('/history')
    @login_required
    def history():
        allowed_roles = ['装维员', '统计员', '管理员', 'admin']
        if current_user.role not in allowed_roles and current_user.name != 'Admin':
            app.logger.warning(f'未授权访问：用户 {current_user.name} 尝试访问历史记录')
            flash('您没有权限访问此页面')
            return redirect(url_for('statistics'))
        
        app.logger.info(f'用户 {current_user.name} 访问历史记录页面')
        page = request.args.get('page', 1, type=int)
        per_page = 20
        search = request.args.get('search', '')
        
        # 查询普通工单
        if current_user.role == '统计员':
            query1 = WorkOrderHandling.query
            query2 = ManualWorkOrder.query
        else:
            # 装维员只能看到自己处理的工单
            query1 = WorkOrderHandling.query.filter_by(handler=current_user.name)
            query2 = ManualWorkOrder.query.filter_by(handler=current_user.name)
        
        # 添加搜索条件
        if search:
            query1 = query1.filter(
                db.or_(
                    WorkOrderHandling.order_id.contains(search),
                    WorkOrderHandling.device_id.contains(search),
                    WorkOrderHandling.branch.contains(search),
                    WorkOrderHandling.handler.contains(search),
                    WorkOrderHandling.fault_type.contains(search),
                    WorkOrderHandling.handle_description.contains(search),
                    WorkOrderHandling.contact_person.contains(search),
                    WorkOrderHandling.remark.contains(search)
                )
            )
            query2 = query2.filter(
                db.or_(
                    ManualWorkOrder.order_id.contains(search),
                    ManualWorkOrder.device_id.contains(search),
                    ManualWorkOrder.branch.contains(search),
                    ManualWorkOrder.handler.contains(search),
                    ManualWorkOrder.fault_type.contains(search),
                    ManualWorkOrder.handle_description.contains(search),
                    ManualWorkOrder.contact_person.contains(search),
                    ManualWorkOrder.remark.contains(search)
                )
            )
        
        # 合并两种工单并按时间排序
        handlings1 = query1.all()
        handlings2 = query2.all()
        
        # 将手工故障单转换为与普通工单相同的格式
        combined_handlings = []
        for h in handlings1:
            combined_handlings.append({
                'order_id': h.order_id,
                'branch': h.branch,
                'device_id': h.device_id,
                'handler': h.handler,
                'time': h.restore_time,
                'fault_type': h.fault_type,
                'type': 'normal'
            })
        
        for h in handlings2:
            combined_handlings.append({
                'order_id': h.order_id,
                'branch': h.branch,
                'device_id': h.device_id,
                'handler': h.handler,
                'time': h.create_time,
                'fault_type': h.fault_type,
                'type': 'manual'
            })
        
        # 按时间排序
        combined_handlings.sort(key=lambda x: x['time'], reverse=True)
        
        # 手动分页
        total = len(combined_handlings)
        start = (page - 1) * per_page
        end = start + per_page
        current_page = combined_handlings[start:end]
        
        # 创建分页对象
        class Pagination:
            def __init__(self, items, page, per_page, total):
                self.items = items
                self.page = page
                self.per_page = per_page
                self.total = total
                self.pages = (total + per_page - 1) // per_page
                self.has_prev = page > 1
                self.has_next = page < self.pages
                self.prev_num = page - 1
                self.next_num = page + 1
        
        handlings = Pagination(current_page, page, per_page, total)
        
        return render_template('history.html', handlings=handlings, search=search)

    @app.route('/history/<string:order_id>')
    @login_required
    def history_detail(order_id):
        allowed_roles = ['装维员', '统计员', '管理员', 'admin']
        if current_user.role not in allowed_roles and current_user.name != 'Admin':
            app.logger.warning(f'未授权访问：用户 {current_user.name} 尝试查看工单详情 {order_id}')
            flash('您没有权限访问此页面')
            return redirect(url_for('statistics'))
        
        app.logger.info(f'用户 {current_user.name} 查看工单 {order_id} 的详情')
        # 根据工单号前缀判断是普通工单还是手工故障单
        if order_id.startswith('M'):
            handling = ManualWorkOrder.query.get_or_404(order_id)
        else:
            handling = WorkOrderHandling.query.filter_by(order_id=order_id).first_or_404()
        
        # 装维员只能查看自己处理的工单
        if current_user.role == '装维员' and handling.handler != current_user.name:
            flash('您没有权限查看此工单')
            return redirect(url_for('history'))
        
        # 传递工单类型到模板
        order_type = 'manual' if order_id.startswith('M') else 'normal'
        
        return render_template('history_detail.html', handling=handling, order_type=order_type)
