package com.sptg.third.biz.grid.controller;

import cn.hutool.core.date.DateUtil;
import com.sptg.common.core.beans.ResultBean;
import com.sptg.common.core.beans.ResultEnum;
import com.sptg.common.core.util.JsonUtils;
import com.sptg.third.api.contants.UrlContants;
import com.sptg.third.api.entity.grid.GridConfig;
import com.sptg.third.api.feigns.grid.GridAuthFeign;
import com.sptg.third.biz.grid.service.GridConfigServiceInterface;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author zwx
 * @create 2020/11/28 20:23
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping(value = "/third/grid/auth")
public class GridAuthController implements GridAuthFeign {

    private final GridConfigServiceInterface gridConfigServiceInterface;
    private final RestTemplate restTemplate;
    private final RedisTemplate redisTemplate;
    public static String GRID_TOKEN_CACHE = "sptg:third:grid:token";

    @Override
    @PostMapping(value = "/login")
    public ResultBean<String> gridAuth() {
        GridConfig gridConfig = this.gridConfigServiceInterface.getById(1L);
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Tenant-Id", gridConfig.getTenantId());
        httpHeaders.add("Authorization", gridConfig.getAuthorization());
        httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //  封装参数，千万不要替换为Map与HashMap，否则参数无法传递
        MultiValueMap<String, String> params = new LinkedMultiValueMap<>();
        params.add("grant_type", gridConfig.getGrantType());
        params.add("scope", gridConfig.getScope());
        params.add("username", gridConfig.getUserName());
        params.add("password", gridConfig.getPassword());
        params.add("tenantId", gridConfig.getTenantId());
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(params, httpHeaders);
        String url = gridConfig.getGridHost() + ":" + gridConfig.getGridPort() + UrlContants.Grid.AUTH;
        //  执行HTTP请求
        ResponseEntity<String> response = null;
        response = restTemplate.postForEntity(url, requestEntity, String.class);
        HttpStatus statusCode = response.getStatusCode();
        if(statusCode.is2xxSuccessful()){
            Map<String, Object> map = JsonUtils.jsonToPojo(response.getBody(), Map.class);
            String access_token = (String) map.get("access_token");
            Integer expires_in = (Integer)map.get("expires_in");
            gridConfig.setToken(access_token);
            boolean b = this.gridConfigServiceInterface.updateById(gridConfig);
            if(b){
                //  验证码存入缓存
                ValueOperations<String, String> operations = this.redisTemplate.opsForValue();
                //  设置缓存有效期 20分钟
                operations.set(GRID_TOKEN_CACHE, access_token, expires_in, TimeUnit.SECONDS);
            }
            return new ResultBean<>(ResultEnum.SUCCESS);
        }else{
            return new ResultBean<>(ResultEnum.FAILURE, "授权登录失败");
        }
    }
}
