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

// 获取智能耳标列表
const getSmartEarmarks = async (req, res) => {
  try {
    const { page = 1, pageSize = 10, earmarkId = '', status = '' } = req.query;
    
    const whereCondition = {};
    
    // 耳标编号搜索
    if (earmarkId) {
      whereCondition.earmark_id = { [Op.like]: `%${earmarkId}%` };
    }
    
    // 状态筛选
    if (status) {
      whereCondition.status = status;
    }
    
    const offset = (page - 1) * pageSize;
    
    const { count, rows } = await SmartEarmark.findAndCountAll({
      where: whereCondition,
      offset,
      limit: parseInt(pageSize),
      order: [['created_at', 'DESC']]
    });
    
    // 格式化数据以便前端使用
    const formattedData = rows.map(earmark => ({
      id: earmark.id,
      key: earmark.id.toString(),
      earmarkId: earmark.earmark_id,
      name: earmark.name,
      status: earmark.status,
      battery: earmark.battery,
      remark: earmark.remark,
      createdAt: earmark.created_at.toLocaleString('zh-CN'),
      updatedAt: earmark.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 createSmartEarmark = async (req, res) => {
  try {
    const {
      earmarkId,
      name,
      status = 'inactive',
      battery = 100,
      remark = ''
    } = req.body;
    
    // 检查耳标编号是否已存在
    const existingEarmark = await SmartEarmark.findOne({ where: { earmark_id: earmarkId } });
    if (existingEarmark) {
      return res.status(400).json({
        success: false,
        message: '该智能耳标编号已存在'
      });
    }
    
    const earmark = await SmartEarmark.create({
      earmark_id: earmarkId,
      name,
      status,
      battery,
      remark
    });
    
    res.status(201).json({
      success: true,
      data: {
        id: earmark.id,
        earmarkId: earmark.earmark_id,
        name: earmark.name,
        status: earmark.status,
        battery: earmark.battery,
        remark: earmark.remark,
        createdAt: earmark.created_at.toLocaleString('zh-CN'),
        updatedAt: earmark.updated_at.toLocaleString('zh-CN')
      },
      message: '新增智能耳标成功'
    });
  } catch (error) {
    console.error('新增智能耳标失败:', error);
    res.status(500).json({
      success: false,
      message: '新增智能耳标失败',
      error: error.message
    });
  }
};

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

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

module.exports = {
  getSmartEarmarks,
  createSmartEarmark,
  updateSmartEarmark,
  deleteSmartEarmark
};