package com.trade.service.thirdparty.xiaotu.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.trade.common.constant.CacheConstants;
import com.trade.common.redis.RedisCache;
import com.trade.common.utils.http.HttpClientUtils;
import com.trade.common.utils.http.HttpConfig;
import com.trade.common.utils.http.HttpHeader;
import com.trade.service.thirdparty.xiaotu.configuration.XiaotuConfiguration;
import com.trade.service.thirdparty.xiaotu.dto.CommonResponse;
import com.trade.service.thirdparty.xiaotu.dto.RequestTokenDto;
import com.trade.service.thirdparty.xiaotu.service.XiaotuRequestService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Service
public class XiaotuRequestServiceImpl implements XiaotuRequestService {

    private static final Logger logger = LoggerFactory.getLogger(XiaotuRequestServiceImpl.class);
    private static final String CONTENT_TYPE_JSON = "application/json";
    @Resource
    private RedisCache redisCache;
    @Resource
    private XiaotuConfiguration xiaotuConfiguration;

    private HttpHeader getCommonHeader() {
        return HttpHeader.custom().other("accessClientId", xiaotuConfiguration.getAccessClientId())
                .other("ftype", xiaotuConfiguration.getFtype())
                .other("gatewaAppKey", xiaotuConfiguration.getAccessClientId());
    }

    /**
     * 获取小图accessToken 和小图约定token的有效期为20分钟
     * 
     * @param xtUid 小图用户id
     * @param xtEid 小图企业id
     * @return 小图accessToken
     */
    private String getAccessToken(String xtUid, String xtEid) {
        String cacheKey = CacheConstants.XIAOTU_ACCESS_TOKEN + "_" + xtUid + "_" + xtEid;
        String accessToken = redisCache.getCacheObject(cacheKey);
        if (StrUtil.isEmpty(accessToken)) {
            String resp = HttpClientUtils
                    .post(HttpConfig.custom().headers(getCommonHeader().contentType(CONTENT_TYPE_JSON).build())
                            .json(JSON.toJSONString(new RequestTokenDto(xtEid, xtUid)))
                            .url(xiaotuConfiguration.getGetAccessTokenUrl()));
            CommonResponse commonResponse = JSON.parseObject(resp, CommonResponse.class);
            if (commonResponse != null && !commonResponse.isSuccess()) {
                logger.error("获取小图accessToken失败,resp={}", resp);
                throw new RuntimeException("获取小图accessToken失败");
            }
            JSONObject jsonObject = JSON.parseObject(resp).getJSONObject("body");
            accessToken = (String) jsonObject.get("ACCESS_TOKEN");
            if (StringUtils.isEmpty(accessToken)) {
                logger.error("获取小图accessToken为空,resp={}", resp);
                throw new RuntimeException("获取小图accessToken为空");
            }
            redisCache.setCacheObject(cacheKey, accessToken, 10, TimeUnit.MINUTES);
            return accessToken;
        }
        return accessToken;
    }
}
