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

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

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

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

module.exports = {
  getSmartHosts,
  createSmartHost,
  updateSmartHost,
  deleteSmartHost
};