package com.zksy.data.schedule;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zksy.common.exception.CommonException;
import com.zksy.data.config.XinyonghuaihuaProperty;
import com.zksy.data.constant.RedisKeyConstant;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Map;

@EnableScheduling
@Component
public class RefreshTokenSchedule {
    @Autowired
    private XinyonghuaihuaProperty xinyonghuaihuaProperty;
    @Autowired
    private OkHttpClient okHttpClient;
    @Autowired
    private ObjectMapper objectMapper;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
//    @Scheduled(fixedRate = 600000)
    public void getToken() {
        HttpUrl url = new HttpUrl.Builder()
                .scheme("http")
                .host(xinyonghuaihuaProperty.getHost())
                .addPathSegment("interface/v1/auth/getToken")
                .addQueryParameter("refreshToken", xinyonghuaihuaProperty.getRefreshToken())
                .build();
        Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        try {
            redisTemplate.opsForValue().set(RedisKeyConstant.HUAIHUA_LOCK_KEY,"1");
            Response response = okHttpClient.newCall(request).execute();
            if (!response.isSuccessful()) {
                throw new CommonException("刷新token的接口请求失败",5000);
            }
            if (ObjectUtil.isEmpty(response.body())) {
                throw new CommonException("刷新token的接口出现问题",5000);
            }
            String s = response.body().string();
            Map map = objectMapper.readValue(s, Map.class);
            if((Integer) map.get("status") != 0){
                throw new CommonException("刷新token的接口返回异常",5000);
            }
            String token = (String) map.get("data");
            if(StrUtil.isEmpty(token)){
                throw new CommonException("刷新token的接口返回异常",5000);
            }
            redisTemplate.opsForValue().set(RedisKeyConstant.HUAIHUA_TOKEN_KEY,token);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            redisTemplate.delete(RedisKeyConstant.HUAIHUA_LOCK_KEY);
        }
    }
}
