const express = require('express');
const router = express.Router();
const { Activity, Photo, Sponsor, Expense, Registration } = require('../models');
const { upload, uploadFilesToMinio } = require('../middleware/upload');

// 获取活动列表
router.get('/activities', async (req, res) => {
  try {
    const { status } = req.query;
    const where = status ? { status } : {};
    const activities = await Activity.findAll({ where, order: [['startTime', 'DESC']] });
    res.json(activities);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取活动详情
router.get('/activities/:id', async (req, res) => {
  try {
    const activity = await Activity.findByPk(req.params.id);
    // 只返回已审核通过的照片
    const photos = await Photo.findAll({ 
      where: { activityId: req.params.id, status: 'approved' } 
    });
    const sponsors = await Sponsor.findAll({ where: { activityId: req.params.id } });
    const expenses = await Expense.findAll({ where: { activityId: req.params.id } });
    
    res.json({ activity, photos, sponsors, expenses });
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 获取活动经费（公开接口）
router.get('/activities/:id/expenses', async (req, res) => {
  try {
    const expenses = await Expense.findAll({ where: { activityId: req.params.id } });
    res.json(expenses);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 用户上传照片（需要审核）
router.post('/activities/:id/photos', upload.array('photos', 10), async (req, res) => {
  try {
    const { uploadedBy } = req.body;
    const uploaded = await uploadFilesToMinio(req.files);
    const photos = uploaded.map(file => ({
      activityId: req.params.id,
      url: file.url,
      type: /\.(mp4|mov|avi)$/i.test(file.filename) ? 'video' : 'image',
      uploadedBy,
      status: 'pending'
    }));
    const created = await Photo.bulkCreate(photos);
    res.json(created);
  } catch (error) {
    res.status(500).json({ error: error.message });
  }
});

// 用户验证登录
router.post('/auth/verify/:activityId', async (req, res) => {
  try {
    const { phone, carNumber } = req.body;
    const { activityId } = req.params;
    
    console.log('验证请求:', { phone, carNumber, activityId });
    
    if (!phone || !carNumber) {
      return res.status(400).json({ error: '请输入手机号和车牌号' });
    }
    
    const registration = await Registration.findOne({
      where: { 
        activityId, 
        phone, 
        carNumber 
      }
    });
    
    console.log('查询结果:', registration ? '找到' : '未找到');
    
    if (!registration) {
      // 调试：查询该活动下该手机号的所有报名
      const allRegs = await Registration.findAll({
        where: { activityId, phone }
      });
      console.log('该手机号的所有报名:', allRegs.map(r => ({ id: r.id, carNumber: r.carNumber })));
      
      return res.status(404).json({ error: '未找到报名信息，请检查车牌号是否正确' });
    }
    
    res.json({
      registration: {
        id: registration.id,
        name: registration.name,
        phone: registration.phone,
        carNumber: registration.carNumber,
        carModel: registration.carModel,
        status: registration.status,
        activityId: registration.activityId
      }
    });
  } catch (error) {
    console.error('验证错误:', error);
    res.status(500).json({ error: error.message });
  }
});

module.exports = router;
