package com.YuyeTech.HeartRate.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwk.Jwk;
import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.DefaultJwtBuilder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.security.Key;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.EncodedKeySpec;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @author:slambb
 * @date:2020/6/5
 */

@Slf4j
@Configuration
public class AppleUtil {
    private static String APPLE_KEYS_URL;
    //Revoke tokens
    //由于苹果注册后，删除用户需要revoke tokens
    public static String privateKeyStr;
    private static String APPLE_REVOKE_TOKENS_URL;
    private static String APPLE_AUTH_TOKENS_URL;
    private static String APPLE_TEAM_ID;
    private static String APPLE_KID;
    private static String APPLE_BUNDLE_IDENTIFIER;

    @Value("${apple.KEYS_URL}")
    public void set_APPLE_KEYS_URL(String APPLE_KEYS_URL) {
        AppleUtil.APPLE_KEYS_URL = APPLE_KEYS_URL;
    }
    @Value("${apple.REVOKE_TOKENS_URL}")
    public void set_REVOKE_TOKENS_URL(String REVOKE_TOKENS_URL) {
        AppleUtil.APPLE_REVOKE_TOKENS_URL = REVOKE_TOKENS_URL;
    }
    @Value("${apple.AUTH_TOKENS_URL}")
    public void set_APPLE_AUTH_TOKENS_URL(String AUTH_TOKENS_URL) {
        AppleUtil.APPLE_AUTH_TOKENS_URL = AUTH_TOKENS_URL;
    }
    @Value("${apple.TEAM_ID}")
    public void set_APPLE_TEAM_ID(String TEAM_ID) {
        AppleUtil.APPLE_TEAM_ID = TEAM_ID;
    }
    @Value("${apple.KID}")
    public void set_APPLE_KID(String KID) {
        AppleUtil.APPLE_KID = KID;
    }
    @Value("${apple.BUNDLE_IDENTIFIER}")
    public void set_APPLE_BUNDLE_IDENTIFIER(String BUNDLE_IDENTIFIER) {
        AppleUtil.APPLE_BUNDLE_IDENTIFIER = BUNDLE_IDENTIFIER;
    }
    /**
     * 获取苹果的公钥
     * @return
     * @throws Exception
     */
    private static JSONArray getAuthKeys() throws Exception {
//        String url = "https://appleid.apple.com/auth/keys";
        RestTemplate restTemplate = new RestTemplate();
        JSONObject json = restTemplate.getForObject(APPLE_KEYS_URL,JSONObject.class);
        JSONArray arr = json.getJSONArray("keys");
        return arr;
    }

    public static Boolean verify(String jwt) throws  Exception{
        JSONArray arr = getAuthKeys();
        if(arr == null){
            return false;
        }
        //先取苹果第一个key进行校验
        JSONObject authKey = arr.getJSONObject(0);
        if(verifyExc(jwt, authKey)){
            return true;
        }else{
            //再取第二个key校验
            authKey = arr.getJSONObject(1);
            return verifyExc(jwt, authKey);
        }

    }

    /**
     * 对前端传来的identityToken进行验证
     * @param jwt 对应前端传来的 identityToken
     * @param authKey 苹果的公钥 authKey
     * @return
     * @throws Exception
     */
    public static Boolean verifyExc(String jwt, JSONObject authKey) throws Exception {

        Jwk jwa = Jwk.fromValues(authKey);
        PublicKey publicKey = jwa.getPublicKey();

        String aud = "";
        String sub = "";
        if (jwt.split("\\.").length > 1) {
            String claim = new String(Base64.decodeBase64(jwt.split("\\.")[1]));
            aud = JSONObject.parseObject(claim).get("aud").toString();
            sub = JSONObject.parseObject(claim).get("sub").toString();
        }
        JwtParser jwtParser = Jwts.parser().setSigningKey(publicKey);
        jwtParser.requireIssuer("https://appleid.apple.com");
        jwtParser.requireAudience(aud);
        jwtParser.requireSubject(sub);

        try {
            Jws<Claims> claim = jwtParser.parseClaimsJws(jwt);
            if (claim != null && claim.getBody().containsKey("auth_time")) {
                System.out.println(claim);
                return true;
            }
            return false;
        } catch (ExpiredJwtException e) {
//            log.error("apple identityToken expired", e);
            return false;
        } catch (Exception e) {
//            log.error("apple identityToken illegal", e);
            return false;
        }

    }



    /**
     * 对前端传来的JWT字符串identityToken的第二部分进行解码
     * 主要获取其中的aud和sub，aud大概对应ios前端的包名，sub大概对应当前用户的授权的openID
     * @param identityToken
     * @return  {"aud":"com.xkj.****","sub":"000***.8da764d3f9e34d2183e8da08a1057***.0***","c_hash":"UsKAuEoI-****","email_verified":"true","auth_time":1574673481,"iss":"https://appleid.apple.com","exp":1574674081,"iat":1574673481,"email":"****@qq.com"}
     */
    public static JSONObject parserIdentityToken(String identityToken){
        String[] arr = identityToken.split("\\.");
        Base64 base64 = new Base64();
        String decode = new String (base64.decodeBase64(arr[1]));
        String substring = decode.substring(0, decode.indexOf("}")+1);
        JSONObject jsonObject = JSON.parseObject(substring);
        return  jsonObject;
    }


    /**
     * 获取p8文件中的内容
     *
     * @return
     */
    private static Key getPrivateKey() {
        try {
            ClassPathResource resource = new ClassPathResource("config/AuthKey_8G9994KW4L.p8");
            InputStream inputStream = resource.getInputStream();
            Reader reader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader br = new BufferedReader(reader);
            String string = null;
            StringBuffer sb = new StringBuffer();
            while ((string = br.readLine()) != null) {
                if (string.startsWith("---")) {
                    continue;
                }
                sb.append(string);
            }
            br.close();

            KeyFactory factory = KeyFactory.getInstance("EC");
            EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(org.apache.commons.codec.binary.Base64.decodeBase64(sb.toString().replaceAll("\\n", "")));
            return factory.generatePrivate(keySpec);
        } catch (FileNotFoundException e) {
            log.error("not find p8 file !=>{}", e.getMessage());
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 私钥加密后给苹果去验证，构造clientSecret，就是构造一个jwt字符串
     * [获取私钥]
     *
     * @param iss team_id
     * @param sub client_id
     * @param kid access_token
     * @return
     */
    public static String buildJwt(String iss, String sub, String kid) {
        Map<String, Object> header = new HashMap<>();
        header.put("alg", SignatureAlgorithm.ES256.getValue()); //SHA256withECDSA
        header.put("kid", kid);

        long iat = System.currentTimeMillis() / 1000; //以秒为单位
        Map<String, Object> claims = new HashMap<>();
        claims.put("iss", iss);// apple开发组id 问ios开发要
        claims.put("iat", iat);
        claims.put("exp", iat + 180 * 3600); //设置过期时间
        claims.put("aud", "https://appleid.apple.com"); //固定值
        claims.put("sub", sub);// Bundle Identifier
        return new DefaultJwtBuilder().setHeader(header).setClaims(claims).signWith(SignatureAlgorithm.ES256, getPrivateKey()).compact();
    }

    /**
     * 用户授权获取
     *
     * @param code
     * @return
     */
    public static String getAuthToken(String code) {
        if (code.isEmpty() ) {
            return null;
        }
//        JSONObject jsonObject = null;
        try {

            privateKeyStr = buildJwt(APPLE_TEAM_ID, APPLE_BUNDLE_IDENTIFIER, APPLE_KID);
            MultiValueMap<String, String> stringStringHashMap = new LinkedMultiValueMap<>();
            stringStringHashMap.add("client_id", APPLE_BUNDLE_IDENTIFIER);
            stringStringHashMap.add("client_secret", privateKeyStr);
            stringStringHashMap.add("code", code);
            stringStringHashMap.add("grant_type", "authorization_code");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity request = new HttpEntity<>(stringStringHashMap,headers);
            RestTemplate restTemplate = new RestTemplate();
            JSONObject jsonObject = restTemplate.postForObject(APPLE_AUTH_TOKENS_URL,request,JSONObject.class);
            System.out.println(jsonObject);
            return jsonObject.get("access_token").toString();
        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException(e);
        }

    }

    public static Boolean appleRevoke(String code) {
        try {
            String authToken = getAuthToken(code);
            MultiValueMap<String, String> requestMap = new LinkedMultiValueMap<>();
            requestMap.add("client_id", APPLE_BUNDLE_IDENTIFIER);
            requestMap.add("client_secret", privateKeyStr);
            requestMap.add("token", authToken);
            requestMap.add("token_type_hint", "access_token");
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            HttpEntity request = new HttpEntity<>(requestMap,headers);
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<String> responseEntity = restTemplate.postForEntity(APPLE_REVOKE_TOKENS_URL,request,String.class);
            int statusCode = responseEntity.getStatusCodeValue();
            if (statusCode != 200) {
                JSONObject jsonObject = JSON.parseObject(responseEntity.getBody());
                String error = jsonObject.get("error").toString();
                System.out.println("error --------- " + error);
                if (!error.isEmpty()) {
                    return false;
                }
            }
        } catch (Exception e) {
            log.error("revoke token error");
            return false;
        }
        return true;
    }


}
