const LivestockClaim = require('../models/LivestockClaim');
const LivestockPolicy = require('../models/LivestockPolicy');
const LivestockType = require('../models/LivestockType');
const User = require('../models/User');
const responseFormat = require('../utils/response');
const { Op } = require('sequelize');
const ExcelExport = require('../utils/excelExport');

// 获取生资理赔列表
const getLivestockClaims = async (req, res) => {
  try {
    console.log('🚀 [后端] 开始处理理赔列表查询请求');
    console.log('📥 [后端] 接收到的查询参数:', {
      接收时间: new Date().toLocaleString(),
      完整URL: req.originalUrl,
      查询字符串: req.url,
      原始查询参数: JSON.stringify(req.query, null, 2),
      查询参数类型: typeof req.query,
      查询参数键: Object.keys(req.query),
      请求方法: req.method,
      请求路径: req.path,
      用户信息: req.user ? { id: req.user.id, username: req.user.username } : '未登录'
    });
    
    console.log('🔍 [详细调试] 请求信息:');
    console.log('req.url:', req.url);
    console.log('req.originalUrl:', req.originalUrl);
    console.log('req.baseUrl:', req.baseUrl);
    console.log('req.path:', req.path);
    console.log('查询字符串:', req.url.split('?')[1] || '无');
    console.log('原始查询参数:', req.query);
    console.log('查询参数类型:', typeof req.query);
    console.log('查询参数键:', Object.keys(req.query));
    console.log('查询参数JSON:', JSON.stringify(req.query));
    
    const {
      claim_no,
      policy_no,
      reporter_name,
      contact_phone,
      claim_status,
      claim_type,
      start_date,
      end_date,
      page = 1,
      limit = 10
    } = req.query;
    
    console.log('🔍 [后端] 解析后的查询参数:', {
      理赔单号: claim_no,
      保单号: policy_no,
      报案人: reporter_name,
      联系电话: contact_phone,
      理赔状态: claim_status,
      理赔类型: claim_type,
      开始日期: start_date,
      结束日期: end_date,
      页码: page,
      每页条数: limit
    });
    
    const whereClause = {};
    
    // 理赔编号筛选 - 精确匹配
    if (claim_no) {
      whereClause.claim_no = claim_no;
      console.log('🔍 [后端] 添加理赔编号筛选条件(精确匹配):', whereClause.claim_no);
    }
    
    // 理赔状态筛选
    if (claim_status) {
      whereClause.claim_status = claim_status;
      console.log('🔍 [后端] 添加理赔状态筛选条件:', whereClause.claim_status);
    }
    
    // 理赔类型筛选
    if (claim_type) {
      whereClause.claim_type = claim_type;
      console.log('🔍 [后端] 添加理赔类型筛选条件:', whereClause.claim_type);
    }
    
    // 报案人筛选
    if (reporter_name) {
      whereClause.reporter_name = { [Op.like]: `%${reporter_name}%` };
      console.log('🔍 [后端] 添加报案人筛选条件:', whereClause.reporter_name);
    }
    
    // 联系电话筛选
    if (contact_phone) {
      whereClause.contact_phone = { [Op.like]: `%${contact_phone}%` };
      console.log('🔍 [后端] 添加联系电话筛选条件:', whereClause.contact_phone);
    }
    
    // 日期范围筛选
    if (start_date && end_date) {
      whereClause.incident_date = {
        [Op.between]: [new Date(start_date), new Date(end_date)]
      };
      console.log('🔍 [后端] 添加日期范围筛选条件:', whereClause.incident_date);
    }
    
    const offset = (page - 1) * limit;
    
    console.log('📊 [后端] 构建的查询条件:', {
      构建时间: new Date().toLocaleString(),
      WHERE条件: JSON.stringify(whereClause, null, 2),
      分页信息: {
        页码: page,
        每页条数: limit,
        偏移量: offset
      }
    });
    
    console.log('🗄️ [后端] 开始执行数据库查询...');
    
    const queryConfig = {
      where: whereClause,
      include: [
        {
          model: LivestockPolicy,
          as: 'policy',
          attributes: ['id', 'policy_no', 'policyholder_name', 'policyholder_phone', 'livestock_count'],
          where: policy_no ? { policy_no: { [Op.like]: `%${policy_no}%` } } : {},
          required: !!policy_no,
          include: [
            {
              model: LivestockType,
              as: 'livestock_type',
              attributes: ['id', 'name']
            }
          ]
        },
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'real_name', 'username']
        },
        {
          model: User,
          as: 'reviewer',
          attributes: ['id', 'real_name', 'username']
        }
      ],
      order: [['created_at', 'DESC']],
      offset,
      limit: parseInt(limit)
    };
    
    console.log('🗄️ [后端] 数据库查询配置:', {
      查询时间: new Date().toLocaleString(),
      查询配置: JSON.stringify(queryConfig, null, 2)
    });
    
    console.log('🚀 [后端] 即将执行查询，最终配置:', JSON.stringify(queryConfig, null, 2));
    
    const { count, rows } = await LivestockClaim.findAndCountAll(queryConfig);
    
    console.log('✅ [后端] 数据库查询完成:', {
      查询时间: new Date().toLocaleString(),
      返回总数: count,
      返回记录数: rows.length,
      记录ID列表: rows.map(r => ({ id: r.id, claim_no: r.claim_no }))
    });
    
    console.log('📋 [后端] 详细查询结果:', {
      查询完成时间: new Date().toLocaleString(),
      查询结果统计: {
        总记录数: count,
        当前页记录数: rows.length,
        查询耗时: '已完成'
      },
      数据样例: rows.length > 0 ? {
        第一条记录ID: rows[0].id,
        第一条记录理赔单号: rows[0].claim_no,
        第一条记录状态: rows[0].claim_status
      } : '无数据'
    });
    
    const responseData = responseFormat.pagination(rows, {
      page: parseInt(page),
      limit: parseInt(limit),
      total: count
    }, '获取生资理赔列表成功');
    
    console.log('📤 [后端->前端] 准备发送响应:', {
      响应时间: new Date().toLocaleString(),
      响应状态: 'success',
      响应数据结构: {
        status: responseData.status,
        message: responseData.message,
        data类型: Array.isArray(responseData.data) ? 'Array' : typeof responseData.data,
        data长度: responseData.data?.length,
        pagination: responseData.pagination
      },
      完整响应: JSON.stringify(responseData, null, 2)
    });
    
    res.json(responseData);
  } catch (error) {
    console.error('💥 [后端] 获取生资理赔列表错误:', {
      错误时间: new Date().toLocaleString(),
      错误类型: error.name,
      错误信息: error.message,
      错误堆栈: error.stack,
      SQL错误: error.sql || '无SQL信息'
    });
    res.status(500).json(responseFormat.error('获取生资理赔列表失败'));
  }
};

// 创建生资理赔申请
const createLivestockClaim = async (req, res) => {
  try {
    const claimData = req.body;
    
    // 验证保单是否存在且有效
    const policy = await LivestockPolicy.findByPk(claimData.policy_id);
    if (!policy) {
      return res.status(400).json(responseFormat.error('保单不存在'));
    }
    
    if (policy.policy_status !== 'active') {
      return res.status(400).json(responseFormat.error('保单状态无效，无法申请理赔'));
    }
    
    // 生成理赔编号
    const claimNo = `LC${Date.now()}${Math.random().toString(36).substr(2, 6).toUpperCase()}`;
    
    const claim = await LivestockClaim.create({
      ...claimData,
      claim_no: claimNo,
      claim_status: 'pending',
      created_by: req.user?.id
    });
    
    // 获取完整的理赔信息（包含关联数据）
    const fullClaim = await LivestockClaim.findByPk(claim.id, {
      include: [
        {
          model: LivestockPolicy,
          as: 'policy',
          attributes: ['id', 'policy_no', 'farmer_name', 'farmer_phone'],
          include: [
            {
              model: LivestockType,
              as: 'livestock_type',
              attributes: ['id', 'name']
            }
          ]
        }
      ]
    });
    
    res.status(201).json(responseFormat.created(fullClaim, '生资理赔申请创建成功'));
  } catch (error) {
    console.error('创建生资理赔申请错误:', error);
    res.status(500).json(responseFormat.error('创建生资理赔申请失败'));
  }
};

// 获取单个生资理赔详情
const getLivestockClaimById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const claim = await LivestockClaim.findByPk(id, {
      include: [
        {
          model: LivestockPolicy,
          as: 'policy',
          include: [
            {
              model: LivestockType,
              as: 'livestock_type',
              attributes: ['id', 'name', 'description', 'base_value']
            }
          ]
        },
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'real_name', 'username']
        },
        {
          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 reviewLivestockClaim = async (req, res) => {
  try {
    const { id } = req.params;
    const { claim_status, review_notes, approved_amount } = req.body;
    
    const claim = await LivestockClaim.findByPk(id);
    if (!claim) {
      return res.status(404).json(responseFormat.error('生资理赔不存在'));
    }
    
    if (claim.claim_status !== 'pending') {
      return res.status(400).json(responseFormat.error('该理赔已经审核过了'));
    }
    
    const updateData = {
      claim_status,
      review_notes,
      reviewed_by: req.user?.id,
      reviewed_at: new Date()
    };
    
    if (claim_status === 'approved' && approved_amount) {
      updateData.approved_amount = approved_amount;
    }
    
    await claim.update(updateData);
    
    // 获取更新后的完整信息
    const updatedClaim = await LivestockClaim.findByPk(id, {
      include: [
        {
          model: LivestockPolicy,
          as: 'policy',
          attributes: ['id', 'policy_no', 'farmer_name', 'farmer_phone']
        },
        {
          model: User,
          as: 'reviewer',
          attributes: ['id', 'real_name', 'username']
        }
      ]
    });
    
    res.json(responseFormat.success(updatedClaim, '生资理赔审核成功'));
  } catch (error) {
    console.error('审核生资理赔错误:', error);
    res.status(500).json(responseFormat.error('审核生资理赔失败'));
  }
};

// 更新理赔支付状态
const updateLivestockClaimPayment = async (req, res) => {
  try {
    const { id } = req.params;
    const { payment_status, payment_date, payment_method, payment_reference } = req.body;
    
    const claim = await LivestockClaim.findByPk(id);
    if (!claim) {
      return res.status(404).json(responseFormat.error('生资理赔不存在'));
    }
    
    if (claim.claim_status !== 'approved') {
      return res.status(400).json(responseFormat.error('只有已批准的理赔才能更新支付状态'));
    }
    
    const updateData = {
      payment_status,
      payment_date,
      payment_method,
      payment_reference,
      updated_by: req.user?.id
    };
    
    await claim.update(updateData);
    
    res.json(responseFormat.success(claim, '理赔支付状态更新成功'));
  } catch (error) {
    console.error('更新理赔支付状态错误:', error);
    res.status(500).json(responseFormat.error('更新理赔支付状态失败'));
  }
};

// 获取生资理赔统计
const getLivestockClaimStats = async (req, res) => {
  try {
    const { sequelize } = require('../config/database');
    
    // 总理赔数
    const totalClaims = await LivestockClaim.count();
    
    // 待审核理赔数
    const pendingClaims = await LivestockClaim.count({
      where: { claim_status: 'pending' }
    });
    
    // 已批准理赔数
    const approvedClaims = await LivestockClaim.count({
      where: { claim_status: 'approved' }
    });
    
    // 已拒绝理赔数
    const rejectedClaims = await LivestockClaim.count({
      where: { claim_status: 'rejected' }
    });
    
    // 总理赔金额
    const totalClaimAmount = await LivestockClaim.sum('claim_amount') || 0;
    
    // 已支付理赔金额
    const paidClaimAmount = await LivestockClaim.sum('approved_amount', {
      where: { 
        claim_status: 'approved',
        payment_status: 'paid'
      }
    }) || 0;
    
    // 按理赔类型统计
    const typeStats = await sequelize.query(`
      SELECT 
        claim_type,
        COUNT(*) as claim_count,
        SUM(claim_amount) as total_claim_amount,
        SUM(CASE WHEN claim_status = 'approved' THEN approved_amount ELSE 0 END) as total_approved_amount,
        AVG(CASE WHEN claim_status = 'approved' THEN approved_amount ELSE NULL END) as avg_approved_amount
      FROM livestock_claims
      GROUP BY claim_type
      ORDER BY claim_count DESC
    `, { type: sequelize.QueryTypes.SELECT });
    
    // 按月份统计（最近12个月）
    const monthlyStats = await sequelize.query(`
      SELECT 
        DATE_FORMAT(created_at, '%Y-%m') as month,
        COUNT(*) as claim_count,
        SUM(claim_amount) as total_claim_amount,
        SUM(CASE WHEN claim_status = 'approved' THEN approved_amount ELSE 0 END) as total_approved_amount,
        COUNT(CASE WHEN claim_status = 'approved' THEN 1 END) as approved_count
      FROM livestock_claims
      WHERE created_at >= DATE_SUB(NOW(), INTERVAL 12 MONTH)
      GROUP BY DATE_FORMAT(created_at, '%Y-%m')
      ORDER BY month DESC
    `, { type: sequelize.QueryTypes.SELECT });
    
    const stats = {
      overview: {
        total_claims: totalClaims,
        pending_claims: pendingClaims,
        approved_claims: approvedClaims,
        rejected_claims: rejectedClaims,
        total_claim_amount: parseFloat(totalClaimAmount),
        paid_claim_amount: parseFloat(paidClaimAmount),
        approval_rate: totalClaims > 0 ? (approvedClaims / totalClaims * 100).toFixed(2) : 0
      },
      by_type: typeStats,
      monthly: monthlyStats
    };
    
    res.json(responseFormat.success(stats, '获取生资理赔统计成功'));
  } catch (error) {
    console.error('获取生资理赔统计错误:', error);
    res.status(500).json(responseFormat.error('获取生资理赔统计失败'));
  }
};

// 更新生资理赔
const updateLivestockClaim = async (req, res) => {
  try {
    const { id } = req.params;
    const updateData = req.body;
    
    const claim = await LivestockClaim.findByPk(id);
    if (!claim) {
      return res.status(404).json(responseFormat.error('生资理赔不存在'));
    }
    
    // 更新理赔信息
    await claim.update({
      ...updateData,
      updated_by: req.user?.id
    });
    
    // 获取更新后的完整信息
    const updatedClaim = await LivestockClaim.findByPk(id, {
      include: [
        {
          model: LivestockPolicy,
          as: 'policy',
          attributes: ['id', 'policy_no', 'policyholder_name', 'policyholder_phone'],
          include: [
            {
              model: LivestockType,
              as: 'livestock_type',
              attributes: ['id', 'name']
            }
          ]
        },
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'real_name', 'username']
        },
        {
          model: User,
          as: 'reviewer',
          attributes: ['id', 'real_name', 'username']
        }
      ]
    });
    
    res.json(responseFormat.success(updatedClaim, '生资理赔更新成功'));
  } catch (error) {
    console.error('更新生资理赔错误:', error);
    res.status(500).json(responseFormat.error('更新生资理赔失败'));
  }
};

// 删除生资理赔
const deleteLivestockClaim = async (req, res) => {
  try {
    const { id } = req.params;
    
    const claim = await LivestockClaim.findByPk(id);
    if (!claim) {
      return res.status(404).json(responseFormat.error('生资理赔不存在'));
    }
    
    // 检查是否可以删除（只有待处理状态的理赔可以删除）
    if (claim.claim_status !== 'pending') {
      return res.status(400).json(responseFormat.error('只有待处理状态的理赔可以删除'));
    }
    
    await claim.destroy();
    
    res.json(responseFormat.success(null, '生资理赔删除成功'));
  } catch (error) {
    console.error('删除生资理赔错误:', error);
    res.status(500).json(responseFormat.error('删除生资理赔失败'));
  }
};

// 导出理赔列表到Excel
const exportToExcel = async (req, res) => {
  try {
    const ExcelJS = require('exceljs');
    const { claim_no, reporter_name, claim_status } = req.query;
    
    const where = {};
    if (claim_no) where.claim_no = { [Op.like]: `%${claim_no}%` };
    if (reporter_name) where.reporter_name = { [Op.like]: `%${reporter_name}%` };
    if (claim_status) where.claim_status = claim_status;
    
    const claims = await LivestockClaim.findAll({
      where,
      include: [
        {
          model: LivestockPolicy,
          as: 'policy',
          attributes: ['id', 'policy_no', 'policyholder_name'],
          required: false
        },
        {
          model: User,
          as: 'reviewer',
          attributes: ['id', 'real_name', 'username'],
          required: false
        },
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'real_name', 'username'],
          required: false
        }
      ],
      order: [['created_at', 'DESC']],
      limit: 10000
    });
    
    // 将Sequelize实例转换为纯对象
    const plainClaims = claims.map(claim => claim.toJSON());
    
    // 状态映射
    const statusMap = { 
      'pending': '待审核',
      'investigating': '调查中',
      'approved': '已批准',
      'rejected': '已拒绝',
      'paid': '已支付'
    };
    
    // 理赔类型映射
    const claimTypeMap = {
      'death': '死亡',
      'disease': '疾病',
      'accident': '意外事故',
      'natural_disaster': '自然灾害'
    };
    
    // 创建Excel工作簿
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('生资理赔列表');
    
    // 定义列（包含所有字段）
    worksheet.columns = [
      { header: 'ID', key: 'id', width: 8 },
      { header: '理赔编号', key: 'claim_no', width: 18 },
      { header: '报案人姓名', key: 'reporter_name', width: 12 },
      { header: '联系电话', key: 'contact_phone', width: 15 },
      { header: '保单号', key: 'policy_no', width: 18 },
      { header: '保单持有人', key: 'policy_holder', width: 12 },
      { header: '理赔类型', key: 'claim_type', width: 12 },
      { header: '受影响数量', key: 'affected_count', width: 12 },
      { header: '理赔金额', key: 'claim_amount', width: 15 },
      { header: '事故日期', key: 'incident_date', width: 20 },
      { header: '报案日期', key: 'report_date', width: 20 },
      { header: '事故描述', key: 'incident_description', width: 35 },
      { header: '事故地点', key: 'incident_location', width: 25 },
      { header: '理赔状态', key: 'claim_status', width: 12 },
      { header: '调查报告', key: 'investigation_report', width: 30 },
      { header: '审核人', key: 'reviewer_name', width: 12 },
      { header: '审核备注', key: 'review_notes', width: 30 },
      { header: '审核日期', key: 'review_date', width: 20 },
      { header: '赔付日期', key: 'payment_date', width: 20 },
      { header: '赔付金额', key: 'payment_amount', width: 15 },
      { header: '创建人', key: 'creator_name', width: 12 },
      { header: '创建时间', key: 'created_at', width: 20 },
      { header: '更新时间', key: 'updated_at', width: 20 }
    ];
    
    // 设置表头样式
    worksheet.getRow(1).font = { bold: true, size: 12 };
    worksheet.getRow(1).fill = {
      type: 'pattern',
      pattern: 'solid',
      fgColor: { argb: 'FFE0E0E0' }
    };
    worksheet.getRow(1).alignment = { vertical: 'middle', horizontal: 'center' };
    
    // 添加数据行
    plainClaims.forEach(claim => {
      worksheet.addRow({
        id: claim.id || '',
        claim_no: claim.claim_no || '',
        reporter_name: claim.reporter_name || '',
        contact_phone: claim.contact_phone || '',
        policy_no: claim.policy_no || '',
        policy_holder: claim.policy?.policyholder_name || '',
        claim_type: claimTypeMap[claim.claim_type] || claim.claim_type || '',
        affected_count: claim.affected_count || '',
        claim_amount: claim.claim_amount || '',
        incident_date: claim.incident_date || '',
        report_date: claim.report_date || '',
        incident_description: claim.incident_description || '',
        incident_location: claim.incident_location || '',
        claim_status: statusMap[claim.claim_status] || claim.claim_status || '',
        investigation_report: claim.investigation_report || '',
        reviewer_name: claim.reviewer?.real_name || '',
        review_notes: claim.review_notes || '',
        review_date: claim.review_date || '',
        payment_date: claim.payment_date || '',
        payment_amount: claim.payment_amount || '',
        creator_name: claim.creator?.real_name || '',
        created_at: claim.created_at || '',
        updated_at: claim.updated_at || ''
      });
    });
    
    // 设置数据行样式
    worksheet.eachRow((row, rowNumber) => {
      if (rowNumber > 1) {
        row.alignment = { vertical: 'middle', horizontal: 'left' };
      }
    });
    
    // 生成Excel文件
    const buffer = await workbook.xlsx.writeBuffer();
    
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', `attachment; filename=livestock_claims_${Date.now()}.xlsx`);
    res.send(buffer);
  } catch (error) {
    console.error('导出生资理赔记录失败:', error);
    res.status(500).json(responseFormat.error('导出失败'));
  }
};

module.exports = {
  getLivestockClaims,
  createLivestockClaim,
  getLivestockClaimById,
  updateLivestockClaim,
  deleteLivestockClaim,
  reviewLivestockClaim,
  updateLivestockClaimPayment,
  getLivestockClaimStats,
  exportToExcel
};