export const dynamic = "force-dynamic";
import getDb from '@/lib/db';
import { getUserFromRequest, unauthorizedResponse } from '@/lib/auth';
import ExcelJS from 'exceljs';

// GET /api/contracts/export - 导出合同为 Excel
export async function GET(request) {
  try {
    const user = getUserFromRequest(request);
    if (!user) return unauthorizedResponse();

    const { searchParams } = new URL(request.url);
    const status = searchParams.get('status');
    const search = searchParams.get('search');
    const date_from = searchParams.get('date_from');
    const date_to = searchParams.get('date_to');
    const department_id = searchParams.get('department_id');

    const db = await getDb();

    let whereClauses = [];
    let queryParams = [];

    // 根据角色应用可见性规则（与列表 API 相同）
    switch (user.role) {
      case 'employee':
        whereClauses.push('c.creator_id = ?');
        queryParams.push(user.id);
        break;
      case 'supervisor':
        whereClauses.push('c.department_id = ?');
        queryParams.push(user.department_id);
        break;
      case 'finance':
      case 'secretary':
      case 'admin':
        break;
    }

    if (status && status !== 'all') {
      whereClauses.push('c.status = ?');
      queryParams.push(status);
    }

    if (search && search.trim()) {
      whereClauses.push('(c.project_name LIKE ? OR c.partner_name LIKE ?)');
      const keyword = `%${search.trim()}%`;
      queryParams.push(keyword, keyword);
    }

    if (date_from) {
      whereClauses.push('c.sign_date >= ?');
      queryParams.push(date_from);
    }
    if (date_to) {
      whereClauses.push('c.sign_date <= ?');
      queryParams.push(date_to);
    }

    if (department_id) {
      whereClauses.push('c.department_id = ?');
      queryParams.push(department_id);
    }

    const whereSQL = whereClauses.length > 0 ? `WHERE ${whereClauses.join(' AND ')}` : '';

    const contracts = db.prepare(
      `SELECT c.* FROM contracts c ${whereSQL} ORDER BY c.created_at DESC`
    ).all(...queryParams);

    // 创建 Excel 工作簿
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('合同列表');

    // 设置列
    worksheet.columns = [
      { header: '经办日期', key: 'created_at', width: 18 },
      { header: '经办人', key: 'creator_name', width: 12 },
      { header: '经办部门', key: 'department_name', width: 15 },
      { header: '项目负责人', key: 'project_leader', width: 12 },
      { header: '签订时间', key: 'sign_date', width: 15 },
      { header: '项目名称', key: 'project_name', width: 25 },
      { header: '合作单位', key: 'partner_name', width: 25 },
      { header: '项目内容', key: 'contract_content', width: 30 },
      { header: '合同总金额', key: 'contract_amount', width: 15 },
      { header: '预估利润', key: 'estimated_profit', width: 15 },
      { header: '收款/付款', key: 'payment_type', width: 12 },
      { header: '初审意见', key: 'supervisor_opinion', width: 20 },
      { header: '财务部意见', key: 'finance_opinion', width: 20 },
      { header: '终审意见', key: 'secretary_opinion', width: 20 },
    ];

    // 设置表头样式
    const headerRow = worksheet.getRow(1);
    headerRow.font = { bold: true };
    headerRow.alignment = { horizontal: 'center' };

    // 添加数据
    const paymentTypeMap = { receive: '收款', pay: '付款' };
    for (const contract of contracts) {
      worksheet.addRow({
        created_at: contract.created_at ? contract.created_at.substring(0, 10) : '',
        creator_name: contract.creator_name || '',
        department_name: contract.department_name || '',
        project_leader: contract.project_leader || '',
        sign_date: contract.sign_date || '',
        project_name: contract.project_name || '',
        partner_name: contract.partner_name || '',
        contract_content: contract.contract_content || '',
        contract_amount: contract.contract_amount || 0,
        estimated_profit: contract.estimated_profit !== null && contract.estimated_profit !== undefined ? contract.estimated_profit : '',
        payment_type: paymentTypeMap[contract.payment_type] || contract.payment_type || '',
        supervisor_opinion: contract.supervisor_opinion || '',
        finance_opinion: contract.finance_opinion || '',
        secretary_opinion: contract.secretary_opinion || '',
      });
    }

    // 生成 Excel 文件
    const buffer = await workbook.xlsx.writeBuffer();

    return new Response(buffer, {
      headers: {
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'Content-Disposition': `attachment; filename=contracts_${new Date().toISOString().substring(0, 10)}.xlsx`,
      },
    });
  } catch (error) {
    console.error('导出合同失败:', error);
    return Response.json(
      { error: '服务器内部错误' },
      { status: 500 }
    );
  }
}
