// 管理员用户管理控制器
const User = require('../../models/user');
const UserService = require('../../services/user');
const { query } = require('../../config/database');

/**
 * 获取用户列表
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @param {Function} next - 下一个中间件
 */
exports.getUserList = async (req, res, next) => {
  try {
    const {
      page = 1,
      pageSize = 10,
      keyword = '',
      userType = '',
      status = '',
      startDate = '',
      endDate = '',
      sortField = 'created_at',
      sortOrder = 'desc'
    } = req.query;

    // 构建查询条件
    let whereClause = 'WHERE 1=1';
    const params = [];

    // 关键词搜索
    if (keyword) {
      whereClause += ' AND (nickname LIKE ? OR phone LIKE ? OR email LIKE ?)';
      const searchTerm = `%${keyword}%`;
      params.push(searchTerm, searchTerm, searchTerm);
    }

    // 用户类型筛选
    if (userType) {
      whereClause += ' AND user_type = ?';
      params.push(userType);
    }

    // 状态筛选
    if (status) {
      whereClause += ' AND status = ?';
      params.push(status);
    }

    // 日期范围筛选
    if (startDate) {
      whereClause += ' AND created_at >= ?';
      params.push(startDate);
    }
    if (endDate) {
      whereClause += ' AND created_at <= ?';
      params.push(endDate + ' 23:59:59');
    }

    // 计算总数
    const countSql = `SELECT COUNT(*) as total FROM users ${whereClause}`;
    const countResult = await query(countSql, params);
    const total = countResult[0].total;

    // 分页查询
    const offset = (page - 1) * pageSize;
    const orderBy = `ORDER BY ${sortField} ${sortOrder.toUpperCase()}`;
    const listSql = `
      SELECT 
        id, nickname, phone, email, user_type, status, 
        travel_count, animal_claim_count, points, level,
        last_login_at, created_at, updated_at
      FROM users 
      ${whereClause} 
      ${orderBy} 
      LIMIT ? OFFSET ?
    `;
    
    const listParams = [...params, parseInt(pageSize), offset];
    const users = await query(listSql, listParams);

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

/**
 * 获取用户详情
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @param {Function} next - 下一个中间件
 */
exports.getUserDetail = async (req, res, next) => {
  try {
    const { userId } = req.params;

    // 获取用户基本信息
    const userSql = `
      SELECT 
        id, openid, nickname, avatar, gender, birthday, phone, email,
        province, city, travel_count, animal_claim_count, points, level,
        status, last_login_at, created_at, updated_at
      FROM users 
      WHERE id = ?
    `;
    const userResult = await query(userSql, [userId]);
    
    if (userResult.length === 0) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '用户不存在'
      });
    }

    const user = userResult[0];

    // 获取用户兴趣
    const interestsSql = `
      SELECT ui.interest_name, ui.created_at
      FROM user_interests ui
      WHERE ui.user_id = ?
    `;
    const interests = await query(interestsSql, [userId]);

    // 获取用户最近的旅行记录
    const travelsSql = `
      SELECT id, title, destination, start_date, end_date, status, created_at
      FROM travels
      WHERE user_id = ?
      ORDER BY created_at DESC
      LIMIT 5
    `;
    const travels = await query(travelsSql, [userId]);

    // 获取用户最近的认领记录
    const claimsSql = `
      SELECT ac.id, a.name as animal_name, ac.status, ac.created_at
      FROM animal_claims ac
      JOIN animals a ON ac.animal_id = a.id
      WHERE ac.user_id = ?
      ORDER BY ac.created_at DESC
      LIMIT 5
    `;
    const claims = await query(claimsSql, [userId]);

    res.status(200).json({
      success: true,
      code: 200,
      message: '获取成功',
      data: {
        user: {
          ...user,
          interests: interests.map(i => i.interest_name),
          recentTravels: travels,
          recentClaims: claims
        }
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 更新用户状态
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @param {Function} next - 下一个中间件
 */
exports.updateUserStatus = async (req, res, next) => {
  try {
    const { userId } = req.params;
    const { status, reason } = req.body;

    // 验证状态值
    const validStatuses = ['active', 'inactive', 'banned'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '无效的状态值'
      });
    }

    // 检查用户是否存在
    const checkSql = 'SELECT id, status FROM users WHERE id = ?';
    const checkResult = await query(checkSql, [userId]);
    
    if (checkResult.length === 0) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '用户不存在'
      });
    }

    // 更新用户状态
    const updateSql = 'UPDATE users SET status = ?, updated_at = NOW() WHERE id = ?';
    await query(updateSql, [status, userId]);

    // 记录操作日志
    const logSql = `
      INSERT INTO admin_operation_logs (admin_id, operation_type, target_type, target_id, operation_detail, created_at)
      VALUES (?, 'update_user_status', 'user', ?, ?, NOW())
    `;
    const operationDetail = JSON.stringify({
      old_status: checkResult[0].status,
      new_status: status,
      reason: reason || '无'
    });
    await query(logSql, [req.admin.id, userId, operationDetail]);

    res.status(200).json({
      success: true,
      code: 200,
      message: '状态更新成功'
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 批量更新用户状态
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @param {Function} next - 下一个中间件
 */
exports.batchUpdateUserStatus = async (req, res, next) => {
  try {
    const { userIds, status, reason } = req.body;

    // 验证输入
    if (!Array.isArray(userIds) || userIds.length === 0) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '用户ID列表不能为空'
      });
    }

    const validStatuses = ['active', 'inactive', 'banned'];
    if (!validStatuses.includes(status)) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '无效的状态值'
      });
    }

    // 批量更新
    const placeholders = userIds.map(() => '?').join(',');
    const updateSql = `UPDATE users SET status = ?, updated_at = NOW() WHERE id IN (${placeholders})`;
    const updateParams = [status, ...userIds];
    
    const result = await query(updateSql, updateParams);

    // 记录操作日志
    const logSql = `
      INSERT INTO admin_operation_logs (admin_id, operation_type, target_type, target_id, operation_detail, created_at)
      VALUES (?, 'batch_update_user_status', 'user', ?, ?, NOW())
    `;
    const operationDetail = JSON.stringify({
      user_ids: userIds,
      new_status: status,
      reason: reason || '无',
      affected_rows: result.affectedRows
    });
    await query(logSql, [req.admin.id, 0, operationDetail]);

    res.status(200).json({
      success: true,
      code: 200,
      message: `成功更新 ${result.affectedRows} 个用户的状态`
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 获取用户统计信息
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @param {Function} next - 下一个中间件
 */
exports.getUserStatistics = async (req, res, next) => {
  try {
    const { period = '7d' } = req.query;

    // 基础统计
    const basicStatsSql = `
      SELECT 
        COUNT(*) as total_users,
        COUNT(CASE WHEN status = 'active' THEN 1 END) as active_users,
        COUNT(CASE WHEN status = 'inactive' THEN 1 END) as inactive_users,
        COUNT(CASE WHEN status = 'banned' THEN 1 END) as banned_users,
        COUNT(CASE WHEN user_type = 'farmer' THEN 1 END) as farmers,
        COUNT(CASE WHEN user_type = 'merchant' THEN 1 END) as merchants,
        COUNT(CASE WHEN DATE(created_at) = CURDATE() THEN 1 END) as new_users_today,
        COUNT(CASE WHEN DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 7 DAY) THEN 1 END) as new_users_week,
        COUNT(CASE WHEN DATE(created_at) >= DATE_SUB(CURDATE(), INTERVAL 30 DAY) THEN 1 END) as new_users_month
      FROM users
    `;
    const basicStats = await query(basicStatsSql);

    // 用户等级分布
    const levelStatsSql = `
      SELECT 
        level,
        COUNT(*) as count
      FROM users
      GROUP BY level
    `;
    const levelStats = await query(levelStatsSql);

    // 根据时间周期获取趋势数据
    let trendSql;
    let trendDays;
    
    switch (period) {
      case '30d':
        trendDays = 30;
        break;
      case '90d':
        trendDays = 90;
        break;
      default:
        trendDays = 7;
    }

    trendSql = `
      SELECT 
        DATE(created_at) as date,
        COUNT(*) as new_users,
        COUNT(CASE WHEN user_type = 'farmer' THEN 1 END) as new_farmers,
        COUNT(CASE WHEN user_type = 'merchant' THEN 1 END) as new_merchants
      FROM users
      WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL ${trendDays} DAY)
      GROUP BY DATE(created_at)
      ORDER BY date ASC
    `;
    const trendData = await query(trendSql);

    // 活跃用户统计（最近30天有登录的用户）
    const activeUsersSql = `
      SELECT COUNT(*) as active_users_30d
      FROM users
      WHERE last_login_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    `;
    const activeUsersResult = await query(activeUsersSql);

    res.status(200).json({
      success: true,
      code: 200,
      message: '获取成功',
      data: {
        basicStats: basicStats[0],
        levelDistribution: levelStats,
        trendData,
        activeUsers30d: activeUsersResult[0].active_users_30d
      }
    });
  } catch (error) {
    next(error);
  }
};

/**
 * 导出用户数据
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 * @param {Function} next - 下一个中间件
 */
exports.exportUsers = async (req, res, next) => {
  try {
    const {
      format = 'csv',
      userType = '',
      status = '',
      startDate = '',
      endDate = ''
    } = req.query;

    // 构建查询条件
    let whereClause = 'WHERE 1=1';
    const params = [];

    if (userType) {
      whereClause += ' AND user_type = ?';
      params.push(userType);
    }

    if (status) {
      whereClause += ' AND status = ?';
      params.push(status);
    }

    if (startDate) {
      whereClause += ' AND created_at >= ?';
      params.push(startDate);
    }

    if (endDate) {
      whereClause += ' AND created_at <= ?';
      params.push(endDate + ' 23:59:59');
    }

    // 查询用户数据
    const exportSql = `
      SELECT 
        id, nickname, phone, email, user_type, status, 
        travel_count, animal_claim_count, points, level,
        created_at, last_login_at
      FROM users 
      ${whereClause}
      ORDER BY created_at DESC
    `;
    
    const users = await query(exportSql, params);

    if (format === 'csv') {
      // 生成CSV格式
      const csvHeader = 'ID,昵称,手机号,邮箱,用户类型,状态,旅行次数,认领次数,积分,等级,注册时间,最后登录\n';
      const csvData = users.map(user => {
        return [
          user.id,
          user.nickname || '',
          user.phone || '',
          user.email || '',
          user.user_type || '',
          user.status,
          user.travel_count,
          user.animal_claim_count,
          user.points,
          user.level,
          user.created_at,
          user.last_login_at || ''
        ].join(',');
      }).join('\n');

      res.setHeader('Content-Type', 'text/csv; charset=utf-8');
      res.setHeader('Content-Disposition', `attachment; filename=users_${Date.now()}.csv`);
      res.send('\uFEFF' + csvHeader + csvData); // 添加BOM以支持中文
    } else {
      // 返回JSON格式
      res.status(200).json({
        success: true,
        code: 200,
        message: '导出成功',
        data: {
          users,
          total: users.length
        }
      });
    }

    // 记录操作日志
    const logSql = `
      INSERT INTO admin_operation_logs (admin_id, operation_type, target_type, target_id, operation_detail, created_at)
      VALUES (?, 'export_users', 'user', ?, ?, NOW())
    `;
    const operationDetail = JSON.stringify({
      format,
      filters: { userType, status, startDate, endDate },
      exported_count: users.length
    });
    await query(logSql, [req.admin.id, 0, operationDetail]);

  } catch (error) {
    next(error);
  }
};