package com.zd.forward.serivce;

import com.alibaba.fastjson.JSON;
import com.zd.common.core.constant.SecurityConstants;
import com.zd.common.core.domain.R;
import com.zd.common.core.exception.ServiceException;
import com.zd.common.security.service.TokenService;
import com.zd.forward.config.AlgorithmYml;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
@EnableScheduling
@Slf4j
public class LoginService {


    @Autowired
    AlgorithmYml algorithmYml;
    @Autowired
    TokenService tokenService;

    private String token;

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    /**
     * 登录获取token
     * 优化建议， 不要每次请求都登录， 需要本地维护， 定时刷新token,只有访问过期时再重试登录请求
     */
    public void loginLab() {
        //不再重复登录
        RestTemplate restTemplate = new RestTemplate();
        //创建请求头
        String url = algorithmYml.getLoginUri() + "auth/one/login";
        Map<String, String> map = new HashMap<>(2);
        map.put("username", "admin");
        map.put("password", "zd123456..");
        ParameterizedTypeReference<R<Map<String, Object>>> reference = new ParameterizedTypeReference<R<Map<String, Object>>>(){};
        try {
            ResponseEntity<R<Map<String, Object>>> response = restTemplate.exchange(url, HttpMethod.POST, new HttpEntity<>(map), reference);
            R<Map<String, Object>> parse = response.getBody();
            if (parse != null) {
                Assert.isTrue(parse.getCode() == R.SUCCESS, "登录失败：" + parse.getMsg());
                //拿到token
                Map<String, Object> data = parse.getData();
                setToken("Bearer " + data.get("access_token"));
            }
        } catch (RestClientException e) {
            throw new ServiceException(e.getMessage());
        }
    }


    public String getCacheToken() {
        //换取缓存的token
        return getToken();
    }

    /**
     * 刷新key
     */
    public void refreshToken() {
        try {
            String tokenValue = token.replace(SecurityConstants.TOKEN_PREFIX, "");
            tokenService.refreshToken(tokenValue);
        } catch (Exception e) {
            loginLab();
        }
    }

    /**
     * 每隔30分钟刷新次token
     */
    @Scheduled(cron = "0 */30 * * * ?")
    //或直接指定时间间隔，例如：5秒
    //@Scheduled(fixedRate=5000)
    private void configureTasks() {
        log.info("第一次执行！！");
        if (token != null) {
            refreshToken();
        }
    }

}
