const { Op, sequelize } = require('sequelize');
const { sequelize: dbSequelize } = require('../config/database');
const User = require('../models/User');
const InsuranceApplication = require('../models/InsuranceApplication');
const Policy = require('../models/Policy');
const Claim = require('../models/Claim');
const OperationLog = require('../models/OperationLog');

/**
 * 获取仪表板统计数据
 */
const getStats = async (req, res) => {
  try {
    console.log('获取仪表板统计数据...');

    // 获取今日日期范围
    const today = new Date();
    const startOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    const endOfDay = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1);

    // 获取本月日期范围
    const startOfMonth = new Date(today.getFullYear(), today.getMonth(), 1);
    const endOfMonth = new Date(today.getFullYear(), today.getMonth() + 1, 1);

    // 并行查询各种统计数据
    const [
      totalApplications,
      todayApplications,
      monthApplications,
      totalPolicies,
      activePolicies,
      totalClaims,
      pendingClaims,
      totalUsers,
      recentActivities
    ] = await Promise.all([
      // 总申请数
      InsuranceApplication.count(),
      
      // 今日申请数
      InsuranceApplication.count({
        where: {
          created_at: {
            [Op.gte]: startOfDay,
            [Op.lt]: endOfDay
          }
        }
      }),
      
      // 本月申请数
      InsuranceApplication.count({
        where: {
          created_at: {
            [Op.gte]: startOfMonth,
            [Op.lt]: endOfMonth
          }
        }
      }),
      
      // 总保单数
      Policy.count(),
      
      // 有效保单数
      Policy.count({
        where: {
          policy_status: 'active'
        }
      }),
      
      // 总理赔数
      Claim.count(),
      
      // 待处理理赔数
      Claim.count({
        where: {
          claim_status: 'pending'
        }
      }),
      
      // 总用户数
      User.count(),
      
      // 最近活动（从系统日志获取）
      OperationLog.findAll({
        limit: 10,
        order: [['created_at', 'DESC']],
        attributes: ['id', 'operation_type', 'operation_content', 'created_at', 'user_id']
      })
    ]);

    // 计算增长率（简化计算，实际应该与上一期间对比）
    const applicationGrowthRate = todayApplications > 0 ? 
      ((todayApplications / Math.max(monthApplications - todayApplications, 1)) * 100).toFixed(1) : 0;
    
    const policyGrowthRate = activePolicies > 0 ? 
      ((activePolicies / Math.max(totalPolicies - activePolicies, 1)) * 100).toFixed(1) : 0;

    const statsData = {
      // 核心指标
      totalApplications,
      todayApplications,
      monthApplications,
      applicationGrowthRate: parseFloat(applicationGrowthRate),
      
      totalPolicies,
      activePolicies,
      policyGrowthRate: parseFloat(policyGrowthRate),
      
      totalClaims,
      pendingClaims,
      claimProcessingRate: totalClaims > 0 ? 
        (((totalClaims - pendingClaims) / totalClaims) * 100).toFixed(1) : 0,
      
      totalUsers,
      
      // 快速统计
      quickStats: {
        newApplicationsToday: todayApplications,
        pendingReviews: pendingClaims,
        activeUsers: totalUsers, // 简化处理，实际应该查询活跃用户
        systemAlerts: 0 // 简化处理，实际应该查询系统告警
      }
    };

    console.log('统计数据获取成功:', statsData);

    res.json({
      code: 200,
      status: 'success',
      data: statsData,
      message: '获取仪表板统计数据成功',
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    console.error('获取仪表板统计数据失败:', error);
    res.status(500).json({
      code: 500,
      status: 'error',
      data: null,
      message: '获取仪表板统计数据失败',
      timestamp: new Date().toISOString()
    });
  }
};

/**
 * 获取最近活动
 */
const getRecentActivities = async (req, res) => {
  try {
    console.log('获取最近活动数据...');

    const { limit = 20 } = req.query;

    // 从系统日志获取最近活动
    const activities = await OperationLog.findAll({
      limit: parseInt(limit),
      order: [['created_at', 'DESC']],
      attributes: ['id', 'operation_type', 'operation_content', 'created_at', 'user_id']
    });

    // 格式化活动数据
    const formattedActivities = activities.map(activity => ({
      id: activity.id,
      type: activity.operation_type,
      title: activity.operation_content,
      description: `操作用户: ${activity.user_id || '系统'}`,
      timestamp: activity.created_at,
      user: activity.user_id,
      level: activity.operation_type
    }));

    console.log(`获取到 ${formattedActivities.length} 条最近活动`);

    res.json({
      code: 200,
      status: 'success',
      data: formattedActivities,
      message: '获取最近活动成功',
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    console.error('获取最近活动失败:', error);
    res.status(500).json({
      code: 500,
      status: 'error',
      data: null,
      message: '获取最近活动失败',
      timestamp: new Date().toISOString()
    });
  }
};

/**
 * 获取图表数据
 */
const getChartData = async (req, res) => {
  try {
    console.log('获取图表数据...');

    const { type = 'applications', period = '7d' } = req.query;

    let startDate;
    const endDate = new Date();

    // 根据时间周期设置开始日期
    switch (period) {
      case '7d':
        startDate = new Date(endDate.getTime() - 7 * 24 * 60 * 60 * 1000);
        break;
      case '30d':
        startDate = new Date(endDate.getTime() - 30 * 24 * 60 * 60 * 1000);
        break;
      case '90d':
        startDate = new Date(endDate.getTime() - 90 * 24 * 60 * 60 * 1000);
        break;
      default:
        startDate = new Date(endDate.getTime() - 7 * 24 * 60 * 60 * 1000);
    }

    let chartData = [];

    if (type === 'applications') {
      // 获取申请数据趋势
      const applications = await InsuranceApplication.findAll({
        where: {
          created_at: {
            [Op.gte]: startDate,
            [Op.lte]: endDate
          }
        },
        attributes: [
          [dbSequelize.fn('DATE', dbSequelize.col('created_at')), 'date'],
          [dbSequelize.fn('COUNT', dbSequelize.col('id')), 'count']
        ],
        group: [dbSequelize.fn('DATE', dbSequelize.col('created_at'))],
        order: [[dbSequelize.fn('DATE', dbSequelize.col('created_at')), 'ASC']]
      });

      chartData = applications.map(item => ({
        date: item.dataValues.date,
        value: parseInt(item.dataValues.count)
      }));
    } else if (type === 'policies') {
      // 获取保单数据趋势
      const policies = await Policy.findAll({
        where: {
          created_at: {
            [Op.gte]: startDate,
            [Op.lte]: endDate
          }
        },
        attributes: [
          [dbSequelize.fn('DATE', dbSequelize.col('created_at')), 'date'],
          [dbSequelize.fn('COUNT', dbSequelize.col('id')), 'count']
        ],
        group: [dbSequelize.fn('DATE', dbSequelize.col('created_at'))],
        order: [[dbSequelize.fn('DATE', dbSequelize.col('created_at')), 'ASC']]
      });

      chartData = policies.map(item => ({
        date: item.dataValues.date,
        value: parseInt(item.dataValues.count)
      }));
    } else if (type === 'claims') {
      // 获取理赔数据趋势
      const claims = await Claim.findAll({
        where: {
          created_at: {
            [Op.gte]: startDate,
            [Op.lte]: endDate
          }
        },
        attributes: [
          [dbSequelize.fn('DATE', dbSequelize.col('created_at')), 'date'],
          [dbSequelize.fn('COUNT', dbSequelize.col('id')), 'count']
        ],
        group: [dbSequelize.fn('DATE', dbSequelize.col('created_at'))],
        order: [[dbSequelize.fn('DATE', dbSequelize.col('created_at')), 'ASC']]
      });

      chartData = claims.map(item => ({
        date: item.dataValues.date,
        value: parseInt(item.dataValues.count)
      }));
    } else if (type === 'policy_status') {
      // 获取保单状态分布数据
      const policyStatusData = await Policy.findAll({
        attributes: [
          'policy_status',
          [dbSequelize.fn('COUNT', dbSequelize.col('id')), 'count']
        ],
        group: ['policy_status'],
        order: [[dbSequelize.fn('COUNT', dbSequelize.col('id')), 'DESC']]
      });

      chartData = policyStatusData.map(item => ({
        status: item.dataValues.policy_status,
        count: parseInt(item.dataValues.count)
      }));
    }

    console.log(`获取到 ${chartData.length} 条图表数据`);

    res.json({
      code: 200,
      status: 'success',
      data: chartData,
      message: '获取图表数据成功',
      timestamp: new Date().toISOString()
    });

  } catch (error) {
    console.error('获取图表数据失败:', error);
    res.status(500).json({
      code: 500,
      status: 'error',
      data: null,
      message: '获取图表数据失败',
      timestamp: new Date().toISOString()
    });
  }
};

module.exports = {
  getStats,
  getRecentActivities,
  getChartData
};