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 com.xinelu.mobile.vo.appletpersoncenter.PostDischargeAppletPhoneVO;
import com.xinelu.mobile.vo.appletpersoncenter.PostDischargeAppletVO;
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.HashMap;
import java.util.Map;
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;
    }

    /**
     * 根据登录编码获取微信小程序用户信息
     *
     * @param appletId  小程序id
     * @param secret    小程序秘钥
     * @param code      登录凭证码
     * @param grantType 授权类型
     * @return 登录信息
     */
    public PostDischargeAppletVO getPostDischargeAppletLogin(String appletId, String secret, String code, String grantType) {
        //请求地址
        String appletLoginUrl = Constants.APPLET_LOGIN_URL
                + "?appid=" + appletId
                + "&secret=" + secret
                + "&js_code=" + code
                + "&grant_type=" + grantType;
        //发送请求
        String result = HttpUtils.sendGet(appletLoginUrl);
        if (StringUtils.isBlank(result)) {
            throw new ServiceException("获取院后微信小程序用户信息失败", 201);
        }
        return JSON.parseObject(result, PostDischargeAppletVO.class);
    }

    /**
     * 获取院后微信小程序的手机号码
     *
     * @param code        登录凭证
     * @param accessToken 小程序accessToken
     * @return 手机信息
     */
    public PostDischargeAppletPhoneVO getPostDischargeAppletPhone(String code, String accessToken) {
        //请求地址
        String phoneUrl = Constants.PHONE_NUMBER_URL + accessToken;
        //请求参数
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", code);
        String param = JSON.toJSONString(paramMap);
        //发送POST请求
        String result = HttpUtils.sendPostJson(phoneUrl, param);
        if (StringUtils.isBlank(result)) {
            throw new ServiceException("获取院后微信小程序手机号失败", 201);
        }
        return JSON.parseObject(result, PostDischargeAppletPhoneVO.class);
    }
}
