/**
 * 监管任务结项API接口测试
 * 测试所有API接口的功能和数据库操作
 */

const axios = require('axios');
const mysql = require('mysql2/promise');

// 配置
const API_BASE_URL = 'http://localhost:3000/api';
const DB_CONFIG = {
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'nxxmdata'
};

// 测试用的JWT Token（需要替换为实际的token）
let authToken = '';

// 数据库连接
let dbConnection;

/**
 * 初始化测试环境
 */
async function initializeTest() {
    console.log('🚀 开始初始化测试环境...');
    
    try {
        // 连接数据库
        dbConnection = await mysql.createConnection(DB_CONFIG);
        console.log('✅ 数据库连接成功');
        
        // 这里应该获取真实的JWT token
        // 暂时使用模拟token进行测试
        authToken = 'test-jwt-token';
        console.log('✅ 认证token准备完成');
        
        console.log('✅ 测试环境初始化完成\n');
    } catch (error) {
        console.error('❌ 测试环境初始化失败:', error.message);
        process.exit(1);
    }
}

/**
 * 创建HTTP请求配置
 */
function createRequestConfig() {
    return {
        headers: {
            'Authorization': `Bearer ${authToken}`,
            'Content-Type': 'application/json'
        },
        timeout: 10000
    };
}

/**
 * 测试数据库表结构
 */
async function testDatabaseStructure() {
    console.log('📋 测试数据库表结构...');
    
    try {
        // 检查主表
        const [mainTable] = await dbConnection.execute('DESCRIBE regulatory_task_completions');
        console.log('✅ 主表 regulatory_task_completions 结构正常');
        
        // 检查附件表
        const [attachmentTable] = await dbConnection.execute('DESCRIBE regulatory_task_completion_attachments');
        console.log('✅ 附件表 regulatory_task_completion_attachments 结构正常');
        
        // 检查日志表
        const [logTable] = await dbConnection.execute('DESCRIBE regulatory_task_completion_logs');
        console.log('✅ 日志表 regulatory_task_completion_logs 结构正常');
        
        // 检查示例数据
        const [sampleData] = await dbConnection.execute('SELECT COUNT(*) as count FROM regulatory_task_completions');
        console.log(`✅ 主表中有 ${sampleData[0].count} 条示例数据`);
        
        console.log('✅ 数据库表结构测试通过\n');
    } catch (error) {
        console.error('❌ 数据库表结构测试失败:', error.message);
        throw error;
    }
}

/**
 * 测试获取列表API
 */
async function testGetList() {
    console.log('📋 测试获取监管任务结项列表API...');
    
    try {
        // 测试基础列表查询
        const response = await axios.get(`${API_BASE_URL}/regulatory-task-completion`, createRequestConfig());
        
        if (response.status === 200) {
            console.log('✅ 基础列表查询成功');
            console.log(`   返回数据条数: ${response.data.data?.list?.length || 0}`);
        }
        
        // 测试带参数的查询
        const paramsResponse = await axios.get(`${API_BASE_URL}/regulatory-task-completion`, {
            ...createRequestConfig(),
            params: {
                page: 1,
                limit: 5,
                status: 'pending',
                product_name: '养殖'
            }
        });
        
        if (paramsResponse.status === 200) {
            console.log('✅ 带参数查询成功');
            console.log(`   筛选后数据条数: ${paramsResponse.data.data?.list?.length || 0}`);
        }
        
        console.log('✅ 获取列表API测试通过\n');
        return response.data.data?.list?.[0]?.id; // 返回第一条记录的ID用于后续测试
    } catch (error) {
        console.error('❌ 获取列表API测试失败:', error.response?.data || error.message);
        throw error;
    }
}

/**
 * 测试创建记录API
 */
async function testCreateRecord() {
    console.log('📋 测试创建监管任务结项记录API...');
    
    const testData = {
        application_no: `APP${Date.now()}`,
        policy_no: `POL${Date.now()}`,
        product_name: '测试养殖保险',
        customer_name: '测试客户',
        customer_phone: '13800138000',
        insurance_amount: 100000.00,
        premium_amount: 5000.00,
        start_date: '2025-01-01',
        end_date: '2025-12-31',
        completion_date: '2025-01-19',
        status: 'pending',
        review_comments: '测试创建记录',
        attachments: [
            {
                file_name: '测试文件.pdf',
                file_path: '/uploads/test/test_file.pdf',
                file_size: 1024,
                file_type: 'application/pdf'
            }
        ]
    };
    
    try {
        const response = await axios.post(`${API_BASE_URL}/regulatory-task-completion`, testData, createRequestConfig());
        
        if (response.status === 201) {
            console.log('✅ 创建记录成功');
            console.log(`   新记录ID: ${response.data.data?.id}`);
            
            // 验证数据库中的记录
            const [dbRecord] = await dbConnection.execute(
                'SELECT * FROM regulatory_task_completions WHERE id = ?',
                [response.data.data.id]
            );
            
            if (dbRecord.length > 0) {
                console.log('✅ 数据库记录验证成功');
                console.log(`   申请编号: ${dbRecord[0].application_no}`);
                console.log(`   客户名称: ${dbRecord[0].customer_name}`);
            }
            
            console.log('✅ 创建记录API测试通过\n');
            return response.data.data.id;
        }
    } catch (error) {
        console.error('❌ 创建记录API测试失败:', error.response?.data || error.message);
        throw error;
    }
}

/**
 * 测试获取详情API
 */
async function testGetDetail(recordId) {
    console.log('📋 测试获取监管任务结项详情API...');
    
    try {
        const response = await axios.get(`${API_BASE_URL}/regulatory-task-completion/${recordId}`, createRequestConfig());
        
        if (response.status === 200) {
            console.log('✅ 获取详情成功');
            console.log(`   记录ID: ${response.data.data?.id}`);
            console.log(`   申请编号: ${response.data.data?.application_no}`);
            console.log(`   客户名称: ${response.data.data?.customer_name}`);
            console.log(`   附件数量: ${response.data.data?.attachments?.length || 0}`);
            console.log(`   操作日志数量: ${response.data.data?.operation_logs?.length || 0}`);
        }
        
        console.log('✅ 获取详情API测试通过\n');
    } catch (error) {
        console.error('❌ 获取详情API测试失败:', error.response?.data || error.message);
        throw error;
    }
}

/**
 * 测试更新记录API
 */
async function testUpdateRecord(recordId) {
    console.log('📋 测试更新监管任务结项记录API...');
    
    const updateData = {
        product_name: '更新后的养殖保险',
        insurance_amount: 120000.00,
        premium_amount: 6000.00,
        review_comments: '记录已更新'
    };
    
    try {
        const response = await axios.put(`${API_BASE_URL}/regulatory-task-completion/${recordId}`, updateData, createRequestConfig());
        
        if (response.status === 200) {
            console.log('✅ 更新记录成功');
            
            // 验证数据库中的更新
            const [dbRecord] = await dbConnection.execute(
                'SELECT * FROM regulatory_task_completions WHERE id = ?',
                [recordId]
            );
            
            if (dbRecord.length > 0 && dbRecord[0].product_name === updateData.product_name) {
                console.log('✅ 数据库更新验证成功');
                console.log(`   更新后产品名称: ${dbRecord[0].product_name}`);
                console.log(`   更新后保险金额: ${dbRecord[0].insurance_amount}`);
            }
        }
        
        console.log('✅ 更新记录API测试通过\n');
    } catch (error) {
        console.error('❌ 更新记录API测试失败:', error.response?.data || error.message);
        throw error;
    }
}

/**
 * 测试审核记录API
 */
async function testReviewRecord(recordId) {
    console.log('📋 测试审核监管任务结项记录API...');
    
    const reviewData = {
        status: 'approved',
        review_comments: '审核通过，符合监管要求',
        reviewer_name: '测试审核员'
    };
    
    try {
        const response = await axios.patch(`${API_BASE_URL}/regulatory-task-completion/${recordId}/review`, reviewData, createRequestConfig());
        
        if (response.status === 200) {
            console.log('✅ 审核记录成功');
            
            // 验证数据库中的审核状态
            const [dbRecord] = await dbConnection.execute(
                'SELECT * FROM regulatory_task_completions WHERE id = ?',
                [recordId]
            );
            
            if (dbRecord.length > 0 && dbRecord[0].status === reviewData.status) {
                console.log('✅ 审核状态更新验证成功');
                console.log(`   审核状态: ${dbRecord[0].status}`);
                console.log(`   审核人员: ${dbRecord[0].reviewer_name}`);
            }
            
            // 检查操作日志
            const [logRecords] = await dbConnection.execute(
                'SELECT * FROM regulatory_task_completion_logs WHERE completion_id = ? ORDER BY operation_time DESC LIMIT 1',
                [recordId]
            );
            
            if (logRecords.length > 0) {
                console.log('✅ 操作日志记录成功');
                console.log(`   操作类型: ${logRecords[0].operation_type}`);
                console.log(`   操作描述: ${logRecords[0].operation_description}`);
            }
        }
        
        console.log('✅ 审核记录API测试通过\n');
    } catch (error) {
        console.error('❌ 审核记录API测试失败:', error.response?.data || error.message);
        throw error;
    }
}

/**
 * 测试统计数据API
 */
async function testGetStatistics() {
    console.log('📋 测试获取统计数据API...');
    
    try {
        const response = await axios.get(`${API_BASE_URL}/regulatory-task-completion/stats`, createRequestConfig());
        
        if (response.status === 200) {
            console.log('✅ 获取统计数据成功');
            console.log(`   状态统计项数: ${response.data.data?.statusStats?.length || 0}`);
            console.log(`   月度统计项数: ${response.data.data?.monthlyStats?.length || 0}`);
            console.log(`   产品统计项数: ${response.data.data?.productStats?.length || 0}`);
            
            // 显示部分统计数据
            if (response.data.data?.statusStats?.length > 0) {
                console.log('   状态统计示例:');
                response.data.data.statusStats.forEach(stat => {
                    console.log(`     ${stat.status}: ${stat.count}条`);
                });
            }
        }
        
        console.log('✅ 获取统计数据API测试通过\n');
    } catch (error) {
        console.error('❌ 获取统计数据API测试失败:', error.response?.data || error.message);
        throw error;
    }
}

/**
 * 测试删除记录API
 */
async function testDeleteRecord(recordId) {
    console.log('📋 测试删除监管任务结项记录API...');
    
    try {
        const response = await axios.delete(`${API_BASE_URL}/regulatory-task-completion/${recordId}`, createRequestConfig());
        
        if (response.status === 200) {
            console.log('✅ 删除记录成功');
            
            // 验证数据库中的记录已删除
            const [dbRecord] = await dbConnection.execute(
                'SELECT * FROM regulatory_task_completions WHERE id = ?',
                [recordId]
            );
            
            if (dbRecord.length === 0) {
                console.log('✅ 数据库记录删除验证成功');
            }
            
            // 验证相关附件和日志也被删除
            const [attachments] = await dbConnection.execute(
                'SELECT * FROM regulatory_task_completion_attachments WHERE completion_id = ?',
                [recordId]
            );
            
            const [logs] = await dbConnection.execute(
                'SELECT * FROM regulatory_task_completion_logs WHERE completion_id = ?',
                [recordId]
            );
            
            if (attachments.length === 0 && logs.length === 0) {
                console.log('✅ 相关数据清理验证成功');
            }
        }
        
        console.log('✅ 删除记录API测试通过\n');
    } catch (error) {
        console.error('❌ 删除记录API测试失败:', error.response?.data || error.message);
        throw error;
    }
}

/**
 * 测试错误处理
 */
async function testErrorHandling() {
    console.log('📋 测试错误处理...');
    
    try {
        // 测试获取不存在的记录
        try {
            await axios.get(`${API_BASE_URL}/regulatory-task-completion/99999`, createRequestConfig());
        } catch (error) {
            if (error.response?.status === 404) {
                console.log('✅ 404错误处理正常');
            }
        }
        
        // 测试创建记录时缺少必填字段
        try {
            await axios.post(`${API_BASE_URL}/regulatory-task-completion`, {
                application_no: 'TEST'
                // 缺少其他必填字段
            }, createRequestConfig());
        } catch (error) {
            if (error.response?.status === 400) {
                console.log('✅ 400错误处理正常');
            }
        }
        
        console.log('✅ 错误处理测试通过\n');
    } catch (error) {
        console.error('❌ 错误处理测试失败:', error.message);
    }
}

/**
 * 清理测试环境
 */
async function cleanupTest() {
    console.log('🧹 清理测试环境...');
    
    try {
        if (dbConnection) {
            await dbConnection.end();
            console.log('✅ 数据库连接已关闭');
        }
        
        console.log('✅ 测试环境清理完成\n');
    } catch (error) {
        console.error('❌ 测试环境清理失败:', error.message);
    }
}

/**
 * 主测试函数
 */
async function runTests() {
    console.log('🎯 开始监管任务结项API接口测试\n');
    
    let testRecordId = null;
    
    try {
        // 初始化测试环境
        await initializeTest();
        
        // 测试数据库表结构
        await testDatabaseStructure();
        
        // 测试获取列表
        const existingRecordId = await testGetList();
        
        // 测试创建记录
        testRecordId = await testCreateRecord();
        
        // 测试获取详情
        await testGetDetail(testRecordId);
        
        // 测试更新记录
        await testUpdateRecord(testRecordId);
        
        // 测试审核记录
        await testReviewRecord(testRecordId);
        
        // 测试统计数据
        await testGetStatistics();
        
        // 测试错误处理
        await testErrorHandling();
        
        // 测试删除记录（放在最后）
        await testDeleteRecord(testRecordId);
        
        console.log('🎉 所有测试通过！监管任务结项API接口功能正常');
        
    } catch (error) {
        console.error('💥 测试失败:', error.message);
        console.log('\n📝 测试报告:');
        console.log('   - 部分功能可能需要启动后端服务才能正常测试');
        console.log('   - 需要配置正确的JWT认证token');
        console.log('   - 确保数据库连接配置正确');
        
    } finally {
        // 清理测试环境
        await cleanupTest();
    }
}

// 运行测试
if (require.main === module) {
    runTests().catch(console.error);
}

module.exports = {
    runTests,
    testDatabaseStructure,
    testGetList,
    testCreateRecord,
    testGetDetail,
    testUpdateRecord,
    testReviewRecord,
    testGetStatistics,
    testDeleteRecord
};