const express = require('express');
const db = require('../db');
const router = express.Router();

router.post('/', async (req, res) => {
  try {
    const { purchase_order_id, logistics_record_id, confirm_date, receiver_name, receiver_phone, received_location, is_complete, missing_items, damage_items, photo_urls, remark, confirmed_by } = req.body;
    if (!purchase_order_id) {
      return res.status(400).json({ success: false, message: '采购订单ID不能为空' });
    }
    const result = await db.query(
      `INSERT INTO receiving_confirms (purchase_order_id, logistics_record_id, confirm_date, receiver_name, receiver_phone, received_location, is_complete, missing_items, damage_items, photo_urls, remark, confirmed_by)
       VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12) RETURNING id`,
      [purchase_order_id, logistics_record_id || null, confirm_date || new Date().toISOString().slice(0, 10), receiver_name || '', receiver_phone || '', received_location || '', is_complete !== false, missing_items || '', damage_items || '', photo_urls || [], remark || '', confirmed_by || null]
    );
    if (is_complete) {
      await db.query("UPDATE purchase_orders SET receiving_status = 'received' WHERE id = $1", [purchase_order_id]);
    } else {
      await db.query("UPDATE purchase_orders SET receiving_status = 'partial_received' WHERE id = $1", [purchase_order_id]);
    }
    if (logistics_record_id) {
      await db.query("UPDATE logistics_records SET status = 'arrived', final_arrival_date = CURRENT_DATE WHERE id = $1", [logistics_record_id]);
    }
    res.json({ success: true, message: '收货确认成功', data: { id: result.rows[0].id } });
  } catch (error) {
    console.error('收货确认失败:', error);
    res.status(500).json({ success: false, message: '收货确认失败' });
  }
});

router.get('/:purchase_order_id', async (req, res) => {
  try {
    const result = await db.query(
      'SELECT * FROM receiving_confirms WHERE purchase_order_id = $1 ORDER BY created_at DESC',
      [req.params.purchase_order_id]
    );
    res.json({ success: true, data: result.rows });
  } catch (error) {
    console.error('获取收货记录失败:', error);
    res.status(500).json({ success: false, message: '获取收货记录失败' });
  }
});

router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const fields = ['confirm_date', 'receiver_name', 'receiver_phone', 'received_location', 'is_complete', 'missing_items', 'damage_items', 'photo_urls', 'remark'];
    const updates = [];
    const values = [];
    let paramIndex = 1;
    for (const field of fields) {
      if (req.body[field] !== undefined) {
        updates.push(`${field} = $${paramIndex++}`);
        values.push(req.body[field]);
      }
    }
    if (updates.length === 0) {
      return res.status(400).json({ success: false, message: '没有更新数据' });
    }
    values.push(id);
    await db.query(`UPDATE receiving_confirms SET ${updates.join(', ')} WHERE id = $${paramIndex}`, values);
    res.json({ success: true, message: '收货记录更新成功' });
  } catch (error) {
    console.error('更新收货记录失败:', error);
    res.status(500).json({ success: false, message: '更新收货记录失败' });
  }
});

module.exports = router;
