from flask import render_template, request, jsonify, flash, redirect, url_for
from flask_login import login_required, current_user
from scripts.models import db, Device, ManualWorkOrder
from datetime import datetime
import os
from utils.file_utils import allowed_file, compress_image
from utils.lzmx import send_manual_lzmx_message
from config import Config

def init_manual_routes(app):
    @app.route('/manual', methods=['GET', 'POST'])
    @login_required
    def manual():
        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'))
        
        if request.method == 'POST':
            app.logger.info(f'用户 {current_user.name} 开始创建手工故障单')
            # 处理文件上传
            photo_paths = []
            if 'photo' in request.files:
                files = request.files.getlist('photo')
                if len(files) > 5:
                    flash('最多只能上传5张图片')
                    return redirect(url_for('manual'))
                for file in files:
                    if file and allowed_file(file.filename, Config.ALLOWED_EXTENSIONS):  # 修改这里
                        filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{file.filename}"
                        file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
                        file.save(file_path)
                        compress_image(file_path)
                        photo_paths.append(filename)
            
            # 生成工单号
            today = datetime.now().strftime('%Y%m%d')
            last_order = ManualWorkOrder.query.filter(
                ManualWorkOrder.order_id.like(f'M{today}%')
            ).order_by(ManualWorkOrder.order_id.desc()).first()
            
            if last_order:
                last_number = int(last_order.order_id[-4:])
                new_number = f"M{today}{str(last_number + 1).zfill(4)}"
            else:
                new_number = f"M{today}0001"
            
            # 创建手工故障单
            manual_order = ManualWorkOrder(
                order_id=new_number,
                project_type=request.form['project_type'],
                device_id=request.form['device_id'],
                device_location=request.form['device_location'],
                fault_time=datetime.strptime(request.form['fault_time'], '%Y-%m-%dT%H:%M'),
                handler=request.form['handler'],
                fault_type=request.form['fault_type'],
                handle_description=request.form['handle_description'],
                photo_paths=','.join(photo_paths) if photo_paths else None,
                contact_person=request.form['contact_person'],
                contact_phone=request.form['contact_phone'],
                distance_from_branch=request.form['distance_from_branch'],
                remark=request.form.get('remark', ''),
                branch=current_user.branch
            )
            
            db.session.add(manual_order)
            db.session.commit()
            
            # 发送量子密信通知
            send_manual_lzmx_message(
                Config.LZMX_WEBHOOK_URL,  # 修改这里
                request.form['handler'],
                request.form['device_id'],
                request.form['fault_type'],
                request.form['distance_from_branch'],
                manual_order.fault_time,
                request.form['project_type'],
                request.form['device_location']
            )

            app.logger.info(f'用户 {current_user.name} 创建手工故障单成功：{new_number}')
            flash('手工故障单创建成功')
            return redirect(url_for('history'))
        
        return render_template('manual.html')