import { NextRequest, NextResponse } from 'next/server'; import pool from '@/lib/db'; import { getAllFields } from '@/lib/field-mapping'; // GET - 获取所有配置 export async function GET() { try { // 先返回字段列表(不依赖数据库) const availableFields = getAllFields(); // 尝试查询配置(如果表不存在会失败) let configs: any[] = []; try { const connection = await pool.getConnection(); const [configRows] = await connection.query( 'SELECT * FROM t_daily_report_config WHERE is_active = 1 ORDER BY create_time DESC' ); configs = configRows || []; connection.release(); } catch (dbError) { // 如果表不存在,返回空数组 console.log('配置表查询失败,可能是表未初始化:', dbError); configs = []; } return NextResponse.json({ success: true, data: configs, availableFields: availableFields }); } catch (error) { return NextResponse.json({ success: false, message: '获取配置失败', error: error instanceof Error ? error.message : '未知错误' }, { status: 500 }); } } // POST - 创建新配置 export async function POST(request: NextRequest) { try { const body = await request.json(); const { config_name, split_type, split_value, split_name, selected_fields, sum_fields } = body; // 验证必填字段 if (!config_name || !split_type || !split_value || !selected_fields || selected_fields.length === 0) { return NextResponse.json({ success: false, message: '缺少必填字段(配置名称、拆分方式、拆分值、选择的字段)' }, { status: 400 }); } // 验证拆分方式 if (split_type !== 'company_id' && split_type !== 'user_id') { return NextResponse.json({ success: false, message: '拆分方式必须是 company_id 或 user_id' }, { status: 400 }); } // 获取连接 const connection = await pool.getConnection(); // 插入配置 await connection.query( `INSERT INTO t_daily_report_config (config_name, split_type, split_value, split_name, selected_fields, sum_fields) VALUES (?, ?, ?, ?, ?, ?)`, [ config_name, split_type, split_value, split_name || null, JSON.stringify(selected_fields), sum_fields ? JSON.stringify(sum_fields) : null ] ); connection.release(); return NextResponse.json({ success: true, message: '配置创建成功' }); } catch (error) { return NextResponse.json({ success: false, message: '创建配置失败', error: error instanceof Error ? error.message : '未知错误' }, { status: 500 }); } }