// 管理员控制器
const Admin = require('../../models/admin');
const AdminService = require('../../services/admin');
const jwt = require('jsonwebtoken');
const { query } = require('../../config/database');

// 生成JWT token
const generateToken = (admin) => {
  return jwt.sign(
    { id: admin.id, username: admin.username, role: admin.role },
    process.env.JWT_SECRET || 'admin-secret-key',
    { expiresIn: process.env.JWT_EXPIRES_IN || '24h' }
  );
};

// 管理员登录
exports.login = async (req, res, next) => {
  try {
    const { username, password } = req.body;

    // 验证输入
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '用户名和密码不能为空'
      });
    }

    // 查找管理员
    const admin = await Admin.findByUsername(username);
    if (!admin) {
      return res.status(401).json({
        success: false,
        code: 401,
        message: '用户名或密码错误'
      });
    }

    // 验证密码
    const isPasswordValid = await admin.verifyPassword(password);
    if (!isPasswordValid) {
      return res.status(401).json({
        success: false,
        code: 401,
        message: '用户名或密码错误'
      });
    }

    // 更新最后登录时间
    await admin.updateLastLogin();

    // 生成token
    const token = generateToken(admin);

    res.status(200).json({
      success: true,
      code: 200,
      message: '登录成功',
      data: {
        admin: admin.toSafeObject(),
        token
      }
    });
  } catch (error) {
    next(error);
  }
};

// 获取用户增长数据
exports.getUserGrowth = async (req, res, next) => {
  try {
    const { days = 7 } = req.query;
    
    // 验证参数
    const daysNum = parseInt(days);
    if (isNaN(daysNum) || daysNum < 1 || daysNum > 365) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '天数参数无效，必须在1-365之间'
      });
    }

    const growthData = await getUserGrowthData(daysNum);
    const summary = calculateGrowthSummary(growthData);

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

// 获取用户增长数据的辅助函数
const getUserGrowthData = async (days) => {
  try {
    // 生成日期范围
    const dates = [];
    const today = new Date();
    for (let i = days - 1; i >= 0; i--) {
      const date = new Date(today);
      date.setDate(today.getDate() - i);
      dates.push(date.toISOString().split('T')[0]);
    }

    // 查询每日新增用户数
    const dailyNewUsersQuery = `
      SELECT 
        DATE(created_at) as date,
        COUNT(*) as newUsers
      FROM users 
      WHERE created_at >= DATE_SUB(CURDATE(), INTERVAL ? DAY)
      GROUP BY DATE(created_at)
      ORDER BY date ASC
    `;
    
    const dailyNewUsersResult = await query(dailyNewUsersQuery, [days]);
    
    // 确保dailyNewUsers是数组
    const dailyNewUsers = Array.isArray(dailyNewUsersResult) ? dailyNewUsersResult : [];

    // 查询总用户数（截止到每一天）
    const growthData = [];
    let cumulativeUsers = 0;

    // 获取起始日期之前的用户总数
    const initialUsersQuery = `
      SELECT COUNT(*) as count 
      FROM users 
      WHERE created_at < DATE_SUB(CURDATE(), INTERVAL ? DAY)
    `;
    const initialUsersResult = await query(initialUsersQuery, [days]);
    const initialResult = initialUsersResult || [];
    cumulativeUsers = initialResult[0]?.count || 0;

    // 构建每日数据
    for (const date of dates) {
      // 将数据库返回的日期转换为字符串进行比较
      const dayData = dailyNewUsers.find(d => {
        const dbDate = d.date instanceof Date ? d.date.toISOString().split('T')[0] : d.date;
        return dbDate === date;
      });
      const newUsers = dayData ? parseInt(dayData.newUsers) : 0;
      cumulativeUsers += newUsers;

      growthData.push({
        date,
        newUsers,
        totalUsers: cumulativeUsers
      });
    }

    return growthData;
  } catch (error) {
    console.error('获取用户增长数据失败:', error);
    throw new Error('获取用户增长数据失败');
  }
};

// 计算增长汇总数据
const calculateGrowthSummary = (growthData) => {
  if (!growthData || growthData.length === 0) {
    return {
      totalNewUsers: 0,
      averageDaily: 0,
      growthRate: 0
    };
  }

  const totalNewUsers = growthData.reduce((sum, day) => sum + day.newUsers, 0);
  const averageDaily = totalNewUsers / growthData.length;
  
  // 计算增长率（相对于期初用户数）
  const initialUsers = growthData[0].totalUsers - growthData[0].newUsers;
  const growthRate = initialUsers > 0 ? (totalNewUsers / initialUsers) * 100 : 0;

  return {
    totalNewUsers,
    averageDaily: Math.round(averageDaily * 100) / 100, // 保留两位小数
    growthRate: Math.round(growthRate * 100) / 100 // 保留两位小数
  };
};

// 获取当前管理员信息
exports.getProfile = async (req, res, next) => {
  try {
    const admin = await Admin.findById(req.admin.id);
    if (!admin) {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '管理员不存在'
      });
    }

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

// 获取仪表板数据
exports.getDashboard = async (req, res, next) => {
  try {
    // 获取统计数据
    const statistics = await getDashboardStatistics();
    
    // 获取最近活动
    const recentActivities = await getRecentActivities();
    
    // 获取系统信息
    const systemInfo = getSystemInfo();

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

// 获取仪表板统计数据
const getDashboardStatistics = async () => {
  try {
    const today = new Date();
    const todayStart = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    const todayEnd = new Date(todayStart.getTime() + 24 * 60 * 60 * 1000);

    // 总用户数
    const [totalUsersResult] = await query('SELECT COUNT(*) as count FROM users');
    const totalUsers = totalUsersResult.count;

    // 今日新增用户
    const [todayUsersResult] = await query(
      'SELECT COUNT(*) as count FROM users WHERE created_at >= ? AND created_at < ?',
      [todayStart, todayEnd]
    );
    const todayNewUsers = todayUsersResult.count;

    // 总动物数
    const [totalAnimalsResult] = await query('SELECT COUNT(*) as count FROM animals');
    const totalAnimals = totalAnimalsResult.count;

    // 今日新增动物
    const [todayAnimalsResult] = await query(
      'SELECT COUNT(*) as count FROM animals WHERE created_at >= ? AND created_at < ?',
      [todayStart, todayEnd]
    );
    const todayNewAnimals = todayAnimalsResult.count;

    // 总旅行数
    const [totalTravelsResult] = await query('SELECT COUNT(*) as count FROM travels');
    const totalTravels = totalTravelsResult.count;

    // 今日新增旅行
    const [todayTravelsResult] = await query(
      'SELECT COUNT(*) as count FROM travels WHERE created_at >= ? AND created_at < ?',
      [todayStart, todayEnd]
    );
    const todayNewTravels = todayTravelsResult.count;

    // 总认领数
    const [totalClaimsResult] = await query('SELECT COUNT(*) as count FROM animal_claims');
    const totalClaims = totalClaimsResult.count;

    // 今日新增认领
    const [todayClaimsResult] = await query(
      'SELECT COUNT(*) as count FROM animal_claims WHERE created_at >= ? AND created_at < ?',
      [todayStart, todayEnd]
    );
    const todayNewClaims = todayClaimsResult.count;

    return {
      totalUsers,
      totalAnimals,
      totalTravels,
      totalClaims,
      todayNewUsers,
      todayNewAnimals,
      todayNewTravels,
      todayNewClaims
    };
  } catch (error) {
    console.error('获取统计数据失败:', error);
    // 返回默认值
    return {
      totalUsers: 0,
      totalAnimals: 0,
      totalTravels: 0,
      totalClaims: 0,
      todayNewUsers: 0,
      todayNewAnimals: 0,
      todayNewTravels: 0,
      todayNewClaims: 0
    };
  }
};

// 获取最近活动
const getRecentActivities = async () => {
  try {
    const activities = [];

    // 最近用户注册
    const recentUsers = await query(`
      SELECT id, nickname, created_at 
      FROM users 
      WHERE status != 'banned' 
      ORDER BY created_at DESC 
      LIMIT 5
    `);

    recentUsers.forEach(user => {
      activities.push({
        type: 'user_register',
        description: `用户 ${user.nickname} 注册了账号`,
        timestamp: user.created_at,
        user: {
          id: user.id,
          nickname: user.nickname
        }
      });
    });

    // 最近动物添加
    const recentAnimals = await query(`
      SELECT a.id, a.name, a.created_at, u.id as user_id, u.nickname as user_nickname
      FROM animals a
      LEFT JOIN users u ON a.farmer_id = u.id
      ORDER BY a.created_at DESC 
      LIMIT 5
    `);

    recentAnimals.forEach(animal => {
      activities.push({
        type: 'animal_add',
        description: `${animal.user_nickname || '用户'} 添加了动物 ${animal.name}`,
        timestamp: animal.created_at,
        user: {
          id: animal.user_id,
          nickname: animal.user_nickname
        }
      });
    });

    // 按时间排序
    activities.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));

    return activities.slice(0, 10); // 返回最近10条活动
  } catch (error) {
    console.error('获取最近活动失败:', error);
    return [];
  }
};

// 获取系统信息
const getSystemInfo = () => {
  const uptime = process.uptime();
  const uptimeHours = Math.floor(uptime / 3600);
  const uptimeMinutes = Math.floor((uptime % 3600) / 60);
  
  return {
    serverTime: new Date().toISOString(),
    uptime: `${uptimeHours}小时${uptimeMinutes}分钟`,
    version: process.env.APP_VERSION || '1.0.0',
    environment: process.env.NODE_ENV || 'development'
  };
};

// 获取管理员列表
exports.getList = async (req, res, next) => {
  try {
    const result = await AdminService.getAdminList(req.query);

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

// 创建管理员
exports.create = async (req, res, next) => {
  try {
    const { username, password, email, nickname, role } = req.body;

    // 验证必填字段
    if (!username || !password) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '用户名和密码不能为空'
      });
    }

    // 创建管理员
    const adminData = {
      username,
      password,
      email: email || null,
      nickname: nickname || null,
      role: role || 'admin',
      status: 1
    };

    const admin = await AdminService.createAdmin(adminData);

    res.status(201).json({
      success: true,
      code: 201,
      message: '创建成功',
      data: {
        admin
      }
    });
  } catch (error) {
    if (error.message === '用户名已存在') {
      return res.status(409).json({
        success: false,
        code: 409,
        message: '用户名已存在'
      });
    }
    next(error);
  }
};

// 更新管理员
exports.update = async (req, res, next) => {
  try {
    const { id } = req.params;
    const updateData = req.body;

    // 不能修改自己角色
    if (req.admin.id == id && updateData.role) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '不能修改自己的角色'
      });
    }

    const admin = await AdminService.updateAdmin(id, updateData);

    res.status(200).json({
      success: true,
      code: 200,
      message: '更新成功',
      data: {
        admin
      }
    });
  } catch (error) {
    if (error.message === '管理员不存在') {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '管理员不存在'
      });
    }
    next(error);
  }
};

// 删除管理员
exports.delete = async (req, res, next) => {
  try {
    const { id } = req.params;

    // 不能删除自己
    if (req.admin.id == id) {
      return res.status(400).json({
        success: false,
        code: 400,
        message: '不能删除自己'
      });
    }

    await AdminService.deleteAdmin(id);

    res.status(200).json({
      success: true,
      code: 200,
      message: '删除成功'
    });
  } catch (error) {
    if (error.message === '管理员不存在') {
      return res.status(404).json({
        success: false,
        code: 404,
        message: '管理员不存在'
      });
    }
    next(error);
  }
};