const express = require('express');
const db = require('../db/init');
const { authMiddleware } = require('../middleware/auth');
const { getEstimatedDrawTime } = require('../services/lottery');

const router = express.Router();

router.use(authMiddleware);

// 获取彩票列表
router.get('/', (req, res) => {
  const { page = 1, limit = 20 } = req.query;
  const offset = (page - 1) * limit;

  const tickets = db.prepare(`
    SELECT * FROM tickets WHERE user_id = ? ORDER BY created_at DESC LIMIT ? OFFSET ?
  `).all(req.user.id, limit, offset);

  // 为未开奖彩票添加预计开奖时间
  const ticketsWithDrawTime = tickets.map(ticket => {
    if (ticket.status === 'pending' && ticket.game && ticket.issue) {
      return {
        ...ticket,
        estimated_draw_time: getEstimatedDrawTime(ticket.game, ticket.issue)
      };
    }
    return ticket;
  });

  const total = db.prepare('SELECT COUNT(*) as count FROM tickets WHERE user_id = ?').get(req.user.id);

  res.json({ tickets: ticketsWithDrawTime, total: total.count, page: Number(page), limit: Number(limit) });
});

// 获取统计数据
router.get('/stats', (req, res) => {
  const stats = db.prepare(`
    SELECT
      COALESCE(SUM(cost), 0) as total_cost,
      COALESCE(SUM(prize), 0) as total_prize,
      COUNT(*) as total_tickets,
      SUM(CASE WHEN status = 'won' THEN 1 ELSE 0 END) as won_count,
      SUM(CASE WHEN status = 'lost' THEN 1 ELSE 0 END) as lost_count,
      SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending_count
    FROM tickets WHERE user_id = ?
  `).get(req.user.id);

  res.json({
    totalCost: stats.total_cost,
    totalPrize: stats.total_prize,
    netIncome: stats.total_prize - stats.total_cost,
    totalTickets: stats.total_tickets,
    wonCount: stats.won_count || 0,
    lostCount: stats.lost_count || 0,
    pendingCount: stats.pending_count || 0
  });
});

// 添加彩票
router.post('/', (req, res) => {
  const { type, game, issue, numbers, bet_count, multiple, is_additional, cost, image_path } = req.body;

  if (!type || !game || !cost) {
    return res.status(400).json({ error: '缺少必要字段' });
  }

  const stmt = db.prepare(`
    INSERT INTO tickets (user_id, type, game, issue, numbers, bet_count, multiple, is_additional, cost, image_path)
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  `);

  const result = stmt.run(
    req.user.id, type, game, issue || null,
    numbers ? JSON.stringify(numbers) : null,
    bet_count || 1, multiple || 1, is_additional ? 1 : 0, cost, image_path || null
  );

  res.json({ id: result.lastInsertRowid, message: '添加成功' });
});

// 更新彩票
router.put('/:id', (req, res) => {
  const { id } = req.params;
  const { type, game, issue, numbers, bet_count, multiple, is_additional, cost, prize, status } = req.body;

  const ticket = db.prepare('SELECT * FROM tickets WHERE id = ? AND user_id = ?').get(id, req.user.id);
  if (!ticket) {
    return res.status(404).json({ error: '彩票不存在' });
  }

  const stmt = db.prepare(`
    UPDATE tickets SET type = ?, game = ?, issue = ?, numbers = ?, bet_count = ?, multiple = ?, is_additional = ?, cost = ?, prize = ?, status = ?
    WHERE id = ?
  `);
  stmt.run(
    type ?? ticket.type,
    game ?? ticket.game,
    issue !== undefined ? issue : ticket.issue,
    numbers ? JSON.stringify(numbers) : ticket.numbers,
    bet_count ?? ticket.bet_count,
    multiple ?? ticket.multiple,
    is_additional !== undefined ? (is_additional ? 1 : 0) : ticket.is_additional,
    cost ?? ticket.cost,
    prize ?? ticket.prize,
    status ?? ticket.status,
    id
  );

  res.json({ message: '更新成功' });
});

// 删除彩票
router.delete('/:id', (req, res) => {
  const { id } = req.params;
  const ticketId = Number(id);

  console.log('删除请求:', { id, ticketId, userId: req.user.id });

  if (isNaN(ticketId)) {
    return res.status(400).json({ error: '无效的ID' });
  }

  try {
    const result = db.prepare('DELETE FROM tickets WHERE id = ? AND user_id = ?').run(ticketId, req.user.id);
    console.log('删除结果:', result);

    if (result.changes === 0) {
      return res.status(404).json({ error: '彩票不存在' });
    }

    res.json({ message: '删除成功' });
  } catch (err) {
    console.error('删除错误:', err);
    res.status(500).json({ error: '删除失败: ' + err.message });
  }
});

module.exports = router;
