-- 用户设备会话管理表
CREATE TABLE `user_device_session` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `username` varchar(50) NOT NULL COMMENT '用户名',
  `device_id` varchar(100) NOT NULL COMMENT '设备ID(基于主板序列号生成)',
  `device_name` varchar(100) DEFAULT NULL COMMENT '设备名称',
  `device_type` varchar(50) DEFAULT 'PC' COMMENT '设备类型',
  `os_name` varchar(50) DEFAULT NULL COMMENT '操作系统',
  `os_version` varchar(50) DEFAULT NULL COMMENT '系统版本',
  `ip_address` varchar(50) DEFAULT NULL COMMENT 'IP地址',
  `hostname` varchar(100) DEFAULT NULL COMMENT '主机名',
  `first_login_time` datetime DEFAULT NULL COMMENT '首次登录时间',
  `last_active_time` datetime DEFAULT NULL COMMENT '最后活跃时间',
  `online_status` char(1) DEFAULT '0' COMMENT '在线状态(0离线 1在线)',
  `login_count` bigint(20) DEFAULT 1 COMMENT '登录次数',
  `token_hash` varchar(64) DEFAULT NULL COMMENT 'JWT令牌哈希(用于识别)',
  `status` char(1) DEFAULT '0' COMMENT '设备状态(0正常 1已踢出 2已禁用)',
  `expire_time` datetime DEFAULT NULL COMMENT '过期时间',
  `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_username_device` (`username`, `device_id`),
  KEY `idx_username` (`username`),
  KEY `idx_device_id` (`device_id`),
  KEY `idx_token_hash` (`token_hash`),
  KEY `idx_online_status` (`online_status`),
  KEY `idx_last_active_time` (`last_active_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户设备会话管理表';

-- 插入测试数据
INSERT INTO `user_device_session` (`username`, `device_id`, `device_name`, `device_type`, `os_name`, `os_version`, `ip_address`, `hostname`, `first_login_time`, `last_active_time`, `online_status`, `login_count`, `status`) VALUES
('admin', 'DEVICE-ABC123DEF456', 'Windows 工作站', 'PC', 'Windows 11', '10.0.22000', '192.168.1.100', 'DESKTOP-ADMIN', NOW(), NOW(), '1', 1, '0'),
('admin', 'DEVICE-XYZ789GHI012', 'MacBook Pro', 'PC', 'Windows 10', '10.0.19045', '192.168.1.101', 'LAPTOP-ADMIN', DATE_SUB(NOW(), INTERVAL 2 DAY), DATE_SUB(NOW(), INTERVAL 1 DAY), '0', 5, '0'),
('testuser', 'DEVICE-QWE456RTY789', 'Ubuntu 桌面', 'PC', 'Windows 11', '10.0.22000', '192.168.1.102', 'UBUNTU-TEST', DATE_SUB(NOW(), INTERVAL 1 HOUR), DATE_SUB(NOW(), INTERVAL 30 MINUTE), '1', 3, '0');

-- 创建定时清理过期设备的事件(可选)
-- DELIMITER $$
-- CREATE EVENT IF NOT EXISTS `clean_expired_devices`
-- ON SCHEDULE EVERY 1 DAY
-- STARTS CURRENT_TIMESTAMP
-- DO
-- BEGIN
--     DELETE FROM user_device_session
--     WHERE (expire_time IS NOT NULL AND expire_time < NOW())
--        OR (online_status = '0' AND last_active_time < DATE_SUB(NOW(), INTERVAL 7 DAY));
-- END$$
-- DELIMITER ;

-- 设置事件调度器开启(如果使用事件)
-- SET GLOBAL event_scheduler = ON;