const { InsuranceApplication, Policy, Claim, InsuranceType, User } = require('../models');
const { Op, Sequelize } = require('sequelize');

// 获取数据仓库概览
const getOverview = async (req, res) => {
  try {
    // 获取总用户数
    const totalUsers = await User.count();
    
    // 获取总申请数
    const totalApplications = await InsuranceApplication.count();
    
    // 获取总保单数
    const totalPolicies = await Policy.count();
    
    // 获取总理赔数
    const totalClaims = await Claim.count();
    
    // 获取总保费收入
    const totalPremium = await Policy.sum('premium_amount') || 0;
    
    // 获取总理赔支出
    const totalClaimAmount = await Claim.sum('claim_amount') || 0;
    
    // 获取活跃保单数
    const activePolicies = await Policy.count({
      where: {
        policy_status: 'active'
      }
    });
    
    // 获取待处理申请数
    const pendingApplications = await InsuranceApplication.count({
      where: {
        status: 'pending'
      }
    });
    
    // 获取待处理理赔数
    const pendingClaims = await Claim.count({
      where: {
        claim_status: 'pending'
      }
    });

    res.json({
      success: true,
      data: {
        totalUsers,
        totalApplications,
        totalPolicies,
        totalClaims,
        totalPremium: parseFloat(totalPremium),
        totalClaimAmount: parseFloat(totalClaimAmount),
        activePolicies,
        pendingApplications,
        pendingClaims,
        profitLoss: parseFloat(totalPremium) - parseFloat(totalClaimAmount)
      }
    });
  } catch (error) {
    console.error('获取数据仓库概览失败:', error);
    res.status(500).json({
      success: false,
      message: '获取数据仓库概览失败',
      error: error.message
    });
  }
};

// 获取保险类型分布数据
const getInsuranceTypeDistribution = async (req, res) => {
  try {
    const distribution = await InsuranceApplication.findAll({
      attributes: [
        'insurance_type_id',
        [Sequelize.fn('COUNT', Sequelize.col('InsuranceApplication.id')), 'count']
      ],
      include: [{
        model: InsuranceType,
        as: 'insurance_type',
        attributes: ['name']
      }],
      group: ['insurance_type_id', 'insurance_type.id'],
      order: [[Sequelize.fn('COUNT', Sequelize.col('InsuranceApplication.id')), 'DESC']]
    });

    // 计算总数用于百分比计算
    const totalCount = distribution.reduce((sum, item) => sum + parseInt(item.dataValues.count), 0);

    res.json({
      success: true,
      data: distribution.map(item => {
        const count = parseInt(item.dataValues.count);
        return {
          type: item.insurance_type.name,
          count: count,
          percentage: totalCount > 0 ? ((count / totalCount) * 100).toFixed(2) : 0
        };
      })
    });
  } catch (error) {
    console.error('获取保险类型分布失败:', error);
    res.status(500).json({
      success: false,
      message: '获取保险类型分布失败',
      error: error.message
    });
  }
};

// 获取申请状态分布数据
const getApplicationStatusDistribution = async (req, res) => {
  try {
    const distribution = await InsuranceApplication.findAll({
      attributes: [
        'status',
        [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
      ],
      group: ['status'],
      order: [[Sequelize.fn('COUNT', Sequelize.col('id')), 'DESC']]
    });

    // 计算总数用于百分比计算
    const totalCount = distribution.reduce((sum, item) => sum + parseInt(item.dataValues.count), 0);

    res.json({
      success: true,
      data: distribution.map(item => {
        const count = parseInt(item.dataValues.count);
        return {
          status: item.status,
          label: getStatusLabel(item.status),
          count: count,
          percentage: totalCount > 0 ? ((count / totalCount) * 100).toFixed(2) : 0
        };
      })
    });
  } catch (error) {
    console.error('获取申请状态分布失败:', error);
    res.status(500).json({
      success: false,
      message: '获取申请状态分布失败',
      error: error.message
    });
  }
};

// 状态标签映射
function getStatusLabel(status) {
  const statusMap = {
    'pending': '待初审',
    'initial_approved': '初审通过待复核',
    'under_review': '已支付待复核',
    'approved': '已批准',
    'rejected': '已拒绝',
    'paid': '已支付'
  };
  return statusMap[status] || status;
}

// 获取近7天趋势数据
const getTrendData = async (req, res) => {
  try {
    const { days = 7 } = req.query;
    const endDate = new Date();
    const startDate = new Date();
    startDate.setDate(endDate.getDate() - parseInt(days));
    
    // 获取每日申请数据
    const applicationTrend = await InsuranceApplication.findAll({
      attributes: [
        [Sequelize.fn('DATE', Sequelize.col('application_date')), 'date'],
        [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
      ],
      where: {
        application_date: {
          [Op.between]: [startDate, endDate]
        }
      },
      group: [Sequelize.fn('DATE', Sequelize.col('application_date'))],
      order: [[Sequelize.fn('DATE', Sequelize.col('application_date')), 'ASC']]
    });
    
    // 获取每日保单数据
    const policyTrend = await Policy.findAll({
      attributes: [
        [Sequelize.fn('DATE', Sequelize.col('created_at')), 'date'],
        [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
      ],
      where: {
        created_at: {
          [Op.between]: [startDate, endDate]
        }
      },
      group: [Sequelize.fn('DATE', Sequelize.col('created_at'))],
      order: [[Sequelize.fn('DATE', Sequelize.col('created_at')), 'ASC']]
    });
    
    // 获取每日理赔数据
    const claimTrend = await Claim.findAll({
      attributes: [
        [Sequelize.fn('DATE', Sequelize.col('claim_date')), 'date'],
        [Sequelize.fn('COUNT', Sequelize.col('id')), 'count']
      ],
      where: {
        claim_date: {
          [Op.between]: [startDate, endDate]
        }
      },
      group: [Sequelize.fn('DATE', Sequelize.col('claim_date'))],
      order: [[Sequelize.fn('DATE', Sequelize.col('claim_date')), 'ASC']]
    });

    res.json({
      success: true,
      data: {
        applications: applicationTrend.map(item => ({
          date: item.dataValues.date,
          count: parseInt(item.dataValues.count)
        })),
        policies: policyTrend.map(item => ({
          date: item.dataValues.date,
          count: parseInt(item.dataValues.count)
        })),
        claims: claimTrend.map(item => ({
          date: item.dataValues.date,
          count: parseInt(item.dataValues.count)
        }))
      }
    });
  } catch (error) {
    console.error('获取趋势数据失败:', error);
    res.status(500).json({
      success: false,
      message: '获取趋势数据失败',
      error: error.message
    });
  }
};

// 获取理赔统计
const getClaimStats = async (req, res) => {
  try {
    // 获取理赔状态分布
    const claimStatusDistribution = await Claim.findAll({
      attributes: [
        'claim_status',
        [Sequelize.fn('COUNT', Sequelize.col('id')), 'count'],
        [Sequelize.fn('SUM', Sequelize.col('claim_amount')), 'total_amount']
      ],
      group: ['claim_status']
    });

    // 获取月度理赔趋势
    const monthlyClaimTrend = await Claim.findAll({
      attributes: [
        [Sequelize.fn('DATE_FORMAT', Sequelize.col('claim_date'), '%Y-%m'), 'month'],
        [Sequelize.fn('COUNT', Sequelize.col('id')), 'count'],
        [Sequelize.fn('SUM', Sequelize.col('claim_amount')), 'total_amount']
      ],
      where: {
        claim_date: {
          [Op.gte]: Sequelize.literal('DATE_SUB(NOW(), INTERVAL 12 MONTH)')
        }
      },
      group: [Sequelize.fn('DATE_FORMAT', Sequelize.col('claim_date'), '%Y-%m')],
      order: [[Sequelize.fn('DATE_FORMAT', Sequelize.col('claim_date'), '%Y-%m'), 'ASC']]
    });

    res.json({
      success: true,
      data: {
        statusDistribution: claimStatusDistribution.map(item => ({
          status: item.claim_status,
          label: getClaimStatusLabel(item.claim_status),
          count: parseInt(item.dataValues.count),
          totalAmount: parseFloat(item.dataValues.total_amount || 0)
        })),
        monthlyTrend: monthlyClaimTrend.map(item => ({
          month: item.dataValues.month,
          count: parseInt(item.dataValues.count),
          totalAmount: parseFloat(item.dataValues.total_amount || 0)
        }))
      }
    });
  } catch (error) {
    console.error('获取理赔统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取理赔统计失败',
      error: error.message
    });
  }
};

// 理赔状态标签映射
function getClaimStatusLabel(status) {
  const statusMap = {
    'pending': '待审核',
    'approved': '已批准',
    'rejected': '已拒绝',
    'processing': '处理中',
    'paid': '已支付'
  };
  return statusMap[status] || status;
}

module.exports = {
  getOverview,
  getInsuranceTypeDistribution,
  getApplicationStatusDistribution,
  getTrendData,
  getClaimStats
};