package com.starry.admin.modules.system.controller;

import com.starry.admin.modules.system.module.entity.Cache;
import com.starry.common.constant.CacheConstants;
import com.starry.common.result.R;
import com.starry.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import java.util.*;
import javax.annotation.Resource;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

/**
 * @author huoqiang 缓存监控
 * @since 2022/10/17
 */
@Api(tags = "缓存监控", description = "系统缓存监控相关接口")
@RestController
@RequestMapping("/monitor/cache")
public class CacheController {

    private final static List<Cache> CACHES = new ArrayList<>();
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    {
        CACHES.add(new Cache(CacheConstants.LOGIN_TOKEN_KEY, "用户信息"));
        CACHES.add(new Cache(CacheConstants.SYS_DICT_KEY, "数据字典"));
        CACHES.add(new Cache(CacheConstants.CAPTCHA_CODE_KEY, "验证码"));
    }

    @ApiOperation(value = "获取缓存信息", notes = "获取Redis服务器信息和命令统计")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = Map.class)})
    @PreAuthorize("@customSs.hasPermission('monitor:cache:list')")
    @GetMapping()
    public R getInfo() throws Exception {
        Properties info = (Properties) redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::info);
        Properties commandStats = (Properties) redisTemplate
                .execute((RedisCallback<Object>) connection -> connection.info("commandstats"));
        Object dbSize = redisTemplate.execute((RedisCallback<Object>) RedisServerCommands::dbSize);

        Map<String, Object> result = new HashMap<>(3);
        result.put("info", info);
        result.put("dbSize", dbSize);
        List<Map<String, String>> pieList = new ArrayList<>();
        commandStats.stringPropertyNames().forEach(key -> {
            Map<String, String> data = new HashMap<>(2);
            String property = commandStats.getProperty(key);
            data.put("name", StringUtils.removeStart(key, "cmdstat_"));
            data.put("value", StringUtils.substringBetween(property, "calls=", ",usec"));
            pieList.add(data);
        });
        result.put("commandStats", pieList);
        return R.ok(result);
    }

    @ApiOperation(value = "获取缓存名称", notes = "获取系统中所有缓存分类名称")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = Cache.class, responseContainer = "List")})
    @PreAuthorize("@customSs.hasPermission('monitor:cache:list')")
    @GetMapping("/getNames")
    public R cache() {
        return R.ok(CACHES);
    }

    @ApiOperation(value = "获取缓存键名", notes = "根据缓存名称获取对应的所有缓存键")
    @ApiImplicitParam(name = "cacheName", value = "缓存名称", required = true, dataType = "String", paramType = "path")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = String.class, responseContainer = "Set")})
    @PreAuthorize("@customSs.hasPermission('monitor:cache:list')")
    @GetMapping("/getKeys/{cacheName}")
    public R getCacheKeys(@PathVariable String cacheName) {
        Set<String> cacheKeys = redisTemplate.keys(cacheName + "*");
        return R.ok(cacheKeys);
    }

    @ApiOperation(value = "获取缓存值", notes = "根据缓存名称和键名获取缓存值")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功", response = Cache.class)})
    @PreAuthorize("@customSs.hasPermission('monitor:cache:list')")
    @GetMapping("/getValue/{cacheName}/{cacheKey}")
    public R getCacheValue(@PathVariable String cacheName, @PathVariable String cacheKey) {
        String cacheValue = redisTemplate.opsForValue().get(cacheKey);
        Cache cache = new Cache(cacheName, cacheKey, cacheValue);
        return R.ok(cache);
    }

    @ApiOperation(value = "清除缓存名称", notes = "清除指定缓存名称下的所有缓存")
    @ApiImplicitParam(name = "cacheName", value = "缓存名称", required = true, dataType = "String", paramType = "path")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("@customSs.hasPermission('monitor:cache:list')")
    @DeleteMapping("/clearCacheName/{cacheName}")
    public R clearCacheName(@PathVariable String cacheName) {
        Collection<String> cacheKeys = redisTemplate.keys(cacheName + "*");
        redisTemplate.delete(cacheKeys);
        return R.ok();
    }

    @ApiOperation(value = "清除缓存键", notes = "清除指定的缓存键")
    @ApiImplicitParam(name = "cacheKey", value = "缓存键", required = true, dataType = "String", paramType = "path")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("@customSs.hasPermission('monitor:cache:list')")
    @DeleteMapping("/clearCacheKey/{cacheKey}")
    public R clearCacheKey(@PathVariable String cacheKey) {
        redisTemplate.delete(cacheKey);
        return R.ok();
    }

    @ApiOperation(value = "清除所有缓存", notes = "清除系统中所有缓存数据")
    @ApiResponses({@ApiResponse(code = 200, message = "操作成功")})
    @PreAuthorize("@customSs.hasPermission('monitor:cache:list')")
    @DeleteMapping("/clearCacheAll")
    public R clearCacheAll() {
        Collection<String> cacheKeys = redisTemplate.keys("*");
        redisTemplate.delete(cacheKeys);
        return R.ok();
    }
}
