const { InsuranceType } = require('../models');
const { Op } = require('sequelize');
const responseFormat = require('../utils/response');
const ExcelExport = require('../utils/excelExport');

// 获取保险类型列表
const getInsuranceTypes = async (req, res) => {
  const requestStartTime = new Date();
  
  try {
    // ========== 后端接收数据日志 ==========
    console.log('🔵 [后端] 接收到获取险种列表请求');
    console.log('📥 [后端] 请求时间:', requestStartTime.toISOString());
    console.log('📥 [后端] 请求方法:', req.method);
    console.log('📥 [后端] 请求路径:', req.path);
    console.log('📥 [后端] 查询参数:', JSON.stringify(req.query, null, 2));
    console.log('📥 [后端] 用户信息:', req.user ? {
      id: req.user.id,
      username: req.user.username,
      role: req.user.role
    } : '未认证用户');
    
    const { 
      page = 1, 
      pageSize = 10, 
      name, 
      status, 
      applicable_livestock, 
      service_area, 
      on_sale_status 
    } = req.query;
    
    // ========== 后端数据处理日志 ==========
    console.log('⚙️ [后端] 开始处理查询参数');
    console.log('⚙️ [后端] 原始查询参数:', {
      page, pageSize, name, status, applicable_livestock, service_area, on_sale_status
    });
    
    const processedParams = {
      page: parseInt(page) || 1,
      pageSize: parseInt(pageSize) || 10,
      name: name ? String(name).trim() : null,
      status: status ? String(status).trim() : null,
      applicable_livestock: applicable_livestock ? String(applicable_livestock).trim() : null,
      service_area: service_area ? String(service_area).trim() : null,
      on_sale_status: on_sale_status !== undefined && on_sale_status !== '' ? on_sale_status === 'true' : null
    };
    
    console.log('⚙️ [后端] 处理后的查询参数:', processedParams);
    
    const offset = (processedParams.page - 1) * processedParams.pageSize;
    console.log('⚙️ [后端] 分页计算 - offset:', offset, 'limit:', processedParams.pageSize);
    
    const whereClause = {};
    if (processedParams.name) {
      whereClause.name = processedParams.name; // 精确查询
    }
    if (processedParams.status) {
      whereClause.status = processedParams.status;
    }
    if (processedParams.applicable_livestock) {
      whereClause.applicable_livestock = { [Op.like]: `%${processedParams.applicable_livestock}%` };
    }
    if (processedParams.service_area) {
      whereClause.service_area = { [Op.like]: `%${processedParams.service_area}%` };
    }
    if (processedParams.on_sale_status !== null) {
      whereClause.on_sale_status = processedParams.on_sale_status;
    }
    
    console.log('⚙️ [后端] 构建的WHERE条件:', whereClause);
    
    const queryOptions = {
      where: whereClause,
      limit: processedParams.pageSize,
      offset: offset,
      order: [['add_time', 'DESC'], ['created_at', 'DESC']]
    };
    
    console.log('⚙️ [后端] 数据库查询选项:', queryOptions);
    console.log('⚙️ [后端] 开始执行数据库查询...');
    
    const { count, rows } = await InsuranceType.findAndCountAll(queryOptions);
    
    console.log('✅ [后端] 数据库查询完成');
    console.log('✅ [后端] 查询结果统计:', {
      totalCount: count,
      returnedRows: rows.length,
      currentPage: processedParams.page,
      pageSize: processedParams.pageSize,
      totalPages: Math.ceil(count / processedParams.pageSize)
    });
    
    // ========== 后端响应数据日志 ==========
    const responseEndTime = new Date();
    const processingTime = responseEndTime - requestStartTime;
    
    const paginationData = {
      page: processedParams.page,
      limit: processedParams.pageSize,
      total: count
    };
    
    const successResponse = responseFormat.pagination(rows, paginationData, '获取险种列表成功');
    
    console.log('📤 [后端] 准备发送成功响应');
    console.log('📤 [后端] 响应时间:', responseEndTime.toISOString());
    console.log('📤 [后端] 处理耗时:', processingTime + 'ms');
    console.log('📤 [后端] 响应状态码:', 200);
    console.log('📤 [后端] 响应数据结构:', {
      success: successResponse.success,
      message: successResponse.message,
      dataType: typeof successResponse.data,
      dataLength: Array.isArray(successResponse.data) ? successResponse.data.length : 'not array',
      paginationType: typeof successResponse.pagination,
      paginationKeys: successResponse.pagination ? Object.keys(successResponse.pagination) : 'no pagination'
    });
    console.log('📤 [后端] 分页信息:', successResponse.pagination);
    console.log('📤 [后端] 返回的险种数据概览:', rows.map(item => ({
      id: item.id,
      name: item.name,
      status: item.status,
      on_sale_status: item.on_sale_status
    })));
    
    res.json(successResponse);
    
  } catch (error) {
    // ========== 后端错误处理日志 ==========
    const errorEndTime = new Date();
    const processingTime = errorEndTime - requestStartTime;
    
    console.error('❌ [后端] 获取险种列表发生错误');
    console.error('❌ [后端] 错误时间:', errorEndTime.toISOString());
    console.error('❌ [后端] 处理耗时:', processingTime + 'ms');
    console.error('❌ [后端] 错误类型:', error.name);
    console.error('❌ [后端] 错误消息:', error.message);
    console.error('❌ [后端] 错误堆栈:', error.stack);
    
    const errorResponse = responseFormat.error('获取险种列表失败');
    
    console.log('📤 [后端] 发送错误响应:', {
      statusCode: 500,
      response: errorResponse
    });
    
    res.status(500).json(errorResponse);
  }
};

// 获取单个保险类型详情
const getInsuranceTypeById = async (req, res) => {
  try {
    const { id } = req.params;
    const insuranceType = await InsuranceType.findByPk(id);
    
    if (!insuranceType) {
      return res.status(404).json(responseFormat.error('保险类型不存在'));
    }
    
    res.json(responseFormat.success(insuranceType, '获取保险类型详情成功'));
  } catch (error) {
    console.error('获取保险类型详情错误:', error);
    res.status(500).json(responseFormat.error('获取保险类型详情失败'));
  }
};

// 创建险种
const createInsuranceType = async (req, res) => {
  const requestStartTime = new Date();
  
  try {
    // ========== 后端接收数据日志 ==========
    console.log('🔵 [后端] 接收到创建险种请求');
    console.log('📥 [后端] 请求时间:', requestStartTime.toISOString());
    console.log('📥 [后端] 请求方法:', req.method);
    console.log('📥 [后端] 请求路径:', req.path);
    console.log('📥 [后端] 请求头信息:', {
      'content-type': req.headers['content-type'],
      'authorization': req.headers.authorization ? '已提供' : '未提供',
      'user-agent': req.headers['user-agent']
    });
    console.log('📥 [后端] 原始请求体数据:', JSON.stringify(req.body, null, 2));
    console.log('📥 [后端] 用户信息:', req.user ? {
      id: req.user.id,
      username: req.user.username,
      role: req.user.role
    } : '未认证用户');
    
    const {
      name,
      description,
      applicable_livestock,
      insurance_term,
      policy_form,
      coverage_amount_min,
      coverage_amount_max,
      premium_rate,
      service_area,
      add_time,
      on_sale_status = true,
      sort_order = 0,
      remarks,
      status = 'active'
    } = req.body;
    
    // ========== 后端数据处理日志 ==========
    console.log('⚙️ [后端] 开始数据处理和验证');
    console.log('⚙️ [后端] 解构后的数据:', {
      name,
      description,
      applicable_livestock,
      insurance_term,
      policy_form,
      coverage_amount_min,
      coverage_amount_max,
      premium_rate,
      service_area,
      add_time,
      on_sale_status,
      sort_order,
      remarks,
      status
    });
    
    // 数据类型验证和转换
    const processedData = {
      name: name ? String(name).trim() : null,
      description: description ? String(description).trim() : null,
      applicable_livestock: Array.isArray(applicable_livestock) ? 
                           applicable_livestock.join(',') : 
                           (applicable_livestock ? String(applicable_livestock).trim() : null),
      insurance_term: insurance_term ? Number(insurance_term) : null,
      policy_form: policy_form ? String(policy_form).trim() : null,
      coverage_amount_min: coverage_amount_min ? Number(coverage_amount_min) : null,
      coverage_amount_max: coverage_amount_max ? Number(coverage_amount_max) : null,
      premium_rate: premium_rate ? Number(premium_rate) : null,
      service_area: service_area ? String(service_area).trim() : null,
      add_time: add_time ? new Date(add_time) : new Date(),
      on_sale_status: Boolean(on_sale_status),
      sort_order: sort_order ? Number(sort_order) : 0,
      remarks: remarks ? String(remarks).trim() : null,
      status: status || 'active'
    };
    
    console.log('⚙️ [后端] 处理后的数据:', processedData);
    
    // 检查名称是否已存在
    console.log('⚙️ [后端] 检查险种名称是否已存在:', processedData.name);
    const existingType = await InsuranceType.findOne({ where: { name: processedData.name } });
    
    if (existingType) {
      console.log('❌ [后端] 险种名称已存在:', existingType.name);
      const errorResponse = responseFormat.error('险种名称已存在');
      console.log('📤 [后端] 发送错误响应:', errorResponse);
      return res.status(400).json(errorResponse);
    }
    
    console.log('✅ [后端] 险种名称验证通过，开始创建数据');
    
    // 准备数据库插入数据
    const dbInsertData = {
      ...processedData,
      created_by: req.user?.id || null
    };
    
    console.log('⚙️ [后端] 准备插入数据库的数据:', dbInsertData);
    
    const insuranceType = await InsuranceType.create(dbInsertData);
    
    console.log('✅ [后端] 险种创建成功，数据库返回:', {
      id: insuranceType.id,
      name: insuranceType.name,
      created_at: insuranceType.created_at
    });
    
    // ========== 后端响应数据日志 ==========
    const responseEndTime = new Date();
    const processingTime = responseEndTime - requestStartTime;
    
    const successResponse = responseFormat.success(insuranceType, '创建险种成功');
    
    console.log('📤 [后端] 准备发送成功响应');
    console.log('📤 [后端] 响应时间:', responseEndTime.toISOString());
    console.log('📤 [后端] 处理耗时:', processingTime + 'ms');
    console.log('📤 [后端] 响应状态码:', 201);
    console.log('📤 [后端] 响应数据结构:', {
      success: successResponse.success,
      message: successResponse.message,
      dataType: typeof successResponse.data,
      dataId: successResponse.data?.id,
      dataKeys: Object.keys(successResponse.data || {})
    });
    console.log('📤 [后端] 完整响应数据:', JSON.stringify(successResponse, null, 2));
    
    res.status(201).json(successResponse);
    
  } catch (error) {
    // ========== 后端错误处理日志 ==========
    const errorEndTime = new Date();
    const processingTime = errorEndTime - requestStartTime;
    
    console.error('❌ [后端] 创建险种发生错误');
    console.error('❌ [后端] 错误时间:', errorEndTime.toISOString());
    console.error('❌ [后端] 处理耗时:', processingTime + 'ms');
    console.error('❌ [后端] 错误类型:', error.name);
    console.error('❌ [后端] 错误消息:', error.message);
    console.error('❌ [后端] 错误堆栈:', error.stack);
    
    let errorResponse;
    let statusCode = 500;
    
    if (error.name === 'SequelizeValidationError') {
      const messages = error.errors.map(err => err.message);
      errorResponse = responseFormat.error(messages.join(', '));
      statusCode = 400;
      console.error('❌ [后端] 数据验证错误:', messages);
    } else {
      errorResponse = responseFormat.error('创建险种失败');
      console.error('❌ [后端] 服务器内部错误');
    }
    
    console.log('📤 [后端] 发送错误响应:', {
      statusCode,
      response: errorResponse
    });
    
    res.status(statusCode).json(errorResponse);
  }
};

// 更新险种
const updateInsuranceType = async (req, res) => {
  try {
    const { id } = req.params;
    const {
      name,
      description,
      applicable_livestock,
      insurance_term,
      policy_form,
      coverage_amount_min,
      coverage_amount_max,
      premium_rate,
      service_area,
      add_time,
      on_sale_status,
      sort_order,
      remarks,
      status
    } = req.body;
    
    const insuranceType = await InsuranceType.findByPk(id);
    if (!insuranceType) {
      return res.status(404).json(responseFormat.error('险种不存在'));
    }
    
    // 检查名称是否已被其他类型使用
    if (name && name !== insuranceType.name) {
      const existingType = await InsuranceType.findOne({ 
        where: { 
          name,
          id: { [Op.ne]: id }
        } 
      });
      if (existingType) {
        return res.status(400).json(responseFormat.error('险种名称已存在'));
      }
    }
    
    // 处理applicable_livestock数据类型转换
    let processedApplicableLivestock = insuranceType.applicable_livestock;
    if (applicable_livestock !== undefined) {
      processedApplicableLivestock = Array.isArray(applicable_livestock) ? 
                                   applicable_livestock.join(',') : 
                                   (applicable_livestock ? String(applicable_livestock).trim() : null);
    }

    await insuranceType.update({
      name: name || insuranceType.name,
      description: description !== undefined ? description : insuranceType.description,
      applicable_livestock: processedApplicableLivestock,
      insurance_term: insurance_term !== undefined ? insurance_term : insuranceType.insurance_term,
      policy_form: policy_form !== undefined ? policy_form : insuranceType.policy_form,
      coverage_amount_min: coverage_amount_min !== undefined ? coverage_amount_min : insuranceType.coverage_amount_min,
      coverage_amount_max: coverage_amount_max !== undefined ? coverage_amount_max : insuranceType.coverage_amount_max,
      premium_rate: premium_rate !== undefined ? premium_rate : insuranceType.premium_rate,
      service_area: service_area !== undefined ? service_area : insuranceType.service_area,
      add_time: add_time !== undefined ? add_time : insuranceType.add_time,
      on_sale_status: on_sale_status !== undefined ? on_sale_status : insuranceType.on_sale_status,
      sort_order: sort_order !== undefined ? sort_order : insuranceType.sort_order,
      remarks: remarks !== undefined ? remarks : insuranceType.remarks,
      status: status || insuranceType.status,
      updated_by: req.user?.id
    });
    
    res.json(responseFormat.success(insuranceType, '更新险种成功'));
  } catch (error) {
    console.error('更新险种错误:', error);
    if (error.name === 'SequelizeValidationError') {
      const messages = error.errors.map(err => err.message);
      return res.status(400).json(responseFormat.error(messages.join(', ')));
    }
    res.status(500).json(responseFormat.error('更新险种失败'));
  }
};

// 删除险种
const deleteInsuranceType = async (req, res) => {
  try {
    const { id } = req.params;
    
    const insuranceType = await InsuranceType.findByPk(id);
    if (!insuranceType) {
      return res.status(404).json(responseFormat.error('险种不存在'));
    }
    
    // 检查是否有相关的保险申请
    const hasApplications = await insuranceType.countApplications();
    if (hasApplications > 0) {
      return res.status(400).json(responseFormat.error('该险种下存在保险申请，无法删除', 400));
    }
    
    await insuranceType.destroy();
    res.json(responseFormat.success(null, '删除险种成功'));
  } catch (error) {
    console.error('删除险种错误:', error);
    
    // 处理外键约束错误
    if (error.name === 'SequelizeForeignKeyConstraintError') {
      return res.status(400).json(responseFormat.error('该险种下存在相关数据，无法删除', 400));
    }
    
    res.status(500).json(responseFormat.error('删除险种失败'));
  }
};

// 更新险种状态
const updateInsuranceTypeStatus = async (req, res) => {
  try {
    const { id } = req.params;
    const { status, on_sale_status } = req.body;
    
    const insuranceType = await InsuranceType.findByPk(id);
    if (!insuranceType) {
      return res.status(404).json(responseFormat.error('险种不存在'));
    }
    
    const updateData = { updated_by: req.user?.id };
    if (status !== undefined) updateData.status = status;
    if (on_sale_status !== undefined) updateData.on_sale_status = on_sale_status;
    
    await insuranceType.update(updateData);
    res.json(responseFormat.success(insuranceType, '更新险种状态成功'));
  } catch (error) {
    console.error('更新险种状态错误:', error);
    res.status(500).json(responseFormat.error('更新险种状态失败'));
  }
};

// 导出保险类型列表到Excel
const exportToExcel = async (req, res) => {
  try {
    const { name, status } = req.query;
    
    const where = {};
    if (name) where.name = { [Op.like]: `%${name}%` };
    if (status) where.status = status;
    
    const types = await InsuranceType.findAll({
      where,
      order: [['created_at', 'DESC']],
      raw: true
    });
    
    const statusMap = { active: '启用', inactive: '停用' };
    
    const exportData = types.map(type => ({
      name: type.name || '',
      coverage_amount: type.coverage_amount || 0,
      premium_rate: type.premium_rate || 0,
      applicable_livestock: type.applicable_livestock || '',
      description: type.description || '',
      status: ExcelExport.formatStatus(type.status, statusMap),
      created_at: ExcelExport.formatDate(type.created_at)
    }));
    
    const columns = [
      { header: '险种名称', key: 'name', width: 20 },
      { header: '保额', key: 'coverage_amount', width: 15 },
      { header: '费率', key: 'premium_rate', width: 10 },
      { header: '适用牲畜', key: 'applicable_livestock', width: 20 },
      { header: '描述', key: 'description', width: 40 },
      { header: '状态', key: 'status', width: 10 },
      { header: '创建时间', key: 'created_at', width: 20 }
    ];
    
    const buffer = await ExcelExport.exportToExcel(exportData, columns, '保险类型列表');
    res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
    res.setHeader('Content-Disposition', `attachment; filename=insurance_types_${Date.now()}.xlsx`);
    res.send(buffer);
  } catch (error) {
    console.error('导出保险类型失败:', error);
    res.status(500).json(responseFormat.error('导出失败'));
  }
};

module.exports = {
  getInsuranceTypes,
  getInsuranceTypeById,
  createInsuranceType,
  updateInsuranceType,
  deleteInsuranceType,
  updateInsuranceTypeStatus,
  exportToExcel
};