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

// 获取养殖户列表
const getFarmers = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, search = '', farmType = '', animalType = '', status = '' } = req.query;
    
    const whereCondition = {};
    
    // 搜索条件
    if (search) {
      whereCondition[Op.or] = [
        { nickname: { [Op.like]: `%${search}%` } },
        { real_name: { [Op.like]: `%${search}%` } },
        { farm_name: { [Op.like]: `%${search}%` } },
        { account: { [Op.like]: `%${search}%` } }
      ];
    }
    
    // 养殖场类型筛选
    if (farmType) {
      whereCondition.farm_type = farmType;
    }
    
    // 养殖种类筛选
    if (animalType) {
      whereCondition.animal_type = animalType;
    }
    
    // 状态筛选
    if (status) {
      whereCondition.status = status;
    }
    
    const offset = (page - 1) * pageSize;
    
    const { count, rows } = await Farmer.findAndCountAll({
      where: whereCondition,
      offset,
      limit: parseInt(pageSize),
      order: [['register_time', 'DESC']]
    });
    
    // 格式化数据以便前端使用
    const formattedData = rows.map(farmer => ({
      id: farmer.id,
      key: farmer.id.toString(),
      account: farmer.account,
      nickname: farmer.nickname,
      real_name: farmer.real_name,
      farm_name: farmer.farm_name,
      farm_type: farmer.farm_type,
      animal_type: farmer.animal_type,
      animal_count: farmer.animal_count,
      address: farmer.address,
      register_time: farmer.register_time.toLocaleString('zh-CN'),
      registrar: farmer.registrar,
      status: farmer.status === 'active' ? '正常' : farmer.status === 'inactive' ? '暂停' : '关闭',
      status_value: farmer.status
    }));
    
    res.json({
      data: formattedData,
      total: count,
      page: parseInt(page),
      pageSize: parseInt(pageSize)
    });
  } catch (error) {
    console.error('获取养殖户列表失败:', error);
    res.status(500).json({ message: error.message });
  }
};

// 新增养殖户
const createFarmer = async (req, res) => {
  try {
    const {
      account,
      nickname,
      real_name,
      farm_name,
      farm_type,
      animal_type,
      animal_count,
      address,
      status = 'active'
    } = req.body;
    
    // 检查账号是否已存在
    const existingFarmer = await Farmer.findOne({ where: { account } });
    if (existingFarmer) {
      return res.status(400).json({ message: '该账号已存在' });
    }
    
    const farmer = await Farmer.create({
      account,
      nickname,
      real_name,
      farm_name,
      farm_type,
      animal_type,
      animal_count,
      address,
      registrar: req.user?.username || 'system',
      status
    });
    
    res.status(201).json({
      success: true,
      message: '养殖户创建成功',
      data: farmer
    });
  } catch (error) {
    console.error('创建养殖户失败:', error);
    res.status(500).json({ message: error.message });
  }
};

// 编辑养殖户
const updateFarmer = async (req, res) => {
  try {
    const { id } = req.params;
    const {
      nickname,
      real_name,
      farm_name,
      farm_type,
      animal_type,
      animal_count,
      address,
      status
    } = req.body;
    
    const farmer = await Farmer.findByPk(id);
    if (!farmer) {
      return res.status(404).json({ message: '养殖户不存在' });
    }
    
    await farmer.update({
      nickname,
      real_name,
      farm_name,
      farm_type,
      animal_type,
      animal_count,
      address,
      status
    });
    
    res.json({
      success: true,
      message: '养殖户信息更新成功',
      data: farmer
    });
  } catch (error) {
    console.error('更新养殖户信息失败:', error);
    res.status(500).json({ message: error.message });
  }
};

// 删除养殖户
const deleteFarmer = async (req, res) => {
  try {
    const { id } = req.params;
    
    const farmer = await Farmer.findByPk(id);
    if (!farmer) {
      return res.status(404).json({ message: '养殖户不存在' });
    }
    
    await farmer.destroy();
    
    res.json({
      success: true,
      message: '养殖户删除成功'
    });
  } catch (error) {
    console.error('删除养殖户失败:', error);
    res.status(500).json({ message: error.message });
  }
};

// 重置养殖户密码（如果需要）
const resetFarmerPassword = async (req, res) => {
  try {
    const { id } = req.params;
    
    const farmer = await Farmer.findByPk(id);
    if (!farmer) {
      return res.status(404).json({ message: '养殖户不存在' });
    }
    
    // 在实际应用中，这里应该生成一个临时密码并发送给用户
    // 为了演示，我们只返回成功信息
    res.json({
      success: true,
      message: '密码重置成功，新密码已发送到用户手机'
    });
  } catch (error) {
    console.error('重置养殖户密码失败:', error);
    res.status(500).json({ message: error.message });
  }
};

// 获取养殖类型列表
const getFarmTypes = async (req, res) => {
  try {
    const farmTypes = [
      { value: '规模', label: '规模' },
      { value: '散养', label: '散养' },
      { value: '其他', label: '其他' }
    ];
    
    res.json(farmTypes);
  } catch (error) {
    console.error('获取养殖类型列表失败:', error);
    res.status(500).json({ message: error.message });
  }
};

// 获取养殖种类列表
const getAnimalTypes = async (req, res) => {
  try {
    const animalTypes = [
      { value: '牛', label: '牛' },
      { value: '羊', label: '羊' },
      { value: '猪', label: '猪' },
      { value: '鸡', label: '鸡' },
      { value: '其他', label: '其他' }
    ];
    
    res.json(animalTypes);
  } catch (error) {
    console.error('获取养殖种类列表失败:', error);
    res.status(500).json({ message: error.message });
  }
};

module.exports = {
  getFarmers,
  createFarmer,
  updateFarmer,
  deleteFarmer,
  resetFarmerPassword,
  getFarmTypes,
  getAnimalTypes
};