package com.xinelu.mobile.utils;

import com.alibaba.fastjson2.JSON;
import com.xinelu.common.config.WeChatAppletChatConfig;
import com.xinelu.common.constant.Constants;
import com.xinelu.common.entity.AccessToken;
import com.xinelu.common.exception.ServiceException;
import com.xinelu.common.utils.http.HttpUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

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

/**
 * @Description 院后微信小程序公共方法工具类
 * @Author 纪寒
 * @Date 2024-03-21 13:41:08
 * @Version 1.0
 */
@Component
public class WeChatAppletUtils {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;
    @Resource
    private WeChatAppletChatConfig weChatAppletChatConfig;
    /**
     * 返回成功状态码
     */
    private static final int SUCCESS_CODE = 0;

    /**
     * 获取微信小程序的accessToken值
     *
     * @return 小程序accessToken值
     */
    public String getWeChatAppletAccessToken() {
        String accessToken;
        String accessTokenRedisKey = Constants.WE_CHAT_APPLET_ACCESS_TOKEN + "accessToken";
        //从Redis中取出accessToken
        Object object = redisTemplate.opsForValue().get(accessTokenRedisKey);
        if (Objects.isNull(object)) {
            //没有，获取accessToken
            String accessTokenUrl = Constants.WE_CHAT_ACCESS_TOKEN_URL + "&appid=" + weChatAppletChatConfig.getAppletId() + "&secret=" + weChatAppletChatConfig.getSecret();
            //发送请求
            String result = HttpUtils.sendGet(accessTokenUrl);
            if (StringUtils.isBlank(result)) {
                throw new ServiceException("获取微信小程序accessToken信息失败", 201);
            }
            AccessToken weAppletAccessToken = JSON.parseObject(result, AccessToken.class);
            if (Objects.isNull(weAppletAccessToken)) {
                throw new ServiceException("获取微信小程序accessToken信息失败");
            }
            if (Objects.nonNull(weAppletAccessToken.getErrcode()) && weAppletAccessToken.getErrcode() != SUCCESS_CODE) {
                throw new ServiceException("获取微信小程序accessToken信息失败，失败信息为：" + weAppletAccessToken.getErrmsg(), 201);
            }
            if (StringUtils.isBlank(weAppletAccessToken.getAccessToken())) {
                throw new ServiceException("微信小程序accessToken信息为空");
            }
            accessToken = weAppletAccessToken.getAccessToken();
            //存入Redis中
            redisTemplate.opsForValue().set(accessTokenRedisKey, accessToken, 3600, TimeUnit.SECONDS);
        } else {
            accessToken = (String) object;
        }
        return accessToken;
    }
}
