import { NextRequest, NextResponse } from 'next/server'; import crypto from 'crypto'; import pool from '@/lib/db'; export async function GET(request: NextRequest) { let connection; try { const { searchParams } = new URL(request.url); const district = searchParams.get('district'); const keyword = searchParams.get('keyword'); connection = await pool.getConnection(); let sql = "SELECT * FROM houses WHERE status = 'approved'"; const params: any[] = []; if (district && district !== '全部') { sql += ' AND district = ?'; params.push(district); } if (keyword) { sql += ' AND (title LIKE ? OR address LIKE ? OR description LIKE ?)'; const kw = `%${keyword}%`; params.push(kw, kw, kw); } sql += ' ORDER BY created_at DESC'; const [rows] = await connection.query(sql, params); const houses = rows.map((row: any) => ({ id: row.id, owner: row.owner, title: row.title, description: row.description, price: row.price, district: row.district, address: row.address, phone: row.phone, images: row.images ? JSON.parse(row.images) : [], createdAt: row.created_at })); connection.release(); return NextResponse.json({ houses }); } catch (error) { console.error('Get houses error:', error); return NextResponse.json({ error: '获取房屋列表失败' }, { status: 500 }); } finally { if (connection) connection.release(); } } export async function POST(request: NextRequest) { let connection; try { const token = request.cookies.get('auth_token')?.value; if (!token) { return NextResponse.json({ error: '请先登录' }, { status: 401 }); } connection = await pool.getConnection(); const [users] = await connection.query('SELECT username FROM users WHERE token = ?', [token]); if (users.length === 0) { connection.release(); return NextResponse.json({ error: '用户不存在' }, { status: 401 }); } const body = await request.json(); const { title, description, price, district, address, phone, images } = body; if (!title || !price || !district || !address || !phone) { connection.release(); return NextResponse.json({ error: '请填写完整信息' }, { status: 400 }); } const id = crypto.randomUUID(); await connection.query( 'INSERT INTO houses (id, owner, title, description, price, district, address, phone, images, status, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)', [id, users[0].username, title, description || '', Number(price), district, address, phone, JSON.stringify(images || []), 'pending', new Date()] ); const house = { id, owner: users[0].username, title, description: description || '', price: Number(price), district, address, phone, images: images || [], status: 'pending', createdAt: new Date() }; connection.release(); return NextResponse.json({ success: true, house }); } catch (error) { console.error('Create house error:', error); return NextResponse.json({ error: '创建房屋失败' }, { status: 500 }); } finally { if (connection) connection.release(); } }