/**
 * 物流管理路由
 * 遵循设计方案：采购-付款-物流-退库一体化流程设计方案.md
 * 章节：四、物流管理
 * 
 * 统一合作伙伴界面规范：
 * - 基本信息：公司名称、地址、联系方式、报价描述
 * - 联系人：支持多个联系人，标记主联系人
 * - 收款信息：支持多个银行账户，标记默认账户
 * - 业务台账：订单列表、运费总额、已付/未付金额
 */
const express = require('express');
const db = require('../db');

const router = express.Router();

/**
 * 获取物流公司列表
 */
router.get('/', async (req, res) => {
  try {
    const { status } = req.query;
    let query = 'SELECT id, code, name, address, phone, email, status, remark, created_at FROM logistics_companies';
    const params = [];
    
    if (status) {
      query += ' WHERE status = $1';
      params.push(status);
    }
    
    query += ' ORDER BY created_at DESC';
    
    const result = await db.query(query, params);
    
    res.json({
      success: true,
      data: result.rows,
      count: result.rows.length
    });
  } catch (error) {
    console.error('获取物流公司列表失败:', error);
    res.status(500).json({
      success: false,
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

/**
 * 获取物流公司详情（包含所有TAB数据）
 */
router.get('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    const companyResult = await db.query('SELECT id, code, name, address, phone, email, status, remark, created_at FROM logistics_companies WHERE id = $1', [id]);
    
    if (companyResult.rows.length === 0) {
      return res.status(404).json({ success: false, message: '物流公司不存在' });
    }
    
    const company = companyResult.rows[0];
    
    const contactsResult = await db.query(`
      SELECT * FROM logistics_company_contacts 
      WHERE logistics_company_id = $1 
      ORDER BY is_primary DESC, id
    `, [id]);
    company.contacts = contactsResult.rows;
    
    const bankAccountsResult = await db.query(`
      SELECT * FROM logistics_company_bank_accounts 
      WHERE logistics_company_id = $1 
      ORDER BY is_default DESC, id
    `, [id]);
    company.payment_infos = bankAccountsResult.rows;
    
    company.orders = [];
    company.total_primary_freight = 0;
    company.total_secondary_freight = 0;
    company.paid_primary_freight = 0;
    company.paid_secondary_freight = 0;
    company.ledger = { summary: { item_count: 0, total_primary_freight: 0, total_secondary_freight: 0, total_freight: 0, paid_primary_freight: 0, paid_secondary_freight: 0, paid_amount: 0, unpaid_amount: 0 }, items: [] };
    
    res.json({
      success: true,
      data: company
    });
  } catch (error) {
    console.error('获取物流公司详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取物流公司详情失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

/**
 * 创建物流公司
 */
router.post('/', async (req, res) => {
  try {
    const { code, name, address, phone, email, remark } = req.body;
    
    const companyCode = code || 'LC' + new Date().toISOString().slice(0, 10).replace(/-/g, '') + 
                        String(Math.floor(Math.random() * 10000)).padStart(4, '0');
    
    const result = await db.query(`
      INSERT INTO logistics_companies 
      (code, name, address, phone, email, status, remark, created_at, updated_at)
      VALUES ($1, $2, $3, $4, $5, 'active', $6, NOW(), NOW())
      RETURNING id
    `, [companyCode, name, address, phone, email, remark]);
    
    res.json({
      success: true,
      message: '物流公司创建成功',
      data: { id: result.rows[0].id, code: companyCode }
    });
  } catch (error) {
    console.error('创建物流公司失败:', error);
    res.status(500).json({
      success: false,
      message: '创建物流公司失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

/**
 * 更新物流公司基本信息
 */
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { name, address, phone, email, remark } = req.body;
    
    const result = await db.query(`
      UPDATE logistics_companies 
      SET name = $1, address = $2, phone = $3, email = $4, remark = $5, updated_at = NOW()
      WHERE id = $6
    `, [name, address, phone, email, remark, id]);
    
    if (result.rowCount === 0) {
      return res.status(404).json({ success: false, message: '物流公司不存在' });
    }
    
    res.json({
      success: true,
      message: '物流公司更新成功'
    });
  } catch (error) {
    console.error('更新物流公司失败:', error);
    res.status(500).json({
      success: false,
      message: '更新物流公司失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

/**
 * 删除物流公司
 */
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    
    await db.query('BEGIN');
    
    try {
      await db.query('DELETE FROM logistics_company_bank_accounts WHERE logistics_company_id = $1', [id]);
      await db.query('DELETE FROM logistics_company_contacts WHERE logistics_company_id = $1', [id]);
      await db.query('DELETE FROM logistics_companies WHERE id = $1', [id]);
      
      await db.query('COMMIT');
      
      res.json({ success: true, message: '物流公司删除成功' });
    } catch (innerError) {
      await db.query('ROLLBACK');
      throw innerError;
    }
  } catch (error) {
    console.error('删除物流公司失败:', error);
    res.status(500).json({
      success: false,
      message: '删除物流公司失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

/**
 * 获取物流公司联系人列表
 */
router.get('/:id/contacts', async (req, res) => {
  try {
    const { id } = req.params;
    
    const result = await db.query(`
      SELECT * FROM logistics_company_contacts 
      WHERE logistics_company_id = $1 
      ORDER BY is_primary DESC, id
    `, [id]);
    
    res.json({
      success: true,
      data: result.rows
    });
  } catch (error) {
    console.error('获取联系人列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取联系人列表失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

/**
 * 添加联系人
 */
router.post('/:id/contacts', async (req, res) => {
  try {
    const { id } = req.params;
    const { name, phone, position, is_primary } = req.body;
    
    if (is_primary) {
      await db.query(
        'UPDATE logistics_company_contacts SET is_primary = false WHERE logistics_company_id = $1',
        [id]
      );
    }
    
    const result = await db.query(`
      INSERT INTO logistics_company_contacts 
      (logistics_company_id, name, phone, position, is_primary, created_at, updated_at)
      VALUES ($1, $2, $3, $4, $5, NOW(), NOW())
      RETURNING id
    `, [id, name, phone, position, is_primary ? true : false]);
    
    res.json({
      success: true,
      message: '联系人添加成功',
      data: { id: result.rows[0].id }
    });
  } catch (error) {
    console.error('添加联系人失败:', error);
    res.status(500).json({
      success: false,
      message: '添加联系人失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

/**
 * 更新联系人
 */
router.put('/:id/contacts/:contactId', async (req, res) => {
  try {
    const { id, contactId } = req.params;
    const { name, phone, position, is_primary } = req.body;
    
    if (is_primary) {
      await db.query(
        'UPDATE logistics_company_contacts SET is_primary = false WHERE logistics_company_id = $1',
        [id]
      );
    }
    
    const result = await db.query(`
      UPDATE logistics_company_contacts 
      SET name = $1, phone = $2, position = $3, is_primary = $4, updated_at = NOW()
      WHERE id = $5 AND logistics_company_id = $6
    `, [name, phone, position, is_primary ? true : false, contactId, id]);
    
    if (result.rowCount === 0) {
      return res.status(404).json({ success: false, message: '联系人不存在' });
    }
    
    res.json({ success: true, message: '联系人更新成功' });
  } catch (error) {
    console.error('更新联系人失败:', error);
    res.status(500).json({
      success: false,
      message: '更新联系人失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

/**
 * 删除联系人
 */
router.delete('/:id/contacts/:contactId', async (req, res) => {
  try {
    const { id, contactId } = req.params;
    
    const result = await db.query(
      'DELETE FROM logistics_company_contacts WHERE id = $1 AND logistics_company_id = $2',
      [contactId, id]
    );
    
    if (result.rowCount === 0) {
      return res.status(404).json({ success: false, message: '联系人不存在' });
    }
    
    res.json({ success: true, message: '联系人删除成功' });
  } catch (error) {
    console.error('删除联系人失败:', error);
    res.status(500).json({
      success: false,
      message: '删除联系人失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

/**
 * 获取物流公司收款信息列表
 */
router.get('/:id/payment-infos', async (req, res) => {
  try {
    const { id } = req.params;
    
    const result = await db.query(`
      SELECT * FROM logistics_company_bank_accounts 
      WHERE logistics_company_id = $1 
      ORDER BY is_default DESC, id
    `, [id]);
    
    res.json({
      success: true,
      data: result.rows
    });
  } catch (error) {
    console.error('获取收款信息列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取收款信息列表失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

/**
 * 添加收款信息
 */
router.post('/:id/payment-infos', async (req, res) => {
  try {
    const { id } = req.params;
    const { account_name, account_number, bank_name, qr_code, is_default } = req.body;
    
    if (is_default) {
      await db.query(
        'UPDATE logistics_company_bank_accounts SET is_default = false WHERE logistics_company_id = $1',
        [id]
      );
    }
    
    const result = await db.query(`
      INSERT INTO logistics_company_bank_accounts 
      (logistics_company_id, account_name, account_number, bank_name, qr_code, is_default, created_at, updated_at)
      VALUES ($1, $2, $3, $4, $5, $6, NOW(), NOW())
      RETURNING id
    `, [id, account_name, account_number, bank_name, qr_code, is_default ? true : false]);
    
    res.json({
      success: true,
      message: '收款信息添加成功',
      data: { id: result.rows[0].id }
    });
  } catch (error) {
    console.error('添加收款信息失败:', error);
    res.status(500).json({
      success: false,
      message: '添加收款信息失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

/**
 * 更新收款信息
 */
router.put('/:id/payment-infos/:infoId', async (req, res) => {
  try {
    const { id, infoId } = req.params;
    const { account_name, account_number, bank_name, qr_code, is_default } = req.body;
    
    if (is_default) {
      await db.query(
        'UPDATE logistics_company_bank_accounts SET is_default = false WHERE logistics_company_id = $1',
        [id]
      );
    }
    
    const result = await db.query(`
      UPDATE logistics_company_bank_accounts 
      SET account_name = $1, account_number = $2, bank_name = $3, qr_code = $4, is_default = $5, updated_at = NOW()
      WHERE id = $6 AND logistics_company_id = $7
    `, [account_name, account_number, bank_name, qr_code, is_default ? true : false, infoId, id]);
    
    if (result.rowCount === 0) {
      return res.status(404).json({ success: false, message: '收款信息不存在' });
    }
    
    res.json({ success: true, message: '收款信息更新成功' });
  } catch (error) {
    console.error('更新收款信息失败:', error);
    res.status(500).json({
      success: false,
      message: '更新收款信息失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

/**
 * 删除收款信息
 */
router.delete('/:id/payment-infos/:infoId', async (req, res) => {
  try {
    const { id, infoId } = req.params;
    
    const result = await db.query(
      'DELETE FROM logistics_company_bank_accounts WHERE id = $1 AND logistics_company_id = $2',
      [infoId, id]
    );
    
    if (result.rowCount === 0) {
      return res.status(404).json({ success: false, message: '收款信息不存在' });
    }
    
    res.json({ success: true, message: '收款信息删除成功' });
  } catch (error) {
    console.error('删除收款信息失败:', error);
    res.status(500).json({
      success: false,
      message: '删除收款信息失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

/**
 * 获取物流公司业务台账
 */
router.get('/:id/orders', async (req, res) => {
  try {
    const { id } = req.params;
    
    res.json({
      success: true,
      data: []
    });
  } catch (error) {
    console.error('获取业务台账失败:', error);
    res.status(500).json({
      success: false,
      message: '获取业务台账失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

/**
 * 获取物流公司财务台账（汇总+订单列表）
 */
router.get('/:id/ledger', async (req, res) => {
  try {
    const { id } = req.params;
    
    res.json({
      success: true,
      data: {
        summary: {
          order_count: 0,
          total_primary_freight: 0,
          total_secondary_freight: 0,
          total_freight: 0,
          paid_amount: 0,
          unpaid_amount: 0
        },
        orders: []
      }
    });
  } catch (error) {
    console.error('获取物流公司台账失败:', error);
    res.status(500).json({
      success: false,
      message: '获取物流公司台账失败',
      error: process.env.NODE_ENV === 'development' ? error.message : '操作失败'
    });
  }
});

module.exports = router;
