import sqlite3
from datetime import datetime
from flask import Blueprint, jsonify, request

# 导入数据库工具
from db_utils import get_db_connection, close_db_connection

# 创建Flask蓝图
api_bp = Blueprint('api', __name__)

# API函数1: 返回最新的参数配置记录
@api_bp.route('/api/parameters', methods=['GET'])
def get_parameters():
    try:
        # 连接数据库
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 查询所有参数配置记录并只返回第一条（最新的一条）
        cursor.execute("""
            SELECT id, param1, param2, param3, param4, param5, update_time 
            FROM parameter_config 
            ORDER BY update_time DESC
            LIMIT 1
        """)
        
        # 获取第一条查询结果
        row = cursor.fetchone()
        
        # 关闭数据库连接
        close_db_connection(conn)
        
        # 如果没有查询到数据
        if not row:
            return jsonify({
                'success': False,
                'error': '未找到参数配置记录',
                'data': None
            }), 404
        
        # 格式化查询结果
        parameter = {
            'id': row[0],
            'param1': row[1],
            'param2': row[2],
            'param3': row[3],
            'param4': row[4],
            'param5': row[5],
            'update_time': row[6]
        }
        
        # 返回JSON格式的数据
        return jsonify({
            'success': True,
            'data': parameter
        })
    except Exception as e:
        # 确保在异常情况下也关闭连接
        if 'conn' in locals() and conn:
            close_db_connection(conn)
        return jsonify({
            'success': False,
            'error': str(e),
            'data': []
        }), 500

# API函数2: 返回query_history表中所有results_count=-1的数据
@api_bp.route('/api/pending-queries', methods=['GET'])
def get_pending_queries():
    try:
        # 连接数据库
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 查询query_history表中results_count=-1的所有数据
        cursor.execute("""
            SELECT id, query_date, plate_number, phone, results_count, query_ip, user_id
            FROM query_history 
            WHERE results_count = -1
            ORDER BY query_date DESC
        """)
        
        # 获取所有查询结果
        rows = cursor.fetchall()
        
        # 关闭数据库连接
        close_db_connection(conn)
        
        # 格式化查询结果
        pending_queries = []
        for row in rows:
            pending_query = {
                'id': row['id'],
                'query_date': row['query_date'],
                'plate_number': row['plate_number'],
                'phone': row['phone'],
                'results_count': row['results_count'],
                'query_ip': row['query_ip'],
                'user_id': row['user_id'] if 'user_id' in row.keys() else None
            }
            pending_queries.append(pending_query)
        
        # 返回JSON格式的数据
        return jsonify({
            'success': True,
            'data': pending_queries,
            'count': len(pending_queries)
        })
    except Exception as e:
        # 确保在异常情况下也关闭连接
        if 'conn' in locals() and conn:
            close_db_connection(conn)
        return jsonify({
            'success': False,
            'error': str(e),
            'data': []
        }), 500

# API函数3: 更新query_history表中对应记录的results_count值，并可选保存车辆信息到car_owner表
@api_bp.route('/api/update-query-result', methods=['POST'])
def update_query_result():
    try:
        # 获取前端提交的数据
        data = request.json
        if not data:
            return jsonify({
                'success': False,
                'error': '请求数据不能为空',
                'data': None
            }), 400
        
        # 检查必要的字段是否存在
        if 'id' not in data or 'results_count' not in data:
            return jsonify({
                'success': False,
                'error': '缺少必要的字段: id 或 results_count',
                'data': None
            }), 400
        
        # 获取id和results_count值
        query_id = data['id']
        results_count = data['results_count']
        cars_info = data.get('cars_info')
        
        # 打印当前函数处理的三个关键值
        print(f"update_query_result函数处理的值 - query_id: {query_id}, results_count: {results_count}, cars_info: {cars_info}")
        
        # 连接数据库
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 更新query_history表中的对应记录
        cursor.execute("""
            UPDATE query_history 
            SET results_count = ? 
            WHERE id = ?
        """, (results_count, query_id))
        
        # 如果提供了车辆信息，将其保存到car_owner表
        car_owner_ids = []
        if cars_info and isinstance(cars_info, list):
            # 先获取查询历史中的车牌号和手机号，用于关联
            cursor.execute("SELECT plate_number, phone FROM query_history WHERE id = ?", (query_id,))
            query_info = cursor.fetchone()
            
            if query_info:
                for car_info in cars_info:
                    # 提取必要的字段
                    plate_number = car_info.get('plate_number', '')
                    phone = car_info.get('mobilephone','')
                    id_card = car_info.get('certno', '')
                    name = car_info.get('name', '')
                    email = car_info.get('email', '')
                    address = ''
                    
                    # 插入car_owners表，包含所有必要的字段
                    cursor.execute("""
                        INSERT INTO car_owners (plate_number, phone, id_card, name, email, address, query_history_id)
                        VALUES (?, ?, ?, ?, ?, ?, ?)
                        RETURNING id
                    """, (plate_number, phone, id_card, name, email, address, query_id))
                    
                    # 获取插入/更新的记录ID
                    result = cursor.fetchone()
                    if result:
                        car_owner_ids.append(result[0])
        
        # 提交更改
        conn.commit()
        
        # 检查query_history表是否有记录被更新
        # 重新查询来确认更新是否成功
        cursor.execute("SELECT 1 FROM query_history WHERE id = ?", (query_id,))
        query_exists = cursor.fetchone() is not None
        
        # 关闭数据库连接
        close_db_connection(conn)
        
        # 检查是否存在该记录
        if not query_exists:
            return jsonify({
                'success': False,
                'error': '未找到id为 {} 的记录'.format(query_id),
                'data': None
            }), 404
        
        # 返回成功响应
        response_data = {
            'id': query_id,
            'results_count': results_count
        }
        
        # 如果保存了车辆信息，添加到响应数据中
        if car_owner_ids:
            response_data['car_owner_ids'] = car_owner_ids
        
        return jsonify({
            'success': True,
            'message': '记录更新成功' + ('，并成功保存车辆信息' if car_owner_ids else ''),
            'data': response_data
        })
        # 打印当前函数处理的三个关键值
        print(f"update_query_result函数处理的值 - query_id: {query_id}, results_count: {results_count}, cars_info: {cars_info}")
    except Exception as e:
        # 确保在异常情况下也关闭连接
        if 'conn' in locals() and conn:
            close_db_connection(conn)
        return jsonify({
            'success': False,
            'error': str(e),
            'data': None
        }), 500

# API函数4: 保存param4的值到参数配置表
@api_bp.route('/api/save-param4', methods=['POST'])
def save_param4():
    try:
        # 获取前端提交的数据
        data = request.json
        if not data:
            return jsonify({
                'success': False,
                'error': '请求数据不能为空',
                'data': None
            }), 400
        
        # 检查必要的字段是否存在
        if 'param4' not in data:
            return jsonify({
                'success': False,
                'error': '缺少必要的字段: param4',
                'data': None
            }), 400
        
        # 获取param4值并处理
        param4_value = data['param4']
        
        # 添加错误处理：确保param4_value是字符串类型或可以转换为字符串
        try:
            # 尝试将param4_value转换为字符串
            if not isinstance(param4_value, str):
                import json
                # 如果是复杂对象，尝试转换为JSON字符串
                param4_value = json.dumps(param4_value)
        except Exception as json_error:
            # 如果转换失败，记录错误并使用字符串表示
            param4_value = str(param4_value)
        
        # 添加错误处理：限制param4_value的长度，防止过长的数据导致数据库错误
        max_length = 10000  # 可根据数据库字段实际长度调整
        if len(param4_value) > max_length:
            param4_value = param4_value[:max_length] + '...(内容过长已截断)'
        
        # 连接数据库
        conn = get_db_connection()
        cursor = conn.cursor()
        
        # 查询是否存在参数配置记录
        cursor.execute("SELECT id FROM parameter_config ORDER BY update_time DESC LIMIT 1")
        row = cursor.fetchone()
        
        current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        
        if row:
            # 如果存在记录，更新param4字段
            try:
                cursor.execute("""
                    UPDATE parameter_config 
                    SET param4 = ?, update_time = ? 
                    WHERE id = ?
                """, (param4_value, current_time, row[0]))
            except Exception as db_error:
                conn.rollback()  # 回滚事务
                close_db_connection(conn)
                return jsonify({
                    'success': False,
                    'error': f'更新数据库记录时出错: {str(db_error)}',
                    'data': None
                }), 500
        else:
            # 如果不存在记录，插入新记录
            try:
                cursor.execute("""
                    INSERT INTO parameter_config (param1, param2, param3, param4, param5, update_time)
                    VALUES (NULL, NULL, NULL, ?, NULL, ?)
                """, (param4_value, current_time))
            except Exception as db_error:
                conn.rollback()  # 回滚事务
                close_db_connection(conn)
                return jsonify({
                    'success': False,
                    'error': f'插入数据库记录时出错: {str(db_error)}',
                    'data': None
                }), 500
        
        # 提交更改
        conn.commit()
        
        # 获取受影响的行数
        affected_rows = cursor.rowcount
        
        # 关闭数据库连接
        close_db_connection(conn)
        
        # 检查是否有记录被更新或插入
        if affected_rows == 0:
            return jsonify({
                'success': False,
                'error': '保存param4失败，没有记录被更新或插入',
                'data': None
            }), 500
        
        # 返回成功响应
        return jsonify({
            'success': True,
            'message': 'param4保存成功',
            'data': {
                'param4': '数据已保存（为避免重复序列化，此处不显示完整内容）'
            }
        })
    except Exception as e:
        # 确保在异常情况下也关闭连接
        if 'conn' in locals() and conn:
            close_db_connection(conn)
        return jsonify({
            'success': False,
            'error': f'服务器内部错误: {str(e)}',
            'data': None
        }), 500