from flask import Blueprint, render_template, request, redirect, url_for, jsonify, send_from_directory, session
import os, utils
from services.service_project import ProjectService
from models.project_data import ProjectModel, SubProjectModel,SubProjectItemModel
from .views_base import BaseView

project_bp = Blueprint('project', __name__, template_folder='templates/project')

ProjectService = ProjectService()

@project_bp.route('/')
@BaseView.login_required
def index():
    return redirect(url_for('project.main_project_list'))

@project_bp.route('/main_project_list')
@BaseView.login_required
def main_project_list():
    page = request.args.get('p', 1, type=int)
    per_page = request.args.get('pp', 10, type=int)
    keyword = request.args.get('k', '')
    projects, total_count = ProjectService.get_all_project_paginated(page, per_page, keyword)
    return render_template('project_list.html', project_list=projects, keyword=keyword, page=page, per_page=per_page, total_count=total_count)

@project_bp.route('/save_project', methods=['POST'])
@BaseView.login_required
def save_project():
    try:
        data = request.get_json()
        project_id = data.get('project_id')
        project_name = data.get('project_name')
        project_desc = data.get('project_desc')
        if not project_name:
            return jsonify({'success': False, 'error': '项目编号和名称不能为空'}), 400
        if project_id:
            project_data = ProjectService.get_project_by_id(int(project_id))
            if not project_data:
                return jsonify({'success': False, 'error': '项目编号不存在'}), 400
            project_data.project_name = project_name
            project_data.description = project_desc
            result, msg = ProjectService.update_project(project_data)
        else:
            _, username = BaseView.get_current_user()
            project_data = ProjectModel(project_name=project_name, description=project_desc, create_by=username, update_by=username)
            result, msg = ProjectService.add_project(project_data)
        if not result:
            return jsonify({'success': False, 'error': msg}), 400
        return jsonify({'success': True})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400

@project_bp.route('/delete_project/<int:project_id>', methods=['POST'])
@BaseView.login_required
def delete_project(project_id:int):
    try:
        success, message = ProjectService.delete_project(project_id)
        if success:
            return jsonify({'success': True}), 200
        return jsonify({'success': False, 'error': message}), 400
    except Exception as e:
        return jsonify({'success': False, 'error': f'删除项目失败{str(e)}'}), 400

@project_bp.route('/download')
@BaseView.login_required
def download_file():
    filename = request.args.get('f', type=str)
    if not filename:
        return jsonify({'success': False, 'error': '文件名不能为空'}), 400
    try:
        # 安全处理文件名
        pure_filename = os.path.basename(filename)
        safe_filename = os.path.basename(pure_filename)
        path = filename.replace(safe_filename, '')
        upload_folder = os.path.abspath(os.path.join(os.getcwd(),path))
        if not os.path.exists(upload_folder):
            return jsonify({'success': False, 'error': '项目目录不存在'}), 404
        full_path = os.path.join(upload_folder, safe_filename)
        if not os.path.exists(full_path):
            return jsonify({'success': False, 'error': '文件不存在'}), 404
    except Exception as e:
        utils.get_logger().error(f'路径构建失败：{str(e)}')
        return jsonify({'success': False, 'error': f'非法文件路径{str(e)}'}), 400
    return send_from_directory(upload_folder.replace('\\', '/'), safe_filename, as_attachment=True)

@project_bp.route('/sub_project_list/<int:project_id>')
@BaseView.login_required
def sub_project_list(project_id:int):
    project_data = ProjectService.get_project_by_id(project_id)
    keyword = request.args.get('k', '', type=str)
    page = request.args.get('p', 1, type=int)
    per_page = request.args.get('pp', 10, type=int)
    status = request.args.get('s',-1, type=int)
    data_list, total_count = ProjectService.get_all_sub_project_paginated(project_id, page, per_page, keyword, None if status == -1 else status)  # 传递 status 参数
    return render_template('sub_project_list.html', project=project_data ,sub_project_list=data_list, keyword=keyword, page=page, per_page=per_page, total_count=total_count, status=status)  # 传递 status 参数到模板

@project_bp.route('/save_sub_project', methods=['POST'])
@BaseView.login_required
def save_sub_project():
    """处理子项目保存请求，包含文件上传和数据处理"""
    try:
        # 获取表单数据
        sub_id = request.form.get('id', type=int)
        project_id = request.form.get('project_id', type=int)
        sub_project_name = request.form.get('sub_project_name', '')
        standard_version = request.form.get('standard_version', '')
        work_catalog = request.form.get('work_catalog', '')
        work_content = request.form.get('work_content', '')
        delete_old = request.form.get('delete_old_data', 'false') == 'true'
        project_files = request.files.getlist('project_files')
        # 获取或创建子项目对象
        project_data = SubProjectModel(
            sub_id=sub_id,
            project_id=project_id,
            sub_project_name=sub_project_name,
            standard_version=standard_version,
            work_catalog=work_catalog,
            work_content=work_content,
        )
        res, msg = ProjectService.save_sub_project(project_data, project_files, delete_old)
        if res:
            return jsonify({'success': True}), 200
        return jsonify({'success': False, 'error': msg}), 400
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400

@project_bp.route('/start_sub_project_task/<project_id>', methods=['POST'])
@BaseView.login_required
def start_sub_project_task(project_id:int):
    try:
        result, err_msg = ProjectService.start_sub_project_task(project_id)
        return jsonify({'success': result, 'error': err_msg})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@project_bp.route('/start_process_sub_project/<project_id>', methods=['POST'])
@BaseView.login_required
def start_process_sub_project(project_id:int):
    try:
        result, err_msg = ProjectService.process_sub_project(project_id)
        return jsonify({'success': result, 'error': err_msg})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@project_bp.route('/start_send_sub_project/<project_id>', methods=['POST'])
@BaseView.login_required
def start_send_sub_project(project_id:int):
    try:
        result, err_msg = ProjectService.start_send_sub_project(project_id)
        return jsonify({'success': result, 'error': err_msg})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@project_bp.route('/delete_sub_project/<project_id>', methods=['POST'])
@BaseView.login_required
def delete_sub_project(project_id:int):
    try:
        result, err_msg = ProjectService.delete_sub_project(project_id)
        return jsonify({'success': result, 'error': err_msg})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@project_bp.route('/project_item_list/<sub_project_id>')
@BaseView.login_required
def project_item_list(sub_project_id:int):
    process_status = request.args.get('p_s', -1, type=int)
    send_status = request.args.get('s_s', -1, type=int)
    keyword = request.args.get('k', '', type=str)
    page = request.args.get('p', 1, type=int)
    per_page = request.args.get('pp', 10, type=int)
    sub_project_data = ProjectService.get_sub_project_by_id(sub_project_id)
    sub_items, total_count = ProjectService.get_sub_project_item_list_by_sub_project_paginated(sub_project_id, page, per_page, keyword, process_status if process_status != -1 else None, send_status if send_status != -1 else None)
    return render_template('sub_project_item_list.html', sub_project=sub_project_data,items=sub_items, process_status=process_status, send_status=send_status, keyword=keyword, page=page, per_page=per_page, total_count=total_count)

@project_bp.route('/save_sub_project_item', methods=['POST'])
@BaseView.login_required
def save_sub_project_item():
    try:
        data = request.get_json()
        item_id = data.get('id')
        sub_id = data.get('sub_id')
        device_name = data.get('device_name')
        device_model = data.get('device_model')
        device_unit = data.get('device_unit')
        device_count = data.get('device_count')
        standard_no = data.get('standard_no')
        is_query =  data.get('is_query') == True or data.get('is_query') == 'true'
        if  item_id:
            item_data = ProjectService.get_sub_project_item_by_id(item_id)
            # 更新项目
            item_data.device_name = device_name
            item_data.device_model = device_model
            item_data.device_unit = device_unit
            item_data.device_count = float(device_count)
            item_data.standard_no = standard_no
            ProjectService.update_sub_project_item(item_data)
        else:
            sub_project = ProjectService.get_sub_project_by_id(sub_id)
            if not sub_project:
                return jsonify({'success': False, 'error': '项目工程不存在'}), 404
            new_item = SubProjectItemModel(project_id=sub_project.project_id,sub_project_id=sub_id, device_name=device_name,device_count=float(device_count), device_model=device_model, device_unit=device_unit, standard_no=standard_no)
            item_id = ProjectService.add_sub_project_item(new_item)
        if is_query:
            ProjectService.start_process_item(item_id)

        return jsonify({'success': True})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400

@project_bp.route('/delete_sub_project_item/<item_id>', methods=['POST'])
@BaseView.login_required
def delete_sub_project_item(item_id):
    try:
        ProjectService.delete_sub_project_item(item_id)
        return jsonify({'success': True})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)}), 400

@project_bp.route('/start_process_item/<item_id>', methods=['POST'])
@BaseView.login_required
def start_process_item(item_id:int):
    try:
        result, err_msg = ProjectService.start_process_item(item_id)
        return jsonify({'success': result, 'error': err_msg})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

@project_bp.route('/start_send_item/<item_id>', methods=['POST'])
@BaseView.login_required
def start_send_item(item_id:int):
    try:
        result, err_msg = ProjectService.start_send_item(item_id)
        return jsonify({'success': result, 'error': err_msg})
    except Exception as e:
        return jsonify({'success': False, 'error': str(e)})

