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 a.*, u.name as user_name, p.name as project_name
      FROM advances a
      LEFT JOIN users u ON a.applicant_id = u.id
      LEFT JOIN projects p ON a.project_id = p.id
      ORDER BY a.created_at DESC
    `);
    
    // 解析每个预支申请的 attachments 字段为数组
    const data = result.rows.map(item => {
      if (item.attachments) {
        try {
          item.attachments = JSON.parse(item.attachments);
        } catch (error) {
          item.attachments = [];
        }
      } else {
        item.attachments = [];
      }
      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()
], validate, async (req, res) => {
  try {
    const { amount, reason, project_id, currency, advance_date, attachments, amount_cny, applicant, status } = req.body;
    const user_id = 1; // 临时使用admin用户
    
    // 生成预支编号
    const advanceCode = `ADV-${Date.now()}`;
    
    const result = await db.query(
      'INSERT INTO advances (applicant_id, project_id, amount, currency, amount_cny, reason, advance_date, advance_code, status, applicant, attachments) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11) RETURNING id',
      [applicant_id, project_id, amount, currency || 'CNY', amount_cny || 0, reason, advance_date, advanceCode, status || 'pending', applicant, JSON.stringify(attachments || [])]
    );
    
    const data = { id: result.rows[0]?.id, applicant_id, project_id, amount, currency, reason, advance_date, advance_code: advanceCode, status, applicant };
    res.json({ success: true, data });
  } 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 advances 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 = [];
      }
      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, advance_date, attachments, amount_cny, applicant, status } = req.body;
    
    const result = await db.query(
      'UPDATE advances SET amount = $1, reason = $2, project_id = $3, currency = $4, advance_date = $5, attachments = $6, amount_cny = $7, applicant = $8, status = $9 WHERE id = $10',
      [amount, reason, project_id, currency, advance_date, JSON.stringify(attachments || []), amount_cny, applicant, 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 advances 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 advances 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 advances 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 advances 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 advances 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;