package com.jiayue.insu.inclientqn.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.jiayue.insu.inclientqn.constant.StatusConstant;
import com.jiayue.insu.inclientqn.entity.TokenInfo;
import com.jiayue.insu.inclientqn.model.ResponseVo;
import com.jiayue.insu.inclientqn.model.TokenVo;
import lombok.RequiredArgsConstructor;
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.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.List;


/**
 * @description: 获取token
 * @author: yuanhao
 * @createDate: 2021/8/19
 * @version: 1.0
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class InTokenService {
    @Autowired
    TokenInfoService tokenInfoService;
    @Value("${stationCode}")
    private String stationCode;

    /**
     * 获取清能一体化交互的token
     * @return
     */
    @Cacheable(value = "intoken" ,key = "'qntoken'")
    public TokenVo getToken() {
        List<TokenInfo> tokenInfoList = tokenInfoService.queryTokenInfo();
        TokenVo tokenVo = null;
        if (!tokenInfoList.isEmpty()) {
            TokenInfo tokenInfo = tokenInfoList.get(0);
            String username = tokenInfo.getUsername();
            String password = tokenInfo.getPassword();
            String passwordMD5 = DigestUtils.md5DigestAsHex(password.getBytes()).toUpperCase();
            String auth = username + ":" + passwordMD5;
            String tokenUrl = tokenInfo.getTokenurl();
            String response = null;
            String token = null;
            String requestTime = DateUtil.now();
            String expirationTime = DateUtil.offsetDay(DateUtil.parse(requestTime), 1).toString();
            try {
                HttpRequest httpRequest = HttpRequest.post(tokenUrl)
                        .header("Content-Type", "application/json")
                        .header("Authorization", auth);
                httpRequest.setGlobalTimeout(5000);
                response = httpRequest.execute().body();
                if (StringUtils.isNotEmpty(response)) {
                    boolean isJson = JSONUtil.isJsonObj(response);
                    if (isJson) {
                        JSON resultJson = JSONUtil.parse(response);
                        ResponseVo responseVo = JSONUtil.toBean(response, ResponseVo.class);
                        if (responseVo.getRetCode().equals(StatusConstant.REQUEST_SUCCESS)) {
                            token = responseVo.getData();
                            tokenVo = TokenVo.builder().requestTime(requestTime)
                                    .expirationTime(expirationTime)
                                    .tokenInfo(token)
                                    .build();
                            log.info("========== 一体化token请求成功: {} token=" + token + "  ==========", stationCode);
                        } else {
                            log.error("========== 一体化token请求异常: {} 接收retCode响应码非成功标识T200 标识为" + resultJson.getByPath("retCode") + " " + resultJson.getByPath("retMsg") + " ==========", stationCode);
                            log.info("========== 请求参数 账号密码:" + username + ":" + password + " MD5加密:" + auth + " ==========");
                        }
                    } else {
                        log.error("========== 一体化token请求异常: {} 接收响应字符串非json格式 ==========", stationCode);
                    }
                } else {
                    log.error("========== 一体化token请求异常: {} 接收响应字符串为空 ==========", stationCode);
                }
            } catch (Exception e) {
                log.error("========== 一体化token请求异常: {} 连接断开或请求超时 ==========", stationCode);
                e.printStackTrace();
            }
        }
        return tokenVo;
    }
}
