package com.sonic.frog.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import io.jsonwebtoken.*;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.RSAPublicKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * 苹果登录工具类
 */
public class AppleThirdUtils {

    @Autowired
    static RestTemplate restTemplate;

    private static final Logger logger = LoggerFactory.getLogger(AppleThirdUtils.class);

    /**
     * client_id (应用id,从苹果注册应用获取)
     */
    public static final String APPLICATION_ID = "gg.sonic";

    /**
     * 密钥key(从txt文件中获取)
     */
    private static final String SECRET_KEY = "MIGTAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBHkwdwIBAQQgRbQpSurTdkoWEfJwaMYRXTdXh/Q9oO3UMsvAv8cUGOagCgYIKoZIzj0DAQehRANCAAQZ1o16rbIdDLhPiINxMwz4HyGh5VVRp+RIf4I8GHRBmhGbBiu4AomiOvANzu3rQt2i0z136q4OUucbqG7SCh43";

    /**
     * p8文件中获取的kid
     */
    private static final String FILE_KID = "WTP5D3C65M";

    /**
     * p8文件中获取的team_id
     */
    private static final String TEAM_ID = "S68QCFB8Q7";

    /**
     * 固定值（用于验证token接口）
     */
    private static final String GRANT_TYPE = "authorization_code";

    /**
     * 获取公钥地址
     */
    private static final String PUBLIC_KEY_URL = "https://appleid.apple.com/auth/keys";

    /**
     * 获取验证token地址
     */
    private static final String GET_ID_TOKEN = "https://appleid.apple.com/auth/token";

    /**
     * 苹果官网地址
     */
    private static final String APPLE_URL = "https://appleid.apple.com";

    /**
     * 苹果验证成功后返回的用户信息中的登录时间
     */
    private static final String AUTH_TIME = "auth_time";


    /**
     * 获取验证的code
     */
    private static String getValidateCode(String code) {
        restTemplate = new RestTemplate();
        //请求苹果验证接口
        ResponseEntity<String> response = restTemplate.postForEntity(GET_ID_TOKEN, AppleThirdUtils.getRequestParams(code), String.class);

        return response.getBody();
    }

    /**
     * 构建验证登录参数
     *
     * @author WangDeyu
     */
    private static HttpEntity<MultiValueMap<String, String>> getRequestParams(String code) {

        //构建请求参数
        HttpHeaders headers = new HttpHeaders();
        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        map.add("client_id", APPLICATION_ID);
        map.add("client_secret", getSecretKey());
        map.add("code", code);
        map.add("grant_type", GRANT_TYPE);

        return new HttpEntity<>(map, headers);
    }

    /**
     * 读取文件中的密钥key,解密
     */
    private static byte[] readKey() {
        return Base64.decodeBase64(SECRET_KEY);
    }

    /**
     * 获取秘钥
     */
    private static String getSecretKey() {
        try {
            Map<String, Object> header = new HashMap<>(16);
            // 参考后台配置kid
            header.put("kid", FILE_KID);
            header.put("typ","JWT");
            Map<String, Object> claims = new HashMap<>(16);
            // 参考后台配置 team id
            claims.put("iss", TEAM_ID);
            long now = System.currentTimeMillis() / 1000;
            claims.put("iat", now);
            // 最长半年，单位秒
            claims.put("exp", now + 86400 * 30);
            // 苹果官网网址
            claims.put("aud", APPLE_URL);
            // client_id (应用id)
            claims.put("sub", APPLICATION_ID);
            PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(readKey());
            KeyFactory keyFactory = KeyFactory.getInstance("EC");
            PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec);

            return Jwts.builder().setHeader(header).setClaims(claims).signWith( privateKey,SignatureAlgorithm.ES256).compact();
        } catch (Exception e) {
            logger.error("获取apple密钥失败:", e);
            throw new RuntimeException("获取apple密钥失败:", e);
        }
    }


    /**
     * 解密个人信息
     *
     * @param identityToken APP获取的identityToken
     * @return 解密参数：失败返回null
     */
    public static String verify(String identityToken) {
        try {
            if (identityToken.split("\\.").length <= 1) {
                return null;
            }
            String firstDate = new String(Base64.decodeBase64(identityToken.split("\\.")[0]), "UTF-8");
            String claim = new String(Base64.decodeBase64(identityToken.split("\\.")[1]));
            String kid = JSONObject.parseObject(firstDate).get("kid").toString();
            String aud = JSONObject.parseObject(claim).get("aud").toString();
            String sub = JSONObject.parseObject(claim).get("sub").toString();
            String response = verify(getPublicKey(kid), identityToken, aud, sub);

            return "SUCCESS".equals(response) ? claim : null;
        } catch (Exception e) {
            logger.error("解密TOKEN失败", e);
            throw new RuntimeException("解密TOKEN失败", e);
        }
    }

    /**
     * 验证token
     */
    private static String verify(PublicKey key, String jwt, String audience, String subject) throws Exception {
        String result = "FAIL";
        JwtParser jwtParser = Jwts.parser().setSigningKey(key);
        jwtParser.requireIssuer(APPLE_URL);
        jwtParser.requireAudience(audience);
        jwtParser.requireSubject(subject);
        try {
            Jws<Claims> claim = jwtParser.parseClaimsJws(jwt);
            if (claim != null && claim.getBody().containsKey(AUTH_TIME)) {
                result = "SUCCESS";
                return result;
            }
        } catch (ExpiredJwtException e) {
            logger.error("苹果token过期", e);
            throw new Exception("苹果token过期", e);
        } catch (SignatureException e) {
            logger.error("苹果token非法", e);
            throw new Exception("苹果token非法", e);
        }
        return result;
    }


    /**
     * 获取苹果公钥
     *
     * @param kid (公钥的id)
     * @return PublicKey
     */
    private static PublicKey getPublicKey(String kid) {
        try {
            restTemplate = new RestTemplate();
            //请求苹果验证接口
            String response = restTemplate.getForObject(PUBLIC_KEY_URL, String.class);
            if (StringUtils.isBlank(response)) {
                return null;
            }
            JSONObject data = JSONObject.parseObject(response);
            JSONArray jsonArray = data.getJSONArray("keys");
            if (jsonArray.isEmpty()) {
                return null;
            }
            //通过kid,n和e的值获取苹果公钥字符串
            for (Object object : jsonArray) {
                JSONObject json = ((JSONObject) object);
                //公钥有多个，只取第一个会报SignatureException异常，得根据token的kid取
                if (json.getString("kid").equals(kid)) {
                    String n = json.getString("n");
                    String e = json.getString("e");
                    BigInteger modulus = new BigInteger(1, Base64.decodeBase64(n));
                    BigInteger publicExponent = new BigInteger(1, Base64.decodeBase64(e));
                    RSAPublicKeySpec spec = new RSAPublicKeySpec(modulus, publicExponent);
                    KeyFactory kf = KeyFactory.getInstance("RSA");
                    return kf.generatePublic(spec);
                }
            }
        } catch (Exception e) {
            logger.error("getPublicKey异常！  {}", e.getMessage());
            e.printStackTrace();
        }
        return null;

    }

}

