package com.inspur.thrid.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.inspur.common.core.redis.RedisCache;
import com.inspur.common.utils.http.HttpUtils;
import com.inspur.thrid.IPBXService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

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

/**
 * 云上协同API
 */
@Service
@Slf4j
public class PBXServiceImpl implements IPBXService {

    // 应用key
    @Value("${pbx.clientId:vyun+008n783ymlvoo7o4}")
    private String clientId;

    // 密钥
    @Value("${pbx.secret:vyun+008n783ymlvoo7o4}")
    private String secret;

    // 获取token的url
    @Value("${pbx.tokenUrl:http://192.168.5.150:8088/openapi/v1.0/get_token}")
    private String tokenUrl;

    // 获取token的url
    @Value("${pbx.refreshTokenUrl:http://192.168.5.150:8088/openapi/v1.0/refresh_token}")
    private String refreshTokenUrl;

    @Autowired
    private RedisCache redisCache;
    private String tokenKey = "pbx" + ":" + "token";
    private String refreshTokenKey = "pbx" + ":" + "refreshToken";
    private String SUCCESS = "0";
    private String TOKEN_FAIL = "0201";

    @Override
    public String getAccessToken() {
        log.debug("getAccessToken start");
        // 从redis获取token
        String token  = (String)redisCache.getCacheObject(tokenKey);
        if(!StringUtils.isEmpty(token)){
            return token;
        }
        Map<String, String> params = new HashMap<String, String>(6);
        // 应用key
        params.put("username", clientId);
        // 密钥
        params.put("password", secret);
        String url = tokenUrl;
        log.debug("getAccessToken,url：" + url + "param：" + params);

        HttpRequest postRequest = HttpUtil.createPost(url);
        // 添加头部信息
        postRequest.header("Content-Type", "application/json");
        postRequest.header("User-Agent", "OpenAPI");
        //postRequest.header("Authorization", "Bearer your_token_here");
        // 设置请求体
        String body = params.toString();
        // 发送请求
        String res = postRequest.body(body).execute().body();

        log.debug("getAccessToken rsp: " + res);
        JSONObject jsonObject = JSONObject.parseObject(res);
        if(SUCCESS.equals(jsonObject.getString("errcode"))){
            // 获取token
            String tokenStr = jsonObject.getString("access_token");
            // 获取过期时间
            Integer expire_time = jsonObject.getInteger("access_token_expire_time");

            // 获取刷新token
            String refreshTokenStr = jsonObject.getString("refresh_token");
            // 获取刷新过期时间
            Integer refreshExpireTime = jsonObject.getInteger("refresh_token_expire_time");

            // 将获取的token放入redis，失效时间-1分钟
            redisCache.setCacheObject(tokenKey, tokenStr, expire_time-60, TimeUnit.SECONDS);
            redisCache.setCacheObject(refreshTokenKey, refreshTokenStr);

            log.debug("getAccessToken end");
            return tokenStr;
        }
        log.error("getAccessToken failed");
        return null;
    }

    /**
     * 刷新访问 Token
     * @param refreshToken token信息
     * @return
     */
    @Override
    public String getRefreshToken(String refreshToken){
        log.debug("refreshToken start");
        Map<String, String> params = new HashMap<String, String>(6);
        // 应用key
        params.put("refreshToken", refreshToken);
        String url = refreshTokenUrl;
        log.debug("refreshToken,url：" + url + "param：" + params);

        HttpRequest postRequest = HttpUtil.createPost(url);
        // 添加头部信息
        postRequest.header("Content-Type", "application/json");
        // 设置请求体
        String body = params.toString();
        // 发送请求
        String res = postRequest.body(body).execute().body();

        log.debug("refreshToken rsp: " + res);
        JSONObject jsonObject = JSONObject.parseObject(res);
        if(SUCCESS.equals(jsonObject.getString("errcode"))){
            // 获取token
            String tokenStr = jsonObject.getString("access_token");
            // 获取过期时间
            Integer expire_time = jsonObject.getInteger("access_token_expire_time");
            // 获取刷新token
            String refreshTokenStr = jsonObject.getString("refresh_token");
            // 获取刷新过期时间
            Integer refreshExpireTime = jsonObject.getInteger("refresh_token_expire_time");

            // 将获取的token放入redis，失效时间-1分钟
            redisCache.setCacheObject(tokenKey, tokenStr, expire_time-60, TimeUnit.SECONDS);

            redisCache.setCacheObject(refreshTokenKey, refreshTokenStr);

            log.debug("refreshToken end");
            return tokenStr;
        }
        log.error("refreshToken failed");
        return null;
    }
}
