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

class FormLogController {
  // 添加表单日志
  static async addFormLog(req, res) {
    try {
      const {
        module,
        action,
        userId,
        username,
        sessionId,
        userAgent,
        screenResolution,
        currentUrl,
        formData,
        additionalData,
        status = 'success',
        errorMessage
      } = req.body

      // 获取客户端IP地址
      const ipAddress = req.ip || req.connection.remoteAddress || req.socket.remoteAddress

      const logData = {
        module,
        action,
        userId: userId || null,
        username: username || null,
        sessionId: sessionId || null,
        userAgent: userAgent || null,
        screenResolution: screenResolution || null,
        currentUrl: currentUrl || null,
        formData: formData || null,
        additionalData: additionalData || null,
        ipAddress,
        timestamp: new Date(),
        status,
        errorMessage: errorMessage || null
      }

      console.group('📝 [后端] 接收表单日志')
      console.log('🕒 时间:', new Date().toLocaleString())
      console.log('📋 模块:', module)
      console.log('🔧 操作:', action)
      console.log('👤 用户:', username || 'unknown')
      console.log('📊 数据:', logData)
      console.groupEnd()

      const formLog = await FormLog.create(logData)

      res.json({
        success: true,
        data: formLog,
        message: '日志记录成功'
      })
    } catch (error) {
      console.error('❌ [后端] 记录表单日志失败:', error)
      res.status(500).json({
        success: false,
        message: '记录日志失败',
        error: error.message
      })
    }
  }

  // 获取表单日志列表
  static async getFormLogs(req, res) {
    try {
      const {
        page = 1,
        pageSize = 10,
        module,
        action,
        userId,
        status,
        startDate,
        endDate,
        keyword
      } = req.query

      const where = {}

      // 构建查询条件
      if (module) {
        where.module = module
      }
      if (action) {
        where.action = action
      }
      if (userId) {
        where.userId = userId
      }
      if (status) {
        where.status = status
      }
      if (startDate && endDate) {
        where.timestamp = {
          [Op.between]: [new Date(startDate), new Date(endDate)]
        }
      }
      if (keyword) {
        where[Op.or] = [
          { username: { [Op.like]: `%${keyword}%` } },
          { action: { [Op.like]: `%${keyword}%` } },
          { module: { [Op.like]: `%${keyword}%` } }
        ]
      }

      const offset = (page - 1) * pageSize

      const { count, rows } = await FormLog.findAndCountAll({
        where,
        order: [['timestamp', 'DESC']],
        limit: parseInt(pageSize),
        offset: parseInt(offset)
      })

      console.group('📋 [后端] 查询表单日志')
      console.log('🕒 时间:', new Date().toLocaleString())
      console.log('📊 查询条件:', where)
      console.log('📈 结果数量:', count)
      console.groupEnd()

      res.json({
        success: true,
        data: {
          list: rows,
          total: count,
          page: parseInt(page),
          pageSize: parseInt(pageSize),
          totalPages: Math.ceil(count / pageSize)
        },
        message: '查询成功'
      })
    } catch (error) {
      console.error('❌ [后端] 查询表单日志失败:', error)
      res.status(500).json({
        success: false,
        message: '查询失败',
        error: error.message
      })
    }
  }

  // 获取日志详情
  static async getFormLogDetail(req, res) {
    try {
      const { id } = req.params

      const formLog = await FormLog.findByPk(id)

      if (!formLog) {
        return res.status(404).json({
          success: false,
          message: '日志不存在'
        })
      }

      console.group('📋 [后端] 查询日志详情')
      console.log('🕒 时间:', new Date().toLocaleString())
      console.log('📋 日志ID:', id)
      console.log('📊 日志数据:', formLog.toJSON())
      console.groupEnd()

      res.json({
        success: true,
        data: formLog,
        message: '查询成功'
      })
    } catch (error) {
      console.error('❌ [后端] 查询日志详情失败:', error)
      res.status(500).json({
        success: false,
        message: '查询失败',
        error: error.message
      })
    }
  }

  // 删除日志
  static async deleteFormLog(req, res) {
    try {
      const { id } = req.params

      const formLog = await FormLog.findByPk(id)
      if (!formLog) {
        return res.status(404).json({
          success: false,
          message: '日志不存在'
        })
      }

      await formLog.destroy()

      console.group('🗑️ [后端] 删除日志')
      console.log('🕒 时间:', new Date().toLocaleString())
      console.log('📋 日志ID:', id)
      console.groupEnd()

      res.json({
        success: true,
        message: '删除成功'
      })
    } catch (error) {
      console.error('❌ [后端] 删除日志失败:', error)
      res.status(500).json({
        success: false,
        message: '删除失败',
        error: error.message
      })
    }
  }

  // 批量删除日志
  static async batchDeleteFormLogs(req, res) {
    try {
      const { ids } = req.body

      if (!ids || !Array.isArray(ids) || ids.length === 0) {
        return res.status(400).json({
          success: false,
          message: '请提供要删除的日志ID列表'
        })
      }

      const deletedCount = await FormLog.destroy({
        where: {
          id: {
            [Op.in]: ids
          }
        }
      })

      console.group('🗑️ [后端] 批量删除日志')
      console.log('🕒 时间:', new Date().toLocaleString())
      console.log('📋 删除ID:', ids)
      console.log('📊 删除数量:', deletedCount)
      console.groupEnd()

      res.json({
        success: true,
        data: {
          deletedCount
        },
        message: `成功删除 ${deletedCount} 条日志`
      })
    } catch (error) {
      console.error('❌ [后端] 批量删除日志失败:', error)
      res.status(500).json({
        success: false,
        message: '批量删除失败',
        error: error.message
      })
    }
  }

  // 获取日志统计信息
  static async getFormLogStats(req, res) {
    try {
      const { startDate, endDate } = req.query

      const where = {}
      if (startDate && endDate) {
        where.timestamp = {
          [Op.between]: [new Date(startDate), new Date(endDate)]
        }
      }

      // 总日志数
      const totalLogs = await FormLog.count({ where })

      // 按模块统计
      const moduleStats = await FormLog.findAll({
        attributes: [
          'module',
          [FormLog.sequelize.fn('COUNT', FormLog.sequelize.col('id')), 'count']
        ],
        where,
        group: ['module'],
        order: [[FormLog.sequelize.fn('COUNT', FormLog.sequelize.col('id')), 'DESC']]
      })

      // 按操作类型统计
      const actionStats = await FormLog.findAll({
        attributes: [
          'action',
          [FormLog.sequelize.fn('COUNT', FormLog.sequelize.col('id')), 'count']
        ],
        where,
        group: ['action'],
        order: [[FormLog.sequelize.fn('COUNT', FormLog.sequelize.col('id')), 'DESC']]
      })

      // 按状态统计
      const statusStats = await FormLog.findAll({
        attributes: [
          'status',
          [FormLog.sequelize.fn('COUNT', FormLog.sequelize.col('id')), 'count']
        ],
        where,
        group: ['status'],
        order: [[FormLog.sequelize.fn('COUNT', FormLog.sequelize.col('id')), 'DESC']]
      })

      // 按用户统计
      const userStats = await FormLog.findAll({
        attributes: [
          'username',
          [FormLog.sequelize.fn('COUNT', FormLog.sequelize.col('id')), 'count']
        ],
        where,
        group: ['username'],
        order: [[FormLog.sequelize.fn('COUNT', FormLog.sequelize.col('id')), 'DESC']],
        limit: 10
      })

      console.group('📊 [后端] 日志统计查询')
      console.log('🕒 时间:', new Date().toLocaleString())
      console.log('📊 总日志数:', totalLogs)
      console.log('📋 模块统计:', moduleStats.length)
      console.log('🔧 操作统计:', actionStats.length)
      console.groupEnd()

      res.json({
        success: true,
        data: {
          totalLogs,
          moduleStats,
          actionStats,
          statusStats,
          userStats
        },
        message: '统计查询成功'
      })
    } catch (error) {
      console.error('❌ [后端] 查询日志统计失败:', error)
      res.status(500).json({
        success: false,
        message: '统计查询失败',
        error: error.message
      })
    }
  }
}

module.exports = FormLogController
