package com.fastbee.deviceData.api.renke.service;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

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

@Component
public class RenKeAuthorizationService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    private final static String AUTH_URL = "http://api.farm.0531yun.cn/api/v2.0/entrance/user/userLogin";
    private final static String LOGIN_NAME = "heilongjiang";
    private final static String LOGIN_PWD = "123456";


    public String getToken(){
        //判断token是否过期
//        String cacheToken = stringRedisTemplate.opsForValue().get("renke:user:token");
//        if (!Objects.isNull(cacheToken)){
//            System.err.println("缓存中获取token:"+cacheToken);
//            return cacheToken;
//        }
        //获取token
        //构建请求体
        Map<String,Object> reqBody =new HashMap<>();
        reqBody.put("loginName",LOGIN_NAME);
        reqBody.put("loginPwd",LOGIN_PWD);

        HttpResponse response = HttpRequest.post(AUTH_URL)
                .body(JSONUtil.toJsonStr(reqBody)).execute();
        String resultObjectStr = response.body();
        if(StringUtils.isBlank(response.toString())){
            throw new RuntimeException("获取token失败!");
        }
        JSONObject resultObject = JSONUtil.parseObj(resultObjectStr);
        JSONObject tokenObject = JSONUtil.parseObj(resultObject.get("data"));
        int currDate = Integer.parseInt(tokenObject.get("currDate").toString());
        int expDate = Integer.parseInt(tokenObject.get("expDate").toString());
        Integer periodValidity= expDate - currDate;
        //将token存入redis
        return tokenObject.get("token").toString();
//        stringRedisTemplate.opsForValue().set("renke:user:token", tokenObject.get("token").toString(),2, TimeUnit.HOURS);
//        System.err.println("请求获取到token:"+tokenObject.get("token").toString());
//        return stringRedisTemplate.opsForValue().get("renke:user:token");
    }
}
