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

// 获取智能项圈列表
const getSmartCollars = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, collarId = '', status = '' } = req.query;
    
    const whereCondition = {};
    
    // 项圈编号搜索
    if (collarId) {
      whereCondition.collar_id = { [Op.like]: `%${collarId}%` };
    }
    
    // 状态筛选
    if (status) {
      whereCondition.status = status;
    }
    
    const offset = (page - 1) * pageSize;
    
    const { count, rows } = await SmartCollar.findAndCountAll({
      where: whereCondition,
      offset,
      limit: parseInt(pageSize),
      order: [['created_at', 'DESC']]
    });
    
    // 格式化数据以便前端使用
    const formattedData = rows.map(collar => ({
      id: collar.id,
      key: collar.id.toString(),
      collarId: collar.collar_id,
      name: collar.name,
      status: collar.status,
      battery: collar.battery,
      remark: collar.remark,
      createdAt: collar.created_at.toLocaleString('zh-CN'),
      updatedAt: collar.updated_at.toLocaleString('zh-CN')
    }));
    
    res.json({
      success: true,
      data: formattedData,
      total: count,
      page: parseInt(page),
      pageSize: parseInt(pageSize),
      message: '获取智能项圈列表成功'
    });
  } catch (error) {
    console.error('获取智能项圈列表失败:', error);
    res.status(500).json({
      success: false,
      message: '获取智能项圈列表失败',
      error: error.message
    });
  }
};

// 新增智能项圈
const createSmartCollar = async (req, res) => {
  try {
    const {
      collarId,
      name,
      status = 'inactive',
      battery = 100,
      remark = ''
    } = req.body;
    
    // 检查项圈编号是否已存在
    const existingCollar = await SmartCollar.findOne({ where: { collar_id: collarId } });
    if (existingCollar) {
      return res.status(400).json({
        success: false,
        message: '该智能项圈编号已存在'
      });
    }
    
    const collar = await SmartCollar.create({
      collar_id: collarId,
      name,
      status,
      battery,
      remark
    });
    
    res.status(201).json({
      success: true,
      data: {
        id: collar.id,
        collarId: collar.collar_id,
        name: collar.name,
        status: collar.status,
        battery: collar.battery,
        remark: collar.remark,
        createdAt: collar.created_at.toLocaleString('zh-CN'),
        updatedAt: collar.updated_at.toLocaleString('zh-CN')
      },
      message: '新增智能项圈成功'
    });
  } catch (error) {
    console.error('新增智能项圈失败:', error);
    res.status(500).json({
      success: false,
      message: '新增智能项圈失败',
      error: error.message
    });
  }
};

// 编辑智能项圈
const updateSmartCollar = async (req, res) => {
  try {
    const { id } = req.params;
    const {
      collarId,
      name,
      status,
      battery,
      remark
    } = req.body;
    
    // 查找要编辑的智能项圈
    const collar = await SmartCollar.findByPk(id);
    if (!collar) {
      return res.status(404).json({
        success: false,
        message: '未找到该智能项圈'
      });
    }
    
    // 如果修改了项圈编号，检查新编号是否已存在
    if (collarId && collarId !== collar.collar_id) {
      const existingCollar = await SmartCollar.findOne({ where: { collar_id: collarId } });
      if (existingCollar) {
        return res.status(400).json({
          success: false,
          message: '该智能项圈编号已存在'
        });
      }
    }
    
    // 更新智能项圈信息
    await collar.update({
      collar_id: collarId,
      name,
      status,
      battery,
      remark
    });
    
    res.json({
      success: true,
      data: {
        id: collar.id,
        collarId: collar.collar_id,
        name: collar.name,
        status: collar.status,
        battery: collar.battery,
        remark: collar.remark,
        createdAt: collar.created_at.toLocaleString('zh-CN'),
        updatedAt: collar.updated_at.toLocaleString('zh-CN')
      },
      message: '编辑智能项圈成功'
    });
  } catch (error) {
    console.error('编辑智能项圈失败:', error);
    res.status(500).json({
      success: false,
      message: '编辑智能项圈失败',
      error: error.message
    });
  }
};

// 删除智能项圈
const deleteSmartCollar = async (req, res) => {
  try {
    const { id } = req.params;
    
    // 查找要删除的智能项圈
    const collar = await SmartCollar.findByPk(id);
    if (!collar) {
      return res.status(404).json({
        success: false,
        message: '未找到该智能项圈'
      });
    }
    
    // 删除智能项圈
    await collar.destroy();
    
    res.json({
      success: true,
      message: '删除智能项圈成功'
    });
  } catch (error) {
    console.error('删除智能项圈失败:', error);
    res.status(500).json({
      success: false,
      message: '删除智能项圈失败',
      error: error.message
    });
  }
};

module.exports = {
  getSmartCollars,
  createSmartCollar,
  updateSmartCollar,
  deleteSmartCollar
};