package com.zanxiang.game.module.sdk.service.api;

import com.zanxiang.game.module.base.pojo.enums.PayApplicationTypeEnum;
import com.zanxiang.game.module.sdk.constant.RedisKeyConstant;
import com.zanxiang.game.module.sdk.enums.ExpireTimeEnum;
import com.zanxiang.game.module.sdk.pojo.dto.GameAppletDTO;
import com.zanxiang.game.module.sdk.service.IGameAppletService;
import com.zanxiang.game.module.sdk.util.RedisUtil;
import com.zanxiang.game.module.sdk.util.SignUtil;
import com.zanxiang.module.util.JsonUtil;
import com.zanxiang.module.util.URIUtil;
import com.zanxiang.module.util.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author : lingfeng
 * @time : 2023-01-03
 * @description : 微信通用api接口
 */
@Slf4j
@Service
public class WxApiService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private RedisUtil<String> redisUtil;

    @Autowired
    private IGameAppletService gameAppletService;

    /**
     * 根据应用类型获取openId
     *
     * @param code   : 授权code
     * @param appId  : 应用id
     * @param secret : 应用密钥
     * @param type   : 应用类型
     * @return {@link String}
     */
    public Map<String, String> getOpenIdByType(String code, String appId, String secret, Integer type) {
        if (Objects.equals(type, PayApplicationTypeEnum.WX_MINI_APP.getType())) {
            return this.getAppletOpenId(code, appId, secret);
        }
        if (Objects.equals(type, PayApplicationTypeEnum.WX_MP.getType())) {
            return this.getMpOpenId(code, appId, secret);
        }
        return Collections.emptyMap();
    }

    /**
     * 小程序/小游戏获取用户应用openId
     *
     * @param code   : 授权code
     * @param appId  : 应用id
     * @param secret : 应用密钥
     * @return {@link String}
     */
    private Map<String, String> getAppletOpenId(String code, String appId, String secret) {
        // 请求微信服务器，使用code获取openid
        Map<String, String> paramMap = new HashMap<>(4);
        paramMap.put("appid", appId);
        paramMap.put("secret", secret);
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        // 发送请求
        String url = URIUtil.fillUrlParams("https://api.weixin.qq.com/sns/jscode2session", paramMap, Boolean.FALSE);
        String sr = restTemplate.getForObject(url, String.class);
        // 解析相应内容（转换成json对象）
        Map<String, String> resultMap = JsonUtil.toMap(sr, Map.class, String.class);
        if (resultMap == null || Strings.isBlank(resultMap.get("openid"))) {
            throw new BaseException("获取用户小程序/小游戏openId失败");
        }
        return resultMap;
    }

    /**
     * 公众号获取用户应用openId
     *
     * @param code   : 授权code
     * @param appId  : 应用id
     * @param secret : 应用密钥
     * @return {@link String}
     */
    private Map<String, String> getMpOpenId(String code, String appId, String secret) {
        // 请求微信服务器，使用code获取openid
        Map<String, String> paramMap = new HashMap<>(4);
        paramMap.put("appid", appId);
        paramMap.put("secret", secret);
        paramMap.put("code", code);
        paramMap.put("grant_type", "authorization_code");
        // 发送请求
        String url = URIUtil.fillUrlParams("https://api.weixin.qq.com/sns/oauth2/access_token", paramMap, Boolean.FALSE);
        String sr = restTemplate.getForObject(url, String.class);
        // 解析相应内容（转换成json对象）
        Map<String, String> resultMap = JsonUtil.toMap(sr, Map.class, String.class);
        if (resultMap == null || Strings.isBlank(resultMap.get("openid"))) {
            throw new BaseException("获取用户公众号openId失败");
        }
        return resultMap;
    }

    /**
     * 获取访问令牌
     *
     * @param appId  应用程序id
     * @param secret 秘密
     * @return {@link String}
     */
    public String getAccessToken(String appId, String secret) {
        String key = RedisKeyConstant.APPLET_ACCESS_TOKEN + appId;
        String cache = redisUtil.getCache(key);
        if (Strings.isNotBlank(cache)) {
            return cache;
        }
        Map<String, String> paramMap = new HashMap<>(4);
        paramMap.put("appid", appId);
        paramMap.put("secret", secret);
        paramMap.put("grant_type", "client_credential");
        // 发送请求
        String url = URIUtil.fillUrlParams("https://api.weixin.qq.com/cgi-bin/token", paramMap, Boolean.FALSE);
        String sr = restTemplate.getForObject(url, String.class);
        // 解析相应内容（转换成json对象）
        Map<String, String> resultMap = JsonUtil.toMap(sr, Map.class, String.class);
        if (resultMap == null || Strings.isBlank(resultMap.get("access_token"))) {
            throw new BaseException("获取应用token失败");
        }
        redisUtil.setCache(key, resultMap.get("access_token"), ExpireTimeEnum.ONE_HOUR.getTime());
        return resultMap.get("access_token");
    }

    /**
     * 返回是否过期
     *
     * @param gameId :  应用id
     * @param openId :  用户openId
     * @return {@link String}
     */
    public boolean checkSessionKey(Long gameId, String openId, String sessionKey) {
        String signature;
        String accessToken;
        try {
            signature = SignUtil.HMACSHA256("", sessionKey);
            GameAppletDTO gameAppletDTO = gameAppletService.getByGameId(gameId);
            accessToken = this.getAccessToken(gameAppletDTO.getAppId(), gameAppletDTO.getAppSecret());
        } catch (Exception e) {
            return Boolean.TRUE;
        }
        Map<String, String> paramMap = new HashMap<>(4);
        paramMap.put("access_token", accessToken);
        paramMap.put("signature", signature);
        paramMap.put("openid", openId);
        paramMap.put("sig_method", "hmac_sha256");
        // 发送请求
        String url = URIUtil.fillUrlParams("https://api.weixin.qq.com/wxa/checksession", paramMap, Boolean.FALSE);
        String sr = restTemplate.getForObject(url, String.class);
        // 解析相应内容（转换成json对象）
        Map<String, String> resultMap = JsonUtil.toMap(sr, Map.class, String.class);
        if (resultMap == null || !Objects.equals("0", resultMap.get("errcode"))) {
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }
}
