const express = require('express');
const db = require('../db');
const { authenticate, requireAdmin } = require('../middleware/auth');

const router = express.Router();

router.get('/', async (req, res) => {
  try {
    const result = await db.query(`
      SELECT * FROM executions 
      ORDER BY created_at DESC
    `);
    res.json({ success: true, data: result.rows, count: result.rows.length });
  } catch (error) {
    console.error('获取执行记录失败:', error);
    res.status(500).json({ success: false, message: '获取执行记录失败' });
  }
});

router.get('/pending', async (req, res) => {
  try {
    const advances = await db.query('SELECT * FROM advances WHERE status = $1', ['approved']);
    const reimbursements = await db.query('SELECT * FROM reimbursements WHERE status = $1', ['approved']);
    const payments = await db.query('SELECT * FROM payment_requests WHERE status = $1', ['approved']);
    const verifications = await db.query('SELECT * FROM verifications WHERE status = $1', ['approved']);
    const purchaseRequests = await db.query('SELECT * FROM purchase_requests WHERE status = $1', ['approved']);
    
    const pendingData = [
      ...advances.rows.map(item => ({ ...item, type: '预支申请', code: item.advance_code })),
      ...reimbursements.rows.map(item => ({ ...item, type: '报销申请', code: item.reimbursement_code })),
      ...payments.rows.map(item => ({ ...item, type: '付款申请', code: item.request_code })),
      ...verifications.rows.map(item => ({ ...item, type: '核销申请', code: item.verification_code })),
      ...purchaseRequests.rows.map(item => ({ ...item, type: '采购申请', code: item.request_code, amount: item.total_amount, date: item.request_date, reason: item.brief_description || item.remark || '采购申请' }))
    ];
    
    res.json({ success: true, data: pendingData, count: pendingData.length });
  } catch (error) {
    console.error('获取待执行列表失败:', error);
    res.status(500).json({ success: false, message: '获取待执行列表失败' });
  }
});

router.get('/executed', async (req, res) => {
  try {
    const advances = await db.query('SELECT * FROM advances WHERE status = $1', ['executed']);
    const reimbursements = await db.query('SELECT * FROM reimbursements WHERE status = $1', ['executed']);
    const payments = await db.query('SELECT * FROM payment_requests WHERE status = $1', ['executed']);
    const verifications = await db.query('SELECT * FROM verifications WHERE status = $1', ['executed']);
    const purchaseRequests = await db.query('SELECT * FROM purchase_requests WHERE status = $1', ['executed']);
    
    const executedData = [
      ...advances.rows.map(item => ({ ...item, type: '预支申请', code: item.advance_code })),
      ...reimbursements.rows.map(item => ({ ...item, type: '报销申请', code: item.reimbursement_code })),
      ...payments.rows.map(item => ({ ...item, type: '付款申请', code: item.request_code })),
      ...verifications.rows.map(item => ({ ...item, type: '核销申请', code: item.verification_code })),
      ...purchaseRequests.rows.map(item => ({ 
        ...item, 
        type: '采购申请', 
        code: item.request_code, 
        amount: item.total_amount, 
        date: item.request_date, 
        reason: item.brief_description || item.remark || '采购申请',
        executeDate: item.execute_date,
        executeMethod: item.execute_method
      }))
    ];
    
    res.json({ success: true, data: executedData, count: executedData.length });
  } catch (error) {
    console.error('获取已执行列表失败:', error);
    res.status(500).json({ success: false, message: '获取已执行列表失败' });
  }
});

router.post('/', async (req, res) => {
  try {
    const { apply_id, apply_type, action, execute_method, voucher_no, remark, reject_reason, voucher_files } = req.body;
    const operator = '系统管理员';
    const operator_role = 'admin';
    
    await db.query(
      'INSERT INTO executions (apply_id, apply_type, action, execute_method, voucher_no, remark, reject_reason, voucher_files, operator, operator_role, created_at) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, NOW())',
      [apply_id, apply_type, action, execute_method, voucher_no, remark, reject_reason, JSON.stringify(voucher_files || []), operator, operator_role]
    );
    
    let status = action === 'execute' ? 'executed' : 'rejected';
    if (action === 'reject') {
      status = 'pending_edit';
    }
    
    const executeDate = new Date().toISOString().split('T')[0];
    
    switch (apply_type) {
      case 'advance':
        await db.query('UPDATE advances SET status = $1, execute_date = $2, execute_method = $3 WHERE id = $4', [status, executeDate, execute_method, apply_id]);
        break;
      case 'reimbursement':
        await db.query('UPDATE reimbursements SET status = $1, execute_date = $2, execute_method = $3 WHERE id = $4', [status, executeDate, execute_method, apply_id]);
        break;
      case 'payment':
        await db.query('UPDATE payment_requests SET status = $1, execute_date = $2, execute_method = $3 WHERE id = $4', [status, executeDate, execute_method, apply_id]);
        break;
      case 'verification':
        await db.query('BEGIN');
        
        try {
          await db.query('UPDATE verifications SET status = $1, execute_date = $2, execute_method = $3 WHERE id = $4', [status, executeDate, execute_method, apply_id]);
          
          const verification = await db.query('SELECT advance_id, settlement, amount FROM verifications WHERE id = $1', [apply_id]);
          const advanceId = verification.rows[0]?.advance_id;
          const isSettlement = verification.rows[0]?.settlement === 1;
          const verificationAmount = verification.rows[0]?.amount || 0;
          
          if (advanceId && status === 'executed') {
            await db.query('UPDATE advances SET total_reimbursed = total_reimbursed + $1 WHERE id = $2', [verificationAmount, advanceId]);
            
            if (isSettlement) {
              await db.query('UPDATE advances SET status = $1 WHERE id = $2', ['completed', advanceId]);
            } else {
              await db.query('UPDATE advances SET status = $1 WHERE id = $2', ['partial_verification', advanceId]);
            }
          }
          
          await db.query('COMMIT');
        } catch (error) {
          await db.query('ROLLBACK');
          throw error;
        }
        break;
      case 'purchase':
        await db.query('UPDATE purchase_requests SET status = $1, execute_date = $2, execute_method = $3 WHERE id = $4', [status, executeDate, execute_method, apply_id]);
        break;
    }
    
    res.json({ success: true, message: '执行操作成功' });
  } catch (error) {
    console.error('执行操作失败:', error);
    res.status(500).json({ success: false, message: '执行操作失败' });
  }
});

module.exports = router;
