const { User, Role, InsuranceApplication, Policy, Claim } = require('../models');
const responseFormat = require('../utils/response');
const { Op } = require('sequelize');

// 获取系统统计信息
const getSystemStats = async (req, res) => {
  try {
    const [
      totalUsers,
      totalRoles,
      totalApplications,
      totalPolicies,
      totalClaims,
      activeUsers,
      pendingApplications,
      approvedApplications,
      activePolicies,
      pendingClaims,
      approvedClaims
    ] = await Promise.all([
      User.count(),
      Role.count(),
      InsuranceApplication.count(),
      Policy.count(),
      Claim.count(),
      User.count({ where: { status: 'active' } }),
      InsuranceApplication.count({ where: { status: 'pending' } }),
      InsuranceApplication.count({ where: { status: 'approved' } }),
      Policy.count({ where: { policy_status: 'active' } }),
      Claim.count({ where: { claim_status: 'pending' } }),
      Claim.count({ where: { claim_status: 'approved' } })
    ]);
    
    // 获取最近7天的数据趋势
    const sevenDaysAgo = new Date();
    sevenDaysAgo.setDate(sevenDaysAgo.getDate() - 7);
    
    const recentStats = await Promise.all([
      User.count({ where: { created_at: { [Op.gte]: sevenDaysAgo } } }),
      InsuranceApplication.count({ where: { created_at: { [Op.gte]: sevenDaysAgo } } }),
      Policy.count({ where: { created_at: { [Op.gte]: sevenDaysAgo } } }),
      Claim.count({ where: { created_at: { [Op.gte]: sevenDaysAgo } } })
    ]);
    
    res.json(responseFormat.success({
      overview: {
        users: totalUsers,
        roles: totalRoles,
        applications: totalApplications,
        policies: totalPolicies,
        claims: totalClaims
      },
      status: {
        active_users: activeUsers,
        pending_applications: pendingApplications,
        approved_applications: approvedApplications,
        active_policies: activePolicies,
        pending_claims: pendingClaims,
        approved_claims: approvedClaims
      },
      recent: {
        new_users: recentStats[0],
        new_applications: recentStats[1],
        new_policies: recentStats[2],
        new_claims: recentStats[3]
      }
    }, '获取系统统计信息成功'));
  } catch (error) {
    console.error('获取系统统计信息错误:', error);
    res.status(500).json(responseFormat.error('获取系统统计信息失败'));
  }
};

// 获取系统日志（模拟）
const getSystemLogs = async (req, res) => {
  try {
    const { page = 1, limit = 50, level, start_date, end_date } = req.query;
    const offset = (page - 1) * limit;
    
    // 模拟日志数据 - 扩展更多有意义的日志记录
    const mockLogs = [
      {
        id: 1,
        level: 'info',
        message: '系统启动成功',
        timestamp: new Date().toISOString(),
        user: 'system'
      },
      {
        id: 2,
        level: 'info',
        message: '数据库连接成功',
        timestamp: new Date(Date.now() - 1000 * 60).toISOString(),
        user: 'system'
      },
      {
        id: 3,
        level: 'warning',
        message: 'Redis连接失败，使用内存缓存',
        timestamp: new Date(Date.now() - 1000 * 120).toISOString(),
        user: 'system'
      },
      {
        id: 4,
        level: 'info',
        message: '用户 admin 登录成功',
        timestamp: new Date(Date.now() - 1000 * 180).toISOString(),
        user: 'admin'
      },
      {
        id: 5,
        level: 'info',
        message: '新增保险申请：车险申请 - 申请人：张三',
        timestamp: new Date(Date.now() - 1000 * 240).toISOString(),
        user: 'zhangsan'
      },
      {
        id: 6,
        level: 'info',
        message: '保单生效：保单号 POL-2024-001 - 投保人：李四',
        timestamp: new Date(Date.now() - 1000 * 300).toISOString(),
        user: 'lisi'
      },
      {
        id: 7,
        level: 'warning',
        message: '理赔申请待审核：理赔号 CLM-2024-001 - 申请人：王五',
        timestamp: new Date(Date.now() - 1000 * 360).toISOString(),
        user: 'wangwu'
      },
      {
        id: 8,
        level: 'info',
        message: '新用户注册：用户名 zhaoliu',
        timestamp: new Date(Date.now() - 1000 * 420).toISOString(),
        user: 'system'
      },
      {
        id: 9,
        level: 'error',
        message: '支付接口调用失败：订单号 ORD-2024-001',
        timestamp: new Date(Date.now() - 1000 * 480).toISOString(),
        user: 'system'
      },
      {
        id: 10,
        level: 'info',
        message: '保险类型更新：新增意外险产品',
        timestamp: new Date(Date.now() - 1000 * 540).toISOString(),
        user: 'admin'
      },
      {
        id: 11,
        level: 'info',
        message: '系统备份完成：数据库备份成功',
        timestamp: new Date(Date.now() - 1000 * 600).toISOString(),
        user: 'system'
      },
      {
        id: 12,
        level: 'warning',
        message: '磁盘空间不足警告：剩余空间 15%',
        timestamp: new Date(Date.now() - 1000 * 660).toISOString(),
        user: 'system'
      },
      {
        id: 13,
        level: 'info',
        message: '理赔审核通过：理赔号 CLM-2024-002 - 赔付金额 ¥5000',
        timestamp: new Date(Date.now() - 1000 * 720).toISOString(),
        user: 'admin'
      },
      {
        id: 14,
        level: 'info',
        message: '保单续费成功：保单号 POL-2024-002 - 续费期限 1年',
        timestamp: new Date(Date.now() - 1000 * 780).toISOString(),
        user: 'system'
      },
      {
        id: 15,
        level: 'error',
        message: '短信发送失败：手机号 138****8888',
        timestamp: new Date(Date.now() - 1000 * 840).toISOString(),
        user: 'system'
      }
    ];
    
    // 简单的过滤逻辑
    let filteredLogs = mockLogs;
    if (level) {
      filteredLogs = filteredLogs.filter(log => log.level === level);
    }
    if (start_date) {
      const startDate = new Date(start_date);
      filteredLogs = filteredLogs.filter(log => new Date(log.timestamp) >= startDate);
    }
    if (end_date) {
      const endDate = new Date(end_date);
      filteredLogs = filteredLogs.filter(log => new Date(log.timestamp) <= endDate);
    }
    
    // 分页
    const paginatedLogs = filteredLogs.slice(offset, offset + parseInt(limit));
    
    res.json(responseFormat.success({
      logs: paginatedLogs,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: filteredLogs.length,
        pages: Math.ceil(filteredLogs.length / parseInt(limit))
      }
    }, '获取系统日志成功'));
  } catch (error) {
    console.error('获取系统日志错误:', error);
    res.status(500).json(responseFormat.error('获取系统日志失败'));
  }
};

// 获取系统配置（模拟）
const getSystemConfig = async (req, res) => {
  try {
    const config = {
      site_name: '保险端口管理系统',
      version: '1.0.0',
      environment: process.env.NODE_ENV || 'development',
      max_file_size: '10MB',
      allowed_file_types: ['jpg', 'jpeg', 'png', 'pdf', 'doc', 'docx'],
      session_timeout: 3600,
      backup_enabled: true,
      backup_schedule: '0 2 * * *', // 每天凌晨2点
      email_notifications: true,
      sms_notifications: false,
      maintenance_mode: false
    };
    
    res.json(responseFormat.success(config, '获取系统配置成功'));
  } catch (error) {
    console.error('获取系统配置错误:', error);
    res.status(500).json(responseFormat.error('获取系统配置失败'));
  }
};

// 更新系统配置（模拟）
const updateSystemConfig = async (req, res) => {
  try {
    const { maintenance_mode, email_notifications, sms_notifications } = req.body;
    
    // 模拟更新配置
    const updatedConfig = {
      maintenance_mode: maintenance_mode !== undefined ? maintenance_mode : false,
      email_notifications: email_notifications !== undefined ? email_notifications : true,
      sms_notifications: sms_notifications !== undefined ? sms_notifications : false,
      updated_at: new Date().toISOString()
    };
    
    res.json(responseFormat.success(updatedConfig, '系统配置更新成功'));
  } catch (error) {
    console.error('更新系统配置错误:', error);
    res.status(500).json(responseFormat.error('更新系统配置失败'));
  }
};

// 备份数据库（模拟）
const backupDatabase = async (req, res) => {
  try {
    // 模拟备份过程
    const backupInfo = {
      id: `backup_${Date.now()}`,
      filename: `backup_${new Date().toISOString().replace(/:/g, '-')}.sql`,
      size: '2.5MB',
      status: 'completed',
      created_at: new Date().toISOString(),
      download_url: '/api/system/backup/download/backup.sql'
    };
    
    res.json(responseFormat.success(backupInfo, '数据库备份成功'));
  } catch (error) {
    console.error('数据库备份错误:', error);
    res.status(500).json(responseFormat.error('数据库备份失败'));
  }
};

// 恢复数据库（模拟）
const restoreDatabase = async (req, res) => {
  try {
    const { backup_id } = req.body;
    
    if (!backup_id) {
      return res.status(400).json(responseFormat.error('备份ID不能为空'));
    }
    
    // 模拟恢复过程
    const restoreInfo = {
      backup_id,
      status: 'completed',
      restored_at: new Date().toISOString(),
      message: '数据库恢复成功'
    };
    
    res.json(responseFormat.success(restoreInfo, '数据库恢复成功'));
  } catch (error) {
    console.error('数据库恢复错误:', error);
    res.status(500).json(responseFormat.error('数据库恢复失败'));
  }
};

module.exports = {
  getSystemStats,
  getSystemLogs,
  getSystemConfig,
  updateSystemConfig,
  backupDatabase,
  restoreDatabase
};