package com.yeejoin.equipmanage.utils;

import com.alibaba.fastjson.JSONObject;
import com.yeejoin.equipmanage.common.datasync.vo.AppTokenVo;
import com.yeejoin.equipmanage.common.utils.HttpContentTypeUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

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

/**
 * @ProjectName: EquipManageRoot
 * @Package: com.yeejoin.equipmanage.utils
 * @ClassName: DcsUtil
 * @Author: Jianqiang Gao
 * @Description: 数字换流站工具类
 * @Date: 2021/4/23 18:16
 * @Version: 1.0
 */
@Component
public class DcsUtil {

    private final Logger logger = LoggerFactory.getLogger(DcsUtil.class);

    @Value("${dcs.client-id}")
    private String clientId;

    @Value("${dcs.client.secret}")
    private String clientSecret;

    @Value("${dcs.grant-type}")
    private String grantType;

    @Value("${dcs.scope}")
    private String scope;

    @Value("${dcs.url.token}")
    private String gettokenUrl;

    @Value("${dcs.token-key}")
    private String tokenKey;

    @Value("${dcs.x.hw.id}")
    private String xHwId;

    @Value("${dcs.x.hw.appKey}")
    private String xHwAppKey;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public String getDcsToken() throws Exception {
        String accessToken = "";
//        accessToken = redisTemplate.opsForValue().get(tokenKey);
        if (!StringUtils.isNotBlank(accessToken)) {
            Map<String, String> headerMap = new HashMap<>();
            headerMap.put("X-HW-ID", xHwId);
            headerMap.put("X-HW-APPKEY", xHwAppKey);
            Map<String, String> map = new HashMap<>();
            map.put("grant_type", grantType);
            map.put("scope", scope);
            map.put("client_id", clientId);
            map.put("client_secret", clientSecret);
            String content = HttpContentTypeUtil.doPostForm(gettokenUrl, map);
            if (StringUtils.isNotBlank(content)) {
                AppTokenVo appTokenVo = JSONObject.parseObject(content, AppTokenVo.class);
//                accessToken = String.join(" ", appTokenVo.getToken_type(), appTokenVo.getAccess_token());
                accessToken = "bearer " + appTokenVo.getAccess_token();
                Integer expiresIn = appTokenVo.getExpires_in();
                redisTemplate.opsForValue().set(tokenKey, accessToken, expiresIn);
            }
        }
        return accessToken;
    }
}