package org.example;

import org.example.config.CacheConstants;
import org.example.entity.Department;
import org.example.service.DepartmentService;
import org.example.service.HospitalService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * Redis缓存测试类
 */
@SpringBootTest
public class RedisTest {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private HospitalService hospitalService;

    /**
     * 测试Redis连接是否正常
     */
    @Test
    public void testRedisConnection() {
        System.out.println("========== 测试Redis连接 ==========");
        try {
            // 测试写入
            String testKey = "test:connection";
            String testValue = "Redis连接成功！";
            redisTemplate.opsForValue().set(testKey, testValue, 60, TimeUnit.SECONDS);
            
            // 测试读取
            Object result = redisTemplate.opsForValue().get(testKey);
            System.out.println("写入值: " + testValue);
            System.out.println("读取值: " + result);
            
            // 验证
            if (testValue.equals(result)) {
                System.out.println("✓ Redis连接测试成功！");
            } else {
                System.out.println("✗ Redis连接测试失败！");
            }
            
            // 清理测试数据
            redisTemplate.delete(testKey);
        } catch (Exception e) {
            System.out.println("✗ Redis连接失败: " + e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 测试Service层缓存是否生效
     */
    @Test
    public void testServiceCache() {
        System.out.println("\n========== 测试Service层缓存 ==========");
        
        // 第一次查询 - 应该从数据库查询
        System.out.println("第一次查询科室列表（从数据库）...");
        long start1 = System.currentTimeMillis();
        List<Department> list1 = departmentService.findList(null, null);
        long time1 = System.currentTimeMillis() - start1;
        System.out.println("第一次查询耗时: " + time1 + "ms, 记录数: " + (list1 != null ? list1.size() : 0));

        // 第二次查询 - 应该从缓存读取
        System.out.println("\n第二次查询科室列表（从缓存）...");
        long start2 = System.currentTimeMillis();
        List<Department> list2 = departmentService.findList(null, null);
        long time2 = System.currentTimeMillis() - start2;
        System.out.println("第二次查询耗时: " + time2 + "ms, 记录数: " + (list2 != null ? list2.size() : 0));

        // 对比
        System.out.println("\n========== 缓存效果对比 ==========");
        System.out.println("第一次（数据库）: " + time1 + "ms");
        System.out.println("第二次（缓存）: " + time2 + "ms");
        if (time2 < time1) {
            System.out.println("✓ 缓存生效！第二次查询更快");
        } else {
            System.out.println("提示：缓存可能已生效，但数据量小时差异不明显");
        }
    }

    /**
     * 测试缓存Key是否正确存储
     */
    @Test
    public void testCacheKeys() {
        System.out.println("\n========== 测试缓存Key ==========");
        
        // 触发缓存
        departmentService.findList(null, null);
        hospitalService.getHospital();
        
        // 查看所有缓存key
        System.out.println("查看Redis中的缓存Key:");
        try {
            // 查看科室缓存
            Set<String> deptKeys = redisTemplate.keys(CacheConstants.CACHE_DEPARTMENT + "*");
            System.out.println("科室缓存Key数量: " + (deptKeys != null ? deptKeys.size() : 0));
            if (deptKeys != null) {
                for (String key : deptKeys) {
                    System.out.println("  - " + key);
                }
            }
            
            // 查看医院缓存
            Set<String> hospitalKeys = redisTemplate.keys(CacheConstants.CACHE_HOSPITAL + "*");
            System.out.println("医院缓存Key数量: " + (hospitalKeys != null ? hospitalKeys.size() : 0));
            if (hospitalKeys != null) {
                for (String key : hospitalKeys) {
                    System.out.println("  - " + key);
                }
            }
            
            System.out.println("\n✓ 缓存Key测试完成！");
        } catch (Exception e) {
            System.out.println("✗ 获取缓存Key失败: " + e.getMessage());
        }
    }

    /**
     * 测试缓存清除
     */
    @Test
    public void testCacheEvict() {
        System.out.println("\n========== 测试缓存清除 ==========");
        
        // 先触发缓存
        System.out.println("1. 先查询一次，触发缓存...");
        departmentService.findList(null, null);
        
        // 检查缓存是否存在
        Set<String> keys1 = redisTemplate.keys(CacheConstants.CACHE_DEPARTMENT + "*");
        System.out.println("缓存Key数量: " + (keys1 != null ? keys1.size() : 0));
        
        // 注意：实际清除缓存需要调用save或delete方法
        // 这里只是演示如何手动清除
        System.out.println("\n2. 手动清除缓存...");
        if (keys1 != null && !keys1.isEmpty()) {
            redisTemplate.delete(keys1);
            System.out.println("已清除 " + keys1.size() + " 个缓存Key");
        }
        
        // 再次检查
        Set<String> keys2 = redisTemplate.keys(CacheConstants.CACHE_DEPARTMENT + "*");
        System.out.println("清除后缓存Key数量: " + (keys2 != null ? keys2.size() : 0));
        
        System.out.println("\n✓ 缓存清除测试完成！");
    }
}
