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

// 获取保险申请列表
const getApplications = async (req, res) => {
  try {
    console.log('获取保险申请列表 - 请求参数:', req.query);
    const {
      applicantName,
      status,
      insuranceType,
      insuranceCategory,
      applicationNumber,
      dateRange,
      page = 1,
      limit = 10
    } = req.query;
    
    const whereClause = {};
    const includeClause = [
      {
        model: InsuranceType,
        as: 'insurance_type',
        attributes: ['id', 'name', 'description'],
        where: {}
      },
      {
        model: User,
        as: 'reviewer',
        attributes: ['id', 'real_name', 'username']
      }
    ];
    
    // 申请单号筛选
    if (applicationNumber) {
      whereClause.application_no = { [Op.like]: `%${applicationNumber}%` };
    }
    
    // 投保人姓名筛选
    if (applicantName) {
      whereClause.customer_name = { [Op.like]: `%${applicantName}%` };
    }
    
    // 状态筛选
    if (status) {
      whereClause.status = status;
    }
    
    // 参保险种筛选
    if (insuranceType) {
      includeClause[0].where.name = { [Op.like]: `%${insuranceType}%` };
    }
    
    // 参保类型筛选
    if (insuranceCategory) {
      whereClause.insurance_category = { [Op.like]: `%${insuranceCategory}%` };
    }
    
    // 日期范围筛选
    if (dateRange && dateRange.start && dateRange.end) {
      whereClause.application_date = {
        [Op.between]: [new Date(dateRange.start), new Date(dateRange.end)]
      };
    }
    
    const offset = (page - 1) * limit;
    
    // 如果没有保险类型筛选条件，清空where条件
    if (!insuranceType) {
      delete includeClause[0].where;
    }
    
    console.log('查询条件:', { whereClause, includeClause, offset, limit: parseInt(limit) });
    
    const { count, rows } = await InsuranceApplication.findAndCountAll({
      where: whereClause,
      include: includeClause,
      order: [['created_at', 'DESC']],
      offset,
      limit: parseInt(limit)
    });
    
    console.log('查询结果:', { count, rowsLength: rows.length });
    
    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 createApplication = async (req, res) => {
  try {
    const {
      customer_name,
      customer_id_card,
      customer_phone,
      customer_address,
      insurance_type_id,
      insurance_category,
      application_quantity,
      application_amount,
      remarks
    } = req.body;
    
    // 验证必填字段
    if (!customer_name || !customer_id_card || !customer_phone || !customer_address || !insurance_type_id) {
      return res.status(400).json(responseFormat.error('请填写所有必填字段'));
    }
    
    // 生成申请编号
    const applicationNo = `${new Date().getFullYear()}${(new Date().getMonth() + 1).toString().padStart(2, '0')}${new Date().getDate().toString().padStart(2, '0')}${Date.now().toString().slice(-6)}`;
    
    const application = await InsuranceApplication.create({
      application_no: applicationNo,
      customer_name,
      customer_id_card,
      customer_phone,
      customer_address,
      insurance_type_id,
      insurance_category,
      application_quantity: application_quantity || 1,
      application_amount: application_amount || 0,
      remarks,
      status: 'pending'
    });
    
    // 返回创建的申请信息，包含关联数据
    const createdApplication = await InsuranceApplication.findByPk(application.id, {
      include: [
        {
          model: InsuranceType,
          as: 'insurance_type',
          attributes: ['id', 'name', 'description']
        }
      ]
    });
    
    res.status(201).json(responseFormat.created(createdApplication, '保险申请创建成功'));
  } catch (error) {
    console.error('创建保险申请错误:', error);
    if (error.name === 'SequelizeValidationError') {
      const errorMessages = error.errors.map(err => err.message).join(', ');
      return res.status(400).json(responseFormat.error(`数据验证失败: ${errorMessages}`));
    }
    res.status(500).json(responseFormat.error('创建保险申请失败'));
  }
};

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

// 更新保险申请
const updateApplication = async (req, res) => {
  try {
    const { id } = req.params;
    const updateData = req.body;
    
    const application = await InsuranceApplication.findByPk(id);
    if (!application) {
      return res.status(404).json(responseFormat.error('保险申请不存在'));
    }
    
    await application.update(updateData);
    
    res.json(responseFormat.success(application, '保险申请更新成功'));
  } catch (error) {
    console.error('更新保险申请错误:', error);
    res.status(500).json(responseFormat.error('更新保险申请失败'));
  }
};

// 审核保险申请
const reviewApplication = async (req, res) => {
  try {
    const { id } = req.params;
    const { status, result, review_notes } = req.body;
    const reviewerId = req.user.id;
    
    const application = await InsuranceApplication.findByPk(id);
    if (!application) {
      return res.status(404).json(responseFormat.error('保险申请不存在'));
    }
    
    // 前端发送的是result字段，后端期望status字段
    const reviewStatus = status || result;
    
    // 状态映射：将前端的pending_review映射为under_review
    let mappedStatus = reviewStatus;
    if (reviewStatus === 'pending_review') {
      mappedStatus = 'under_review';
    }
    
    if (!['approved', 'rejected', 'under_review'].includes(mappedStatus)) {
      return res.status(400).json(responseFormat.error('无效的审核状态'));
    }
    
    await application.update({
      status: mappedStatus,
      review_notes,
      reviewer_id: reviewerId,
      review_date: new Date()
    });
    
    res.json(responseFormat.success(application, '保险申请审核成功'));
  } catch (error) {
    console.error('审核保险申请错误:', error);
    res.status(500).json(responseFormat.error('审核保险申请失败'));
  }
};

// 删除保险申请
const deleteApplication = async (req, res) => {
  try {
    const { id } = req.params;
    
    const application = await InsuranceApplication.findByPk(id);
    if (!application) {
      return res.status(404).json(responseFormat.error('保险申请不存在'));
    }
    
    await application.destroy();
    
    res.json(responseFormat.success(null, '保险申请删除成功'));
  } catch (error) {
    console.error('删除保险申请错误:', error);
    res.status(500).json(responseFormat.error('删除保险申请失败'));
  }
};

// 获取保险申请统计
const getApplicationStats = async (req, res) => {
  try {
    const stats = await InsuranceApplication.findAll({
      attributes: [
        'status',
        [InsuranceApplication.sequelize.fn('COUNT', InsuranceApplication.sequelize.col('id')), 'count']
      ],
      group: ['status']
    });
    
    const total = await InsuranceApplication.count();
    
    res.json(responseFormat.success({
      stats,
      total
    }, '获取保险申请统计成功'));
  } catch (error) {
    console.error('获取保险申请统计错误:', error);
    res.status(500).json(responseFormat.error('获取保险申请统计失败'));
  }
};

// 获取参保类型选项
const getInsuranceCategories = async (req, res) => {
  try {
    const categories = await InsuranceApplication.findAll({
      attributes: ['insurance_category'],
      where: {
        insurance_category: {
          [Op.ne]: null
        }
      },
      group: ['insurance_category'],
      raw: true
    });

    const categoryList = categories.map(item => item.insurance_category).filter(Boolean);
    
    // 添加一些常用的参保类型
    const defaultCategories = ['牛', '羊', '猪', '鸡', '鸭', '鹅'];
    const allCategories = [...new Set([...defaultCategories, ...categoryList])];

    res.json(responseFormat.success(allCategories, '获取参保类型选项成功'));
  } catch (error) {
    console.error('获取参保类型选项错误:', error);
    res.status(500).json(responseFormat.error('获取参保类型选项失败'));
  }
};

// 导出保险申请数据
const exportApplications = async (req, res) => {
  try {
    const ExcelJS = require('exceljs');
    const { 
      page = 1, 
      limit = 10000,  // 增加导出数量限制
      applicantName, 
      insuranceType, 
      insuranceCategory, 
      status 
    } = req.query;

    const where = {};
    
    if (applicantName) {
      where.applicant_name = { [Op.like]: `%${applicantName}%` };
    }
    if (insuranceType) {
      where.insurance_type = insuranceType;
    }
    if (insuranceCategory) {
      where.insurance_category = insuranceCategory;
    }
    if (status) {
      where.status = status;
    }

    const applications = await InsuranceApplication.findAll({
      where,
      include: [
        {
          model: InsuranceType,
          as: 'insurance_type',
          attributes: ['id', 'name', 'description'],
          required: false
        },
        {
          model: User,
          as: 'reviewer',
          attributes: ['id', 'username', 'real_name'],
          required: false
        }
      ],
      order: [['created_at', 'DESC']],
      limit: parseInt(limit),
      offset: (parseInt(page) - 1) * parseInt(limit)
    });

    // 将Sequelize实例转换为纯对象
    const plainApplications = applications.map(app => app.toJSON());

    // 创建Excel工作簿
    const workbook = new ExcelJS.Workbook();
    const worksheet = workbook.addWorksheet('保险申请列表');

    // 状态映射
    const statusMap = {
      'pending': '待审核',
      'initial_approved': '初审通过',
      'under_review': '复审中',
      'approved': '已通过',
      'rejected': '已拒绝'
    };

    // 定义列（包含所有字段）
    worksheet.columns = [
      { header: 'ID', key: 'id', width: 8 },
      { header: '申请编号', key: 'application_no', width: 18 },
      { header: '客户姓名', key: 'customer_name', width: 12 },
      { header: '身份证号', key: 'customer_id_card', width: 20 },
      { header: '联系电话', key: 'customer_phone', width: 15 },
      { header: '客户地址', key: 'customer_address', width: 30 },
      { header: '参保类型', key: 'insurance_category', width: 12 },
      { header: '保险类型ID', key: 'insurance_type_id', width: 12 },
      { header: '保险类型名称', key: 'insurance_type_name', width: 15 },
      { header: '保险类型说明', key: 'insurance_type_description', width: 25 },
      { header: '申请数量', key: 'application_quantity', width: 12 },
      { header: '申请金额', key: 'application_amount', width: 15 },
      { header: '申请日期', key: 'application_date', width: 20 },
      { header: '状态', key: 'status', width: 12 },
      { header: '审核人ID', key: 'reviewer_id', width: 10 },
      { header: '审核人姓名', key: 'reviewer_name', width: 12 },
      { header: '审核日期', key: 'review_date', width: 20 },
      { header: '审核意见', key: 'review_notes', width: 30 },
      { header: '文档附件', key: 'documents', width: 30 },
      { header: '备注', key: 'remarks', width: 30 },
      { header: '创建时间', key: 'createdAt', width: 20 },
      { header: '更新时间', key: 'updatedAt', 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' };

    // 添加数据行
    plainApplications.forEach(app => {
      worksheet.addRow({
        id: app.id || '',
        application_no: app.application_no || '',
        customer_name: app.customer_name || '',
        customer_id_card: app.customer_id_card || '',
        customer_phone: app.customer_phone || '',
        customer_address: app.customer_address || '',
        insurance_category: app.insurance_category || '',
        insurance_type_id: app.insurance_type_id || '',
        insurance_type_name: app.insurance_type?.name || '',
        insurance_type_description: app.insurance_type?.description || '',
        application_quantity: app.application_quantity || '',
        application_amount: app.application_amount || '',
        application_date: app.application_date || '',
        status: statusMap[app.status] || app.status || '',
        reviewer_id: app.reviewer_id || '',
        reviewer_name: app.reviewer?.real_name || '',
        review_date: app.review_date || '',
        review_notes: app.review_notes || '',
        documents: app.documents || '',
        remarks: app.remarks || '',
        createdAt: app.createdAt || '',
        updatedAt: app.updatedAt || ''
      });
    });

    // 设置数据行样式
    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="insurance_applications_${new Date().toISOString().slice(0, 10)}.xlsx"`);
    
    // 发送文件
    res.send(buffer);
  } catch (error) {
    console.error('导出保险申请数据错误:', error);
    res.status(500).json(responseFormat.error('导出保险申请数据失败'));
  }
};

module.exports = {
  getApplications,
  createApplication,
  getApplicationById,
  updateApplication,
  reviewApplication,
  deleteApplication,
  getApplicationStats,
  getInsuranceCategories,
  exportApplications
};