/**
 * 智能耳标客户端控制器
 * 处理iot_jbq_client表的CRUD操作
 */

const { sequelize } = require('../config/database-simple')

class IotJbqClientController {
  /**
   * 获取所有智能耳标设备
   */
  async getAllClients(req, res) {
    try {
      const { cid, page = 1, pageSize = 10 } = req.query
      
      let whereClause = ''
      let params = []
      
      if (cid) {
        whereClause = `WHERE cid = '${cid}'`
      }
      
      const offset = (page - 1) * pageSize
      
      // 获取总数
      const [countResult] = await sequelize.query(
        `SELECT COUNT(*) as total FROM iot_jbq_client ${whereClause}`
      )
      
      // 获取数据
      const [clients] = await sequelize.query(
        `SELECT * FROM iot_jbq_client ${whereClause} ORDER BY id DESC LIMIT ${parseInt(pageSize)} OFFSET ${offset}`
      )
      
      res.json({
        success: true,
        data: clients,
        pagination: {
          current: parseInt(page),
          pageSize: parseInt(pageSize),
          total: countResult[0].total
        },
        message: '获取智能耳标设备列表成功'
      })
    } catch (error) {
      console.error('获取智能耳标设备列表失败:', error)
      res.status(500).json({
        success: false,
        message: '获取智能耳标设备列表失败',
        error: error.message
      })
    }
  }

  /**
   * 根据CID获取智能耳标设备
   */
  async getClientByCid(req, res) {
    try {
      const { cid } = req.params
      const [clients] = await sequelize.query(`SELECT * FROM iot_jbq_client WHERE cid = '${cid}'`)
      
      if (clients.length === 0) {
        return res.status(404).json({
          success: false,
          message: '智能耳标设备不存在'
        })
      }

      res.json({
        success: true,
        data: clients[0],
        message: '获取智能耳标设备成功'
      })
    } catch (error) {
      console.error('获取智能耳标设备失败:', error)
      res.status(500).json({
        success: false,
        message: '获取智能耳标设备失败',
        error: error.message
      })
    }
  }

  /**
   * 根据ID获取智能耳标设备
   */
  async getClientById(req, res) {
    try {
      const { id } = req.params
      const [clients] = await sequelize.query(`SELECT * FROM iot_jbq_client WHERE id = ${id}`)
      
      if (clients.length === 0) {
        return res.status(404).json({
          success: false,
          message: '智能耳标设备不存在'
        })
      }

      res.json({
        success: true,
        data: clients[0],
        message: '获取智能耳标设备成功'
      })
    } catch (error) {
      console.error('获取智能耳标设备失败:', error)
      res.status(500).json({
        success: false,
        message: '获取智能耳标设备失败',
        error: error.message
      })
    }
  }

  /**
   * 更新智能耳标设备
   */
  async updateClient(req, res) {
    try {
      const { id } = req.params
      const updateData = req.body

      // 构建更新字段
      const updateFields = []
      
      Object.keys(updateData).forEach(key => {
        if (updateData[key] !== undefined) {
          const value = typeof updateData[key] === 'string' ? `'${updateData[key]}'` : updateData[key]
          updateFields.push(`${key} = ${value}`)
        }
      })
      
      if (updateFields.length === 0) {
        return res.status(400).json({
          success: false,
          message: '没有要更新的字段'
        })
      }
      
      const [result] = await sequelize.query(
        `UPDATE iot_jbq_client SET ${updateFields.join(', ')} WHERE id = ${id}`
      )

      if (result.affectedRows === 0) {
        return res.status(404).json({
          success: false,
          message: '智能耳标设备不存在'
        })
      }

      res.json({
        success: true,
        data: { id: parseInt(id), ...updateData },
        message: '更新智能耳标设备成功'
      })
    } catch (error) {
      console.error('更新智能耳标设备失败:', error)
      res.status(500).json({
        success: false,
        message: '更新智能耳标设备失败',
        error: error.message
      })
    }
  }

  /**
   * 删除智能耳标设备
   */
  async deleteClient(req, res) {
    try {
      const { id } = req.params

      const [result] = await sequelize.query('DELETE FROM iot_jbq_client WHERE id = ?', [id])

      if (result.affectedRows === 0) {
        return res.status(404).json({
          success: false,
          message: '智能耳标设备不存在'
        })
      }

      res.json({
        success: true,
        message: '删除智能耳标设备成功'
      })
    } catch (error) {
      console.error('删除智能耳标设备失败:', error)
      res.status(500).json({
        success: false,
        message: '删除智能耳标设备失败',
        error: error.message
      })
    }
  }
}

module.exports = new IotJbqClientController()
