const { validationResult } = require('express-validator');
const { Op } = require('sequelize');
const HarmlessRegistration = require('../models/HarmlessRegistration');

// 获取无害化登记列表
exports.getList = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, keyword = '', startDate = '', endDate = '' } = req.query;
    const offset = (page - 1) * pageSize;
    
    const where = {};
    
    if (keyword) {
      where.registrationNumber = { [Op.like]: `%${keyword}%` };
    }
    
    if (startDate) {
      where.processingDate = where.processingDate || {};
      where.processingDate[Op.gte] = startDate;
    }
    
    if (endDate) {
      where.processingDate = where.processingDate || {};
      where.processingDate[Op.lte] = endDate;
    }

    const result = await HarmlessRegistration.findAndCountAll({
      where,
      limit: parseInt(pageSize),
      offset: parseInt(offset),
      order: [['createTime', 'DESC']]
    });

    res.json({
      code: 200,
      message: '获取成功',
      data: {
        list: result.rows,
        total: result.count
      }
    });
  } catch (error) {
    console.error('获取无害化登记列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取失败',
      error: error.message
    });
  }
};

// 获取无害化登记详情
exports.getDetail = async (req, res) => {
  try {
    const { id } = req.params;
    const registration = await HarmlessRegistration.findByPk(id);
    
    if (!registration) {
      return res.status(404).json({
        code: 404,
        message: '无害化登记不存在'
      });
    }

    res.json({
      code: 200,
      message: '获取成功',
      data: registration
    });
  } catch (error) {
    console.error('获取无害化登记详情失败:', error);
    res.status(500).json({
      code: 500,
      message: '获取失败',
      error: error.message
    });
  }
};

// 创建无害化登记
exports.create = async (req, res) => {
  try {
    // 验证请求参数
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      });
    }

    const { registrationNumber, animalType, quantity, reason, 
            processingMethod, processingPlace, processingDate, registrant, status } = req.body;

    // 检查登记编号是否已存在
    const existingRegistration = await HarmlessRegistration.findOne({
      where: { registrationNumber }
    });
    
    if (existingRegistration) {
      return res.status(400).json({
        code: 400,
        message: '登记编号已存在'
      });
    }

    const registration = await HarmlessRegistration.create({
      registrationNumber,
      animalType,
      quantity: parseInt(quantity),
      reason,
      processingMethod,
      processingPlace,
      processingDate,
      registrant,
      status: status || '待处理',
      createTime: new Date(),
      updateTime: new Date()
    });

    res.json({
      code: 200,
      message: '创建成功',
      data: registration
    });
  } catch (error) {
    console.error('创建无害化登记失败:', error);
    res.status(500).json({
      code: 500,
      message: '创建失败',
      error: error.message
    });
  }
};

// 更新无害化登记
exports.update = async (req, res) => {
  try {
    const { id } = req.params;
    const errors = validationResult(req);
    
    if (!errors.isEmpty()) {
      return res.status(400).json({
        code: 400,
        message: '参数验证失败',
        errors: errors.array()
      });
    }

    const registration = await HarmlessRegistration.findByPk(id);
    
    if (!registration) {
      return res.status(404).json({
        code: 404,
        message: '无害化登记不存在'
      });
    }

    const { registrationNumber, animalType, quantity, reason, 
            processingMethod, processingPlace, processingDate, registrant, status } = req.body;

    // 检查登记编号是否已被其他记录使用
    if (registrationNumber && registrationNumber !== registration.registrationNumber) {
      const existingRegistration = await HarmlessRegistration.findOne({
        where: { 
          registrationNumber, 
          id: { [Op.ne]: id }
        }
      });
      
      if (existingRegistration) {
        return res.status(400).json({
          code: 400,
          message: '登记编号已存在'
        });
      }
    }

    await registration.update({
      registrationNumber: registrationNumber || registration.registrationNumber,
      animalType: animalType || registration.animalType,
      quantity: quantity !== undefined ? parseInt(quantity) : registration.quantity,
      reason: reason || registration.reason,
      processingMethod: processingMethod || registration.processingMethod,
      processingPlace: processingPlace || registration.processingPlace,
      processingDate: processingDate || registration.processingDate,
      registrant: registrant || registration.registrant,
      status: status !== undefined ? status : registration.status,
      updateTime: new Date()
    });

    res.json({
      code: 200,
      message: '更新成功',
      data: registration
    });
  } catch (error) {
    console.error('更新无害化登记失败:', error);
    res.status(500).json({
      code: 500,
      message: '更新失败',
      error: error.message
    });
  }
};

// 删除无害化登记
exports.delete = async (req, res) => {
  try {
    const { id } = req.params;
    const registration = await HarmlessRegistration.findByPk(id);
    
    if (!registration) {
      return res.status(404).json({
        code: 404,
        message: '无害化登记不存在'
      });
    }

    await registration.destroy();

    res.json({
      code: 200,
      message: '删除成功'
    });
  } catch (error) {
    console.error('删除无害化登记失败:', error);
    res.status(500).json({
      code: 500,
      message: '删除失败',
      error: error.message
    });
  }
};