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

const router = express.Router();

// 验证错误处理中间件
const validate = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ 
      success: false, 
      errors: errors.array() 
    });
  }
  next();
};

router.get('/', async (req, res) => {
  try {
    const result = await db.query(`
      SELECT r.*, u.name as user_name, p.name as project_name
      FROM reimbursements r
      LEFT JOIN users u ON r.applicant_id = u.id
      LEFT JOIN projects p ON r.project_id = p.id
      ORDER BY r.created_at DESC
    `);
    
    // 解析每个报销申请的 attachments 和 detail_items 字段为数组
    const data = result.rows.map(item => {
      // 解析 attachments 字段
      if (item.attachments) {
        try {
          item.attachments = JSON.parse(item.attachments);
        } catch (error) {
          item.attachments = [];
        }
      } else {
        item.attachments = [];
      }
      // 解析 detail_items 字段
      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: '获取报销记录失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

router.post('/', [
  body('amount').isFloat({ min: 0.01 }),
  body('reason').notEmpty(),
  body('expense_type').notEmpty()
], validate, async (req, res) => {
  try {
    const { amount, reason, project_id, currency, reimbursement_date, attachments, amount_cny, applicant, expense_type, detail_items } = req.body;
    const user_id = 1; // 临时使用admin用户
    
    // 生成报销编号
    const reimbursementCode = `REIMB-${Date.now()}`;
    
    const result = await db.query(
      'INSERT INTO reimbursements (user_id, project_id, amount, currency, amount_cny, reason, reimbursement_date, reimbursement_code, status, applicant, expense_type, detail_items, attachments) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)',
      [user_id, project_id, amount, currency || 'CNY', amount_cny || 0, reason, reimbursement_date, reimbursementCode, 'pending', applicant, expense_type, JSON.stringify(detail_items || []), JSON.stringify(attachments || [])]
    );
    
    // SQLite不支持RETURNING，所以需要查询刚插入的数据
    const lastInsert = await db.query('SELECT * FROM reimbursements 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 reimbursements WHERE id = $1', [id]);
    
    if (result.rows.length > 0) {
      const data = result.rows[0];
      // 解析 attachments 字段为数组
      if (data.attachments) {
        try {
          data.attachments = JSON.parse(data.attachments);
        } catch (error) {
          data.attachments = [];
        }
      } else {
        data.attachments = [];
      }
      // 解析 detail_items 字段为数组
      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 { amount, reason, project_id, currency, reimbursement_date, attachments, amount_cny, applicant, expense_type, detail_items, status } = req.body;
    
    const result = await db.query(
      'UPDATE reimbursements SET amount = $1, reason = $2, project_id = $3, currency = $4, reimbursement_date = $5, attachments = $6, amount_cny = $7, applicant = $8, expense_type = $9, detail_items = $10, status = $11 WHERE id = $12',
      [amount, reason, project_id, currency, reimbursement_date, JSON.stringify(attachments || []), amount_cny, applicant, expense_type, JSON.stringify(detail_items || []), status, 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.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const result = await db.query('DELETE FROM reimbursements 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 reimbursements 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 reimbursements 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 reimbursements 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 reimbursements 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;