const { LoanProduct, User } = require('../models');
const { Op } = require('sequelize');
const { sequelize } = require('../config/database');

// 获取贷款商品列表
const getLoanProducts = async (req, res) => {
  try {
    const {
      page = 1,
      limit = 10,
      search = '',
      onSaleStatus,
      riskLevel,
      sortBy = 'createdAt',
      sortOrder = 'DESC'
    } = req.query;

    const offset = (page - 1) * limit;
    const whereClause = {};

    // 字段映射 - 将模型属性名映射到数据库字段名
    const fieldMapping = {
      'createdAt': 'created_at',
      'updatedAt': 'updated_at',
      'productName': 'product_name',
      'loanAmount': 'loan_amount',
      'loanTerm': 'loan_term',
      'interestRate': 'interest_rate',
      'serviceArea': 'service_area',
      'servicePhone': 'service_phone',
      'onSaleStatus': 'on_sale_status',
      'riskLevel': 'risk_level'
    };

    // 搜索条件
    if (search) {
      whereClause[Op.or] = [
        { product_name: { [Op.like]: `%${search}%` } },
        { service_area: { [Op.like]: `%${search}%` } },
        { service_phone: { [Op.like]: `%${search}%` } }
      ];
    }

    // 在售状态筛选
    if (onSaleStatus !== undefined) {
      whereClause.on_sale_status = onSaleStatus === 'true';
    }

    // 风险等级筛选
    if (riskLevel) {
      whereClause.risk_level = riskLevel;
    }

    const { count, rows } = await LoanProduct.findAndCountAll({
      where: whereClause,
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'real_name']
        },
        {
          model: User,
          as: 'updater',
          attributes: ['id', 'username', 'real_name']
        }
      ],
      order: [[fieldMapping[sortBy] || sortBy, sortOrder.toUpperCase()]],
      limit: parseInt(limit),
      offset: parseInt(offset)
    });

    const totalPages = Math.ceil(count / limit);

    res.json({
      success: true,
      message: '获取贷款商品列表成功',
      data: {
        products: rows,
        pagination: {
          current: parseInt(page),
          pageSize: parseInt(limit),
          total: count,
          totalPages,
          hasNextPage: page < totalPages,
          hasPrevPage: page > 1
        }
      }
    });
  } catch (error) {
    console.error('获取贷款商品列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取贷款商品列表失败',
      error: error.message
    });
  }
};

// 根据ID获取贷款商品详情
const getLoanProductById = async (req, res) => {
  try {
    const { id } = req.params;

    const product = await LoanProduct.findByPk(id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'real_name']
        },
        {
          model: User,
          as: 'updater',
          attributes: ['id', 'username', 'real_name']
        }
      ]
    });

    if (!product) {
      return res.status(404).json({
        success: false,
        message: '贷款商品不存在'
      });
    }

    res.json({
      success: true,
      message: '获取贷款商品详情成功',
      data: product
    });
  } catch (error) {
    console.error('获取贷款商品详情失败:', error);
    res.status(500).json({
      success: false,
      message: '获取贷款商品详情失败',
      error: error.message
    });
  }
};

// 创建贷款商品
const createLoanProduct = async (req, res) => {
  try {
    const {
      productName,
      loanAmount,
      loanTerm,
      interestRate,
      serviceArea,
      servicePhone,
      productDescription,
      applicationRequirements,
      requiredDocuments,
      approvalProcess,
      riskLevel = 'MEDIUM',
      minLoanAmount,
      maxLoanAmount
    } = req.body;

    // 验证必填字段
    if (!productName || !loanAmount || !loanTerm || !interestRate || !serviceArea || !servicePhone) {
      return res.status(400).json({
        success: false,
        message: '请填写所有必填字段'
      });
    }

    // 验证产品名称唯一性
    const existingProduct = await LoanProduct.findOne({
      where: { productName }
    });

    if (existingProduct) {
      return res.status(400).json({
        success: false,
        message: '贷款产品名称已存在'
      });
    }

    // 验证数值字段
    if (loanTerm <= 0) {
      return res.status(400).json({
        success: false,
        message: '贷款周期必须大于0'
      });
    }

    if (interestRate < 0 || interestRate > 100) {
      return res.status(400).json({
        success: false,
        message: '贷款利率必须在0-100之间'
      });
    }

    if (minLoanAmount && maxLoanAmount && minLoanAmount > maxLoanAmount) {
      return res.status(400).json({
        success: false,
        message: '最小贷款金额不能大于最大贷款金额'
      });
    }

    // 检查用户信息
    if (!req.user || !req.user.id) {
      return res.status(401).json({
        success: false,
        message: '用户信息无效'
      });
    }

    const product = await LoanProduct.create({
      productName,
      loanAmount,
      loanTerm: parseInt(loanTerm),
      interestRate: parseFloat(interestRate),
      serviceArea,
      servicePhone,
      productDescription,
      applicationRequirements,
      requiredDocuments,
      approvalProcess,
      riskLevel,
      minLoanAmount: minLoanAmount ? parseFloat(minLoanAmount) : null,
      maxLoanAmount: maxLoanAmount ? parseFloat(maxLoanAmount) : null,
      createdBy: req.user.id,
      updatedBy: req.user.id
    });

    // 获取创建后的完整信息
    const createdProduct = await LoanProduct.findByPk(product.id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'real_name']
        }
      ]
    });

    res.status(201).json({
      success: true,
      message: '创建贷款商品成功',
      data: createdProduct
    });
  } catch (error) {
    console.error('创建贷款商品失败:', error);
    res.status(500).json({
      success: false,
      message: '创建贷款商品失败',
      error: error.message
    });
  }
};

// 更新贷款商品
const updateLoanProduct = async (req, res) => {
  try {
    const { id } = req.params;
    const updateData = req.body;

    const product = await LoanProduct.findByPk(id);
    if (!product) {
      return res.status(404).json({
        success: false,
        message: '贷款商品不存在'
      });
    }

    // 如果更新产品名称，检查唯一性
    if (updateData.productName && updateData.productName !== product.productName) {
      const existingProduct = await LoanProduct.findOne({
        where: { 
          productName: updateData.productName,
          id: { [Op.ne]: id }
        }
      });

      if (existingProduct) {
        return res.status(400).json({
          success: false,
          message: '贷款产品名称已存在'
        });
      }
    }

    // 验证数值字段
    if (updateData.loanTerm && updateData.loanTerm <= 0) {
      return res.status(400).json({
        success: false,
        message: '贷款周期必须大于0'
      });
    }

    if (updateData.interestRate && (updateData.interestRate < 0 || updateData.interestRate > 100)) {
      return res.status(400).json({
        success: false,
        message: '贷款利率必须在0-100之间'
      });
    }

    if (updateData.minLoanAmount && updateData.maxLoanAmount && 
        updateData.minLoanAmount > updateData.maxLoanAmount) {
      return res.status(400).json({
        success: false,
        message: '最小贷款金额不能大于最大贷款金额'
      });
    }

    // 更新数据
    Object.keys(updateData).forEach(key => {
      if (updateData[key] !== undefined) {
        product[key] = updateData[key];
      }
    });

    product.updatedBy = req.user.id;
    await product.save();

    // 获取更新后的完整信息
    const updatedProduct = await LoanProduct.findByPk(id, {
      include: [
        {
          model: User,
          as: 'creator',
          attributes: ['id', 'username', 'real_name']
        },
        {
          model: User,
          as: 'updater',
          attributes: ['id', 'username', 'real_name']
        }
      ]
    });

    res.json({
      success: true,
      message: '更新贷款商品成功',
      data: updatedProduct
    });
  } catch (error) {
    console.error('更新贷款商品失败:', error);
    res.status(500).json({
      success: false,
      message: '更新贷款商品失败',
      error: error.message
    });
  }
};

// 删除贷款商品
const deleteLoanProduct = async (req, res) => {
  try {
    const { id } = req.params;

    const product = await LoanProduct.findByPk(id);
    if (!product) {
      return res.status(404).json({
        success: false,
        message: '贷款商品不存在'
      });
    }

    await product.destroy();

    res.json({
      success: true,
      message: '删除贷款商品成功'
    });
  } catch (error) {
    console.error('删除贷款商品失败:', error);
    res.status(500).json({
      success: false,
      message: '删除贷款商品失败',
      error: error.message
    });
  }
};

// 获取贷款商品统计信息
const getLoanProductStats = async (req, res) => {
  try {
    const totalProducts = await LoanProduct.count();
    const onSaleProducts = await LoanProduct.count({ where: { onSaleStatus: true } });
    const offSaleProducts = await LoanProduct.count({ where: { onSaleStatus: false } });
    
    const riskLevelStats = await LoanProduct.findAll({
      attributes: [
        'riskLevel',
        [LoanProduct.sequelize.fn('COUNT', LoanProduct.sequelize.col('id')), 'count']
      ],
      group: ['riskLevel']
    });

    const totalCustomers = await LoanProduct.sum('totalCustomers');
    const supervisionCustomers = await LoanProduct.sum('supervisionCustomers');
    const completedCustomers = await LoanProduct.sum('completedCustomers');

    res.json({
      success: true,
      message: '获取贷款商品统计成功',
      data: {
        totalProducts,
        onSaleProducts,
        offSaleProducts,
        riskLevelStats,
        totalCustomers: totalCustomers || 0,
        supervisionCustomers: supervisionCustomers || 0,
        completedCustomers: completedCustomers || 0
      }
    });
  } catch (error) {
    console.error('获取贷款商品统计失败:', error);
    res.status(500).json({
      success: false,
      message: '获取贷款商品统计失败',
      error: error.message
    });
  }
};

// 批量更新在售状态
const batchUpdateStatus = async (req, res) => {
  try {
    const { ids, onSaleStatus } = req.body;

    if (!Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请选择要更新的贷款商品'
      });
    }

    if (typeof onSaleStatus !== 'boolean') {
      return res.status(400).json({
        success: false,
        message: '在售状态参数无效'
      });
    }

    await LoanProduct.update(
      { 
        onSaleStatus,
        updatedBy: req.user.id
      },
      { 
        where: { id: { [Op.in]: ids } }
      }
    );

    res.json({
      success: true,
      message: `批量${onSaleStatus ? '启用' : '停用'}贷款商品成功`
    });
  } catch (error) {
    console.error('批量更新状态失败:', error);
    res.status(500).json({
      success: false,
      message: '批量更新状态失败',
      error: error.message
    });
  }
};

// 批量删除贷款商品
const batchDelete = async (req, res) => {
  try {
    const { ids } = req.body;

    if (!Array.isArray(ids) || ids.length === 0) {
      return res.status(400).json({
        success: false,
        message: '请选择要删除的贷款商品'
      });
    }

    await LoanProduct.destroy({
      where: { id: { [Op.in]: ids } }
    });

    res.json({
      success: true,
      message: '批量删除贷款商品成功'
    });
  } catch (error) {
    console.error('批量删除失败:', error);
    res.status(500).json({
      success: false,
      message: '批量删除失败',
      error: error.message
    });
  }
};

module.exports = {
  getLoanProducts,
  getLoanProductById,
  createLoanProduct,
  updateLoanProduct,
  deleteLoanProduct,
  getLoanProductStats,
  batchUpdateStatus,
  batchDelete
};