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

// 获取理赔列表
const getClaims = async (req, res) => {
  try {
    const {
      claim_no,
      customer_name,
      claim_status,
      dateRange,
      page = 1,
      limit = 10
    } = req.query;
    
    const whereClause = {};
    
    // 理赔编号筛选
    if (claim_no) {
      whereClause.claim_no = { [Op.like]: `%${claim_no}%` };
    }
    
    // 理赔状态筛选
    if (claim_status) {
      whereClause.claim_status = claim_status;
    }
    
    // 日期范围筛选
    if (dateRange && dateRange.start && dateRange.end) {
      whereClause.claim_date = {
        [Op.between]: [new Date(dateRange.start), new Date(dateRange.end)]
      };
    }
    
    const offset = (page - 1) * limit;
    
    const { count, rows } = await Claim.findAndCountAll({
      where: whereClause,
      include: [
        {
          model: Policy,
          as: 'policy',
          attributes: ['id', 'policy_no', 'coverage_amount'],
          include: [
            {
              model: InsuranceApplication,
              as: 'application',
              attributes: ['id', 'customer_name'],
              include: [
                {
                  model: InsuranceType,
                  as: 'insurance_type',
                  attributes: ['id', 'name']
                }
              ]
            }
          ]
        },
        {
          model: User,
          as: 'customer',
          attributes: ['id', 'real_name', 'username']
        },
        {
          model: User,
          as: 'reviewer',
          attributes: ['id', 'real_name', 'username']
        }
      ],
      order: [['created_at', 'DESC']],
      offset,
      limit: parseInt(limit)
    });
    
    res.json(responseFormat.pagination(rows, {
      page: parseInt(page),
      limit: parseInt(limit),
      total: count
    }, '获取理赔列表成功'));
  } catch (error) {
    console.error('获取理赔列表错误:', error);
    res.status(500).json(responseFormat.error('获取理赔列表失败'));
  }
};

// 创建理赔申请
const createClaim = async (req, res) => {
  try {
    const claimData = req.body;
    
    // 生成理赔编号
    const claimNo = `CLM${Date.now()}${Math.random().toString(36).substr(2, 6).toUpperCase()}`;
    
    const claim = await Claim.create({
      ...claimData,
      claim_no: claimNo
    });
    
    res.status(201).json(responseFormat.created(claim, '理赔申请创建成功'));
  } catch (error) {
    console.error('创建理赔申请错误:', error);
    res.status(500).json(responseFormat.error('创建理赔申请失败'));
  }
};

// 获取单个理赔详情
const getClaimById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const claim = await Claim.findByPk(id, {
      include: [
        {
          model: Policy,
          as: 'policy',
          include: [
            {
              model: InsuranceApplication,
              as: 'application',
              include: [
                {
                  model: InsuranceType,
                  as: 'insurance_type',
                  attributes: ['id', 'name', 'description']
                }
              ]
            }
          ]
        },
        {
          model: User,
          as: 'customer',
          attributes: ['id', 'real_name', 'username', 'phone', 'email']
        },
        {
          model: User,
          as: 'reviewer',
          attributes: ['id', 'real_name', 'username']
        }
      ]
    });
    
    if (!claim) {
      return res.status(404).json(responseFormat.error('理赔申请不存在'));
    }
    
    res.json(responseFormat.success(claim, '获取理赔详情成功'));
  } catch (error) {
    console.error('获取理赔详情错误:', error);
    res.status(500).json(responseFormat.error('获取理赔详情失败'));
  }
};

// 审核理赔申请
const reviewClaim = async (req, res) => {
  try {
    const { id } = req.params;
    const { claim_status, review_notes } = req.body;
    const reviewerId = req.user.id;
    
    const claim = await Claim.findByPk(id);
    if (!claim) {
      return res.status(404).json(responseFormat.error('理赔申请不存在'));
    }
    
    if (!['approved', 'rejected', 'processing', 'paid'].includes(claim_status)) {
      return res.status(400).json(responseFormat.error('无效的理赔状态'));
    }
    
    await claim.update({
      claim_status,
      review_notes,
      reviewer_id: reviewerId,
      review_date: new Date()
    });
    
    res.json(responseFormat.success(claim, '理赔申请审核成功'));
  } catch (error) {
    console.error('审核理赔申请错误:', error);
    res.status(500).json(responseFormat.error('审核理赔申请失败'));
  }
};

// 更新理赔支付状态
const updateClaimPayment = async (req, res) => {
  try {
    const { id } = req.params;
    
    const claim = await Claim.findByPk(id);
    if (!claim) {
      return res.status(404).json(responseFormat.error('理赔申请不存在'));
    }
    
    if (claim.claim_status !== 'approved') {
      return res.status(400).json(responseFormat.error('只有已批准的理赔才能进行支付'));
    }
    
    await claim.update({
      claim_status: 'paid',
      payment_date: new Date()
    });
    
    res.json(responseFormat.success(claim, '理赔支付状态更新成功'));
  } catch (error) {
    console.error('更新理赔支付状态错误:', error);
    res.status(500).json(responseFormat.error('更新理赔支付状态失败'));
  }
};

// 获取理赔统计
const getClaimStats = async (req, res) => {
  try {
    const stats = await Claim.findAll({
      attributes: [
        'claim_status',
        [Claim.sequelize.fn('COUNT', Claim.sequelize.col('id')), 'count'],
        [Claim.sequelize.fn('SUM', Claim.sequelize.col('claim_amount')), 'total_amount']
      ],
      group: ['claim_status']
    });
    
    const total = await Claim.count();
    const totalAmount = await Claim.sum('claim_amount');
    
    res.json(responseFormat.success({
      stats,
      total,
      total_amount: totalAmount || 0
    }, '获取理赔统计成功'));
  } catch (error) {
    console.error('获取理赔统计错误:', error);
    res.status(500).json(responseFormat.error('获取理赔统计失败'));
  }
};

module.exports = {
  getClaims,
  createClaim,
  getClaimById,
  reviewClaim,
  updateClaimPayment,
  getClaimStats
};