package com.liangjian.dataplatform.member.controller;

import com.liangjian.dataplatform.member.service.IUserGrowthLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.time.Duration;
import java.util.*;

/**
 * @Author: 黄子奇
 * @Date: 2019/8/24 9:43
 */
@Api(value = "测试一下Swagger的API管理", tags="测试", description = "测试一下Swagger的API管理")
@RestController
@RequestMapping("/try")
public class TryController {

    @Autowired
    WebApplicationContext applicationContext;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @GetMapping("/get")
    @ApiOperation(value = "尝试Get的API", notes = "尝试Get的API")
    public String get() {
        try {
            Class clazz = Class.forName("ru.yandex.clickhouse.ClickHouseDriver");
            return clazz.getName();
        } catch (Exception ex) {
            return ex.getMessage();
        }
    }

    @GetMapping("/getAllUrl")
    public Set<String> getAllUrl(){
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        //获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        Set<String> urlList = new TreeSet<>();
        for (RequestMappingInfo info : map.keySet()){
            //获取url的Set集合，一个方法可能对应多个url
            Set<String> patterns = info.getPatternsCondition().getPatterns();
            for (String url : patterns){
                urlList.add(url);
            }
        }
        return urlList;
    }

    @GetMapping("/redis/get")
    public String redisGet(@RequestParam String key) {
        String value = redisTemplate.opsForValue().get(key);
        return Objects.requireNonNullElseGet(value, () -> "no such key: " + key);
    }

    @GetMapping("/redis/set")
    public String redisSet(@RequestParam String key, @RequestParam String value) {
        redisTemplate.opsForValue().set(key,value, Duration.ofSeconds(60));
        return "setted";
    }
}
