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 payment_requests 
      ORDER BY created_at DESC
    `);
    
    const data = result.rows.map(item => {
      if (item.attachments) {
        try {
          item.attachments = JSON.parse(item.attachments);
        } catch (error) {
          item.attachments = [];
        }
      } else {
        item.attachments = [];
      }
      if (item.detail_items) {
        try {
          item.detail_items = JSON.parse(item.detail_items);
        } catch (error) {
          item.detail_items = [];
        }
      } else {
        item.detail_items = [];
      }
      return item;
    });
    
    res.json({ success: true, data, count: data.length });
  } catch (error) {
    console.error('获取付款申请失败:', error);
    res.status(500).json({ success: false, message: '获取付款申请失败' });
  }
});

router.post('/', async (req, res) => {
  try {
    const { 
      payment_date, payee, bank_account, bank_name, currency, reason, 
      detail_items, attachments, applicant,
      payee_type, payee_id, expense_type, expense_category, project_id, amount
    } = req.body;
    
    // 生成付款申请编号
    const requestCode = `PAY-${Date.now()}`;
    
    // 使用默认值处理可选字段
    const finalBankAccount = bank_account || '';
    const finalBankName = bank_name || '';
    const finalAmount = amount || 0;
    
    const result = await db.query(
      `INSERT INTO payment_requests (
        payee, bank_account, bank_name, amount, currency, reason, payment_date, 
        request_code, status, applicant, detail_items, attachments,
        payee_type, payee_id, expense_type, expense_category, project_id
      ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17`,
      [
        payee, finalBankAccount, finalBankName, finalAmount, currency || 'CNY', 
        reason, payment_date, requestCode, 'pending', applicant, 
        JSON.stringify(detail_items || []), JSON.stringify(attachments || []),
        payee_type || 'other', payee_id || null, expense_type || 'company', 
        expense_category || '', project_id || null
      ]
    );
    
    // SQLite不支持RETURNING，所以需要查询刚插入的数据
    const lastInsert = await db.query('SELECT * FROM payment_requests ORDER BY id DESC LIMIT 1');
    res.json({ success: true, data: lastInsert.rows[0] });
  } catch (error) {
    console.error('创建付款申请失败:', error);
    res.status(500).json({ success: false, message: '创建付款申请失败' });
  }
});

router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const result = await db.query('SELECT * FROM payment_requests WHERE id = $1', [id]);
    
    if (result.rows.length > 0) {
      const data = result.rows[0];
      if (data.attachments) {
        try {
          data.attachments = JSON.parse(data.attachments);
        } catch (error) {
          data.attachments = [];
        }
      } else {
        data.attachments = [];
      }
      if (data.detail_items) {
        try {
          data.detail_items = JSON.parse(data.detail_items);
        } catch (error) {
          data.detail_items = [];
        }
      } else {
        data.detail_items = [];
      }
      res.json({ success: true, data });
    } else {
      res.status(404).json({ success: false, message: '付款申请不存在' });
    }
  } catch (error) {
    console.error('获取付款申请失败:', error);
    res.status(500).json({ success: false, message: '获取付款申请失败' });
  }
});

router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { 
      payment_date, payee, bank_account, bank_name, currency, reason, 
      detail_items, attachments, applicant, status,
      payee_type, payee_id, expense_type, expense_category, project_id, amount
    } = req.body;
    
    // 构建动态更新SQL，只更新提供的字段
    const updates = [];
    const params = [];
    
    if (payment_date !== undefined) { updates.push('payment_date = $1'); params.push(payment_date); }
    if (payee !== undefined) { updates.push('payee = $1'); params.push(payee); }
    if (bank_account !== undefined) { updates.push('bank_account = $1'); params.push(bank_account); }
    if (bank_name !== undefined) { updates.push('bank_name = $1'); params.push(bank_name); }
    if (amount !== undefined) { updates.push('amount = $1'); params.push(amount); }
    if (currency !== undefined) { updates.push('currency = $1'); params.push(currency); }
    if (reason !== undefined) { updates.push('reason = $1'); params.push(reason); }
    if (detail_items !== undefined) { updates.push('detail_items = $1'); params.push(JSON.stringify(detail_items || [])); }
    if (attachments !== undefined) { updates.push('attachments = $1'); params.push(JSON.stringify(attachments || [])); }
    if (applicant !== undefined) { updates.push('applicant = $1'); params.push(applicant); }
    if (status !== undefined) { updates.push('status = $1'); params.push(status); }
    if (payee_type !== undefined) { updates.push('payee_type = $1'); params.push(payee_type); }
    if (payee_id !== undefined) { updates.push('payee_id = $1'); params.push(payee_id); }
    if (expense_type !== undefined) { updates.push('expense_type = $1'); params.push(expense_type); }
    if (expense_category !== undefined) { updates.push('expense_category = $1'); params.push(expense_category); }
    if (project_id !== undefined) { updates.push('project_id = $1'); params.push(project_id); }
    
    if (updates.length === 0) {
      return res.status(400).json({ success: false, message: '没有要更新的字段' });
    }
    
    params.push(id);
    
    const result = await db.query(
      `UPDATE payment_requests SET ${updates.join(', ')} WHERE id = $1`,
      params
    );
    
    if (result.changes > 0) {
      res.json({ success: true, message: '更新成功' });
    } else {
      res.status(404).json({ success: false, message: '付款申请不存在' });
    }
  } catch (error) {
    console.error('更新付款申请失败:', error);
    res.status(500).json({ success: false, message: '更新付款申请失败' });
  }
});

router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const result = await db.query('DELETE FROM payment_requests WHERE id = $1', [id]);
    
    if (result.changes > 0) {
      res.json({ success: true, message: '删除成功' });
    } else {
      res.status(404).json({ success: false, message: '付款申请不存在' });
    }
  } catch (error) {
    console.error('删除付款申请失败:', error);
    res.status(500).json({ success: false, message: '删除付款申请失败' });
  }
});

router.post('/:id/submit', async (req, res) => {
  try {
    const { id } = req.params;
    
    const result = await db.query('UPDATE payment_requests SET status = $1 WHERE id = $2', ['pending', id]);
    
    if (result.changes > 0) {
      res.json({ success: true, message: '提交成功' });
    } else {
      res.status(404).json({ success: false, message: '付款申请不存在' });
    }
  } catch (error) {
    console.error('提交付款申请失败:', error);
    res.status(500).json({ success: false, message: '提交付款申请失败' });
  }
});

router.post('/:id/withdraw', async (req, res) => {
  try {
    const { id } = req.params;
    
    const result = await db.query('UPDATE payment_requests SET status = $1 WHERE id = $2', ['withdrawn', id]);
    
    if (result.changes > 0) {
      res.json({ success: true, message: '撤回成功' });
    } else {
      res.status(404).json({ success: false, message: '付款申请不存在' });
    }
  } catch (error) {
    console.error('撤回报销申请失败:', error);
    res.status(500).json({ success: false, message: '撤回报销申请失败' });
  }
});

router.post('/:id/approve', async (req, res) => {
  try {
    const { id } = req.params;
    const { remark } = req.body;
    
    const result = await db.query('UPDATE payment_requests SET status = $1, approval_remark = $2 WHERE id = $3', ['approved', remark, id]);
    
    if (result.changes > 0) {
      res.json({ success: true, message: '审批通过成功' });
    } else {
      res.status(404).json({ success: false, message: '付款申请不存在' });
    }
  } catch (error) {
    console.error('审批付款申请失败:', error);
    res.status(500).json({ success: false, message: '审批付款申请失败' });
  }
});

router.post('/:id/reject', async (req, res) => {
  try {
    const { id } = req.params;
    const { rejectReason } = req.body;
    
    const result = await db.query('UPDATE payment_requests SET status = $1 WHERE id = $2', ['pending_edit', id]);
    
    if (result.changes > 0) {
      res.json({ success: true, message: '退回成功' });
    } else {
      res.status(404).json({ success: false, message: '付款申请不存在' });
    }
  } catch (error) {
    console.error('退回报销申请失败:', error);
    res.status(500).json({ success: false, message: '退回报销申请失败' });
  }
});


module.exports = router;