const { Op } = require('sequelize');
const Slaughterhouse = require('../models/Slaughterhouse');

// 查询屠宰场列表
exports.getSlaughterhouses = async (req, res) => {
  try {
    const { keyword, status, page = 1, pageSize = 10 } = req.query;
    
    const where = {};
    
    if (keyword) {
      where[Op.or] = [
        { name: { [Op.like]: `%${keyword}%` } },
        { contactPerson: { [Op.like]: `%${keyword}%` } },
        { contactPhone: { [Op.like]: `%${keyword}%` } },
        { licenseNumber: { [Op.like]: `%${keyword}%` } }
      ];
    }
    
    if (status) {
      where.status = status;
    }
    
    const { count, rows } = await Slaughterhouse.findAndCountAll({
      where,
      offset: (page - 1) * pageSize,
      limit: parseInt(pageSize),
      order: [['created_at', 'DESC']]
    });
    
    // 转换状态为中文显示
    const processedRows = rows.map(row => ({
      ...row.toJSON(),
      status: row.status === 'active' ? '正常' : row.status === 'inactive' ? '暂停营业' : row.status
    }));
    
    res.json({
      code: 200,
      data: {
        list: processedRows,
        total: count,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      },
      message: '查询成功'
    });
  } catch (error) {
    console.error('查询屠宰场列表失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
};

// 查询单个屠宰场详情
exports.getSlaughterhouseById = async (req, res) => {
  try {
    const { id } = req.params;
    
    const slaughterhouse = await Slaughterhouse.findByPk(id);
    
    if (!slaughterhouse) {
      return res.status(404).json({
        code: 404,
        message: '屠宰场不存在'
      });
    }
    
    // 转换状态为中文显示
    const processedSlaughterhouse = {
      ...slaughterhouse.toJSON(),
      status: slaughterhouse.status === 'active' ? '正常' : slaughterhouse.status === 'inactive' ? '暂停营业' : slaughterhouse.status
    };
    
    res.json({
      code: 200,
      data: processedSlaughterhouse,
      message: '查询成功'
    });
  } catch (error) {
    console.error('查询屠宰场详情失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
};

// 新增屠宰场
exports.createSlaughterhouse = async (req, res) => {
  try {
    const { name, address, contactPerson, contactPhone, licenseNumber, status } = req.body;
    
    // 验证必填字段
    if (!name || !address || !contactPerson || !contactPhone || !licenseNumber || !status) {
      return res.status(400).json({
        code: 400,
        message: '请填写所有必填字段'
      });
    }
    
    // 检查名称是否重复
    const existingSlaughterhouse = await Slaughterhouse.findOne({
      where: { name }
    });
    
    if (existingSlaughterhouse) {
      return res.status(400).json({
        code: 400,
        message: '该屠宰场名称已存在'
      });
    }
    
    // 检查许可证号是否重复
    const existingLicense = await Slaughterhouse.findOne({
      where: { licenseNumber }
    });
    
    if (existingLicense) {
      return res.status(400).json({
        code: 400,
        message: '该许可证号已存在'
      });
    }
    
    // 转换状态为英文存储
    const statusValue = status === '正常' ? 'active' : status === '暂停营业' ? 'inactive' : status;
    
    const slaughterhouse = await Slaughterhouse.create({
      name,
      address,
      contactPerson,
      contactPhone,
      licenseNumber,
      status: statusValue,
      createTime: new Date(),
      created_by: req.user?.id || null,
      updated_by: req.user?.id || null
    });
    
    res.json({
      code: 200,
      data: slaughterhouse,
      message: '新增成功'
    });
  } catch (error) {
    console.error('新增屠宰场失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误: ' + error.message
    });
  }
};

// 更新屠宰场
exports.updateSlaughterhouse = async (req, res) => {
  try {
    const { id } = req.params;
    const { name, address, contactPerson, contactPhone, licenseNumber, status } = req.body;
    
    const slaughterhouse = await Slaughterhouse.findByPk(id);
    
    if (!slaughterhouse) {
      return res.status(404).json({
        code: 404,
        message: '屠宰场不存在'
      });
    }
    
    // 检查名称是否重复（排除当前屠宰场）
    if (name && name !== slaughterhouse.name) {
      const existingSlaughterhouse = await Slaughterhouse.findOne({
        where: {
          name,
          id: { [Op.ne]: id }
        }
      });
      
      if (existingSlaughterhouse) {
        return res.status(400).json({
          code: 400,
          message: '该屠宰场名称已存在'
        });
      }
    }
    
    // 检查许可证号是否重复（排除当前屠宰场）
    if (licenseNumber && licenseNumber !== slaughterhouse.licenseNumber) {
      const existingLicense = await Slaughterhouse.findOne({
        where: {
          licenseNumber,
          id: { [Op.ne]: id }
        }
      });
      
      if (existingLicense) {
        return res.status(400).json({
          code: 400,
          message: '该许可证号已存在'
        });
      }
    }
    
    // 转换状态为英文存储
    const statusValue = status === '正常' ? 'active' : status === '暂停营业' ? 'inactive' : status;
    
    await slaughterhouse.update({
      name,
      address,
      contactPerson,
      contactPhone,
      licenseNumber,
      status: statusValue,
      updated_by: req.user?.id || null
    });
    
    res.json({
      code: 200,
      data: slaughterhouse,
      message: '更新成功'
    });
  } catch (error) {
    console.error('更新屠宰场失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
};

// 删除屠宰场
exports.deleteSlaughterhouse = async (req, res) => {
  try {
    const { id } = req.params;
    
    const slaughterhouse = await Slaughterhouse.findByPk(id);
    
    if (!slaughterhouse) {
      return res.status(404).json({
        code: 404,
        message: '屠宰场不存在'
      });
    }
    
    await slaughterhouse.destroy();
    
    res.json({
      code: 200,
      message: '删除成功'
    });
  } catch (error) {
    console.error('删除屠宰场失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
};

// 切换屠宰场状态
exports.toggleSlaughterhouseStatus = async (req, res) => {
  try {
    const { id } = req.params;
    
    const slaughterhouse = await Slaughterhouse.findByPk(id);
    
    if (!slaughterhouse) {
      return res.status(404).json({
        code: 404,
        message: '屠宰场不存在'
      });
    }
    
    const newStatus = slaughterhouse.status === 'active' ? 'inactive' : 'active';
    
    await slaughterhouse.update({
      status: newStatus,
      updated_by: req.user?.id || null
    });
    
    // 转换状态为中文显示
    const processedSlaughterhouse = {
      ...slaughterhouse.toJSON(),
      status: newStatus === 'active' ? '正常' : '暂停营业'
    };
    
    res.json({
      code: 200,
      data: processedSlaughterhouse,
      message: '状态切换成功'
    });
  } catch (error) {
    console.error('切换屠宰场状态失败:', error);
    res.status(500).json({
      code: 500,
      message: '服务器内部错误'
    });
  }
};