/**
 * 推广活动控制器
 * @module controllers/promotion/activityController
 */

const db = require('../../config/database');

/**
 * 获取推广活动列表
 * @function getActivities
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件next函数
 */
exports.getActivities = async (req, res, next) => {
  try {
    const {
      page = 1,
      pageSize = 20,
      name = '',
      status = ''
    } = req.query;

    const offset = (page - 1) * pageSize;
    const limit = parseInt(pageSize);

    let whereConditions = [];
    let queryParams = [];

    if (name) {
      whereConditions.push('name LIKE ?');
      queryParams.push(`%${name}%`);
    }

    if (status) {
      whereConditions.push('status = ?');
      queryParams.push(status);
    }

    const whereClause = whereConditions.length > 0 
      ? `WHERE ${whereConditions.join(' AND ')}` 
      : '';

    // 获取总数
    const countSql = `SELECT COUNT(*) as total FROM promotion_activities ${whereClause}`;
    const countResult = await db.query(countSql, queryParams);
    const total = countResult[0].total;

    // 获取数据
    const dataSql = `
      SELECT 
        id, name, description, reward_type, reward_amount, status,
        start_time, end_time, max_participants, current_participants,
        created_at, updated_at
      FROM promotion_activities 
      ${whereClause}
      ORDER BY created_at DESC 
      LIMIT ? OFFSET ?
    `;

    const dataParams = [...queryParams, limit, offset];
    const activities = await db.query(dataSql, dataParams);

    res.json({
      success: true,
      code: 200,
      message: '获取成功',
      data: activities,
      pagination: {
        current: parseInt(page),
        pageSize: limit,
        total,
        totalPages: Math.ceil(total / limit)
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取推广活动详情
 * @function getActivity
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件next函数
 */
exports.getActivity = async (req, res, next) => {
  try {
    const { id } = req.params;

    const sql = `
      SELECT 
        id, name, description, reward_type, reward_amount, status,
        start_time, end_time, max_participants, current_participants,
        created_at, updated_at
      FROM promotion_activities 
      WHERE id = ?
    `;

    const activities = await db.query(sql, [id]);

    if (activities.length === 0) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '推广活动不存在'
      });
    }

    res.json({
      success: true,
      code: 200,
      message: '获取成功',
      data: activities[0]
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 创建推广活动
 * @function createActivity
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件next函数
 */
exports.createActivity = async (req, res, next) => {
  try {
    const {
      name,
      description,
      reward_type,
      reward_amount,
      status = 'upcoming',
      start_time,
      end_time,
      max_participants = 0
    } = req.body;

    // 验证必填字段
    if (!name || !reward_type || !reward_amount || !start_time || !end_time) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '缺少必填字段'
      });
    }

    const sql = `
      INSERT INTO promotion_activities 
      (name, description, reward_type, reward_amount, status, start_time, end_time, max_participants, current_participants)
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, 0)
    `;

    const result = await db.query(sql, [
      name,
      description,
      reward_type,
      reward_amount,
      status,
      start_time,
      end_time,
      max_participants
    ]);

    // 获取新创建的活动
    const newActivity = await db.query(
      'SELECT * FROM promotion_activities WHERE id = ?',
      [result.insertId]
    );

    res.status(201).json({
      success: true,
      code: 201,
      message: '创建成功',
      data: newActivity[0]
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 更新推广活动
 * @function updateActivity
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件next函数
 */
exports.updateActivity = async (req, res, next) => {
  try {
    const { id } = req.params;
    const updates = req.body;

    // 检查活动是否存在
    const existingActivity = await db.query(
      'SELECT id FROM promotion_activities WHERE id = ?',
      [id]
    );

    if (existingActivity.length === 0) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '推广活动不存在'
      });
    }

    // 构建更新字段
    const updateFields = [];
    const updateValues = [];

    const allowedFields = [
      'name', 'description', 'reward_type', 'reward_amount',
      'status', 'start_time', 'end_time', 'max_participants'
    ];

    Object.keys(updates).forEach(key => {
      if (allowedFields.includes(key) && updates[key] !== undefined) {
        updateFields.push(`${key} = ?`);
        updateValues.push(updates[key]);
      }
    });

    if (updateFields.length === 0) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '没有有效的更新字段'
      });
    }

    updateValues.push(id);

    const sql = `
      UPDATE promotion_activities 
      SET ${updateFields.join(', ')}, updated_at = NOW()
      WHERE id = ?
    `;

    await db.query(sql, updateValues);

    // 获取更新后的活动
    const updatedActivity = await db.query(
      'SELECT * FROM promotion_activities WHERE id = ?',
      [id]
    );

    res.json({
      success: true,
      code: 200,
      message: '更新成功',
      data: updatedActivity[0]
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 删除推广活动
 * @function deleteActivity
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件next函数
 */
exports.deleteActivity = async (req, res, next) => {
  try {
    const { id } = req.params;

    // 检查活动是否存在
    const existingActivity = await db.query(
      'SELECT id FROM promotion_activities WHERE id = ?',
      [id]
    );

    if (existingActivity.length === 0) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '推广活动不存在'
      });
    }

    // 删除活动
    await db.query('DELETE FROM promotion_activities WHERE id = ?', [id]);

    res.json({
      success: true,
      code: 200,
      message: '删除成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 暂停推广活动
 * @function pauseActivity
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件next函数
 */
exports.pauseActivity = async (req, res, next) => {
  try {
    const { id } = req.params;

    // 检查活动是否存在
    const existingActivity = await db.query(
      'SELECT id, status FROM promotion_activities WHERE id = ?',
      [id]
    );

    if (existingActivity.length === 0) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '推广活动不存在'
      });
    }

    const currentStatus = existingActivity[0].status;

    if (currentStatus !== 'active') {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '只有活跃状态的活动可以暂停'
      });
    }

    // 更新状态为暂停
    await db.query(
      'UPDATE promotion_activities SET status = "paused", updated_at = NOW() WHERE id = ?',
      [id]
    );

    res.json({
      success: true,
      code: 200,
      message: '暂停成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 恢复推广活动
 * @function resumeActivity
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件next函数
 */
exports.resumeActivity = async (req, res, next) => {
  try {
    const { id } = req.params;

    // 检查活动是否存在
    const existingActivity = await db.query(
      'SELECT id, status FROM promotion_activities WHERE id = ?',
      [id]
    );

    if (existingActivity.length === 0) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '推广活动不存在'
      });
    }

    const currentStatus = existingActivity[0].status;

    if (currentStatus !== 'paused') {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '只有暂停状态的活动可以恢复'
      });
    }

    // 更新状态为活跃
    await db.query(
      'UPDATE promotion_activities SET status = "active", updated_at = NOW() WHERE id = ?',
      [id]
    );

    res.json({
      success: true,
      code: 200,
      message: '恢复成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取推广统计数据
 * @function getStatistics
 * @param {Object} req - Express请求对象
 * @param {Object} res - Express响应对象
 * @param {Function} next - Express中间件next函数
 */
exports.getStatistics = async (req, res, next) => {
  try {
    // 获取活动总数
    const totalActivities = await db.query(
      'SELECT COUNT(*) as count FROM promotion_activities'
    );

    // 获取活跃活动数
    const activeActivities = await db.query(
      'SELECT COUNT(*) as count FROM promotion_activities WHERE status = "active"'
    );

    // 获取奖励记录总数
    const totalRewards = await db.query(
      'SELECT COUNT(*) as count FROM promotion_rewards'
    );

    // 获取已发放奖励数
    const issuedRewards = await db.query(
      'SELECT COUNT(*) as count FROM promotion_rewards WHERE status = "issued"'
    );

    // 获取奖励总金额
    const totalAmount = await db.query(`
      SELECT COALESCE(SUM(
        CASE 
          WHEN reward_type = 'cash' THEN reward_amount
          WHEN reward_type = 'points' THEN reward_amount * 0.01 -- 假设1积分=0.01元
          ELSE 0 
        END
      ), 0) as total_amount 
      FROM promotion_rewards 
      WHERE status = 'issued'
    `);

    const statistics = {
      total_activities: totalActivities[0].count,
      active_activities: activeActivities[0].count,
      total_rewards: totalRewards[0].count,
      issued_rewards: issuedRewards[0].count,
      total_amount: parseFloat(totalAmount[0].total_amount)
    };

    res.json({
      success: true,
      code: 200,
      message: '获取成功',
      data: statistics
    });
  } catch (error) {
    next(error);
  }
};