package com.ruoyi.system.config;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.constant.AliKeyConfig;
import com.ruoyi.common.core.domain.UmResp;
import com.ruoyi.common.enums.DeviceTypeEnum;
import com.ruoyi.common.utils.uuid.UUID;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Header;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;


@Component
public class UmengConfig {

    private static final Logger log = LoggerFactory.getLogger(UmengConfig.class);

    public  UmResp send(String token,String deviceTypeUp){
        String umAppkey = null;
        if (deviceTypeUp.equals(DeviceTypeEnum.ANDROID.name())){
            umAppkey = AliKeyConfig.UMApp_Android_Key;
        }else if (deviceTypeUp.equals(DeviceTypeEnum.IOS.name())){
            umAppkey = AliKeyConfig.UMApp_IOS_Key;
        }
        //687b2df479267e0210b79b6f
        String appKey = AliKeyConfig.UMApp_AliKey;
        String appSecret = AliKeyConfig.UMApp_AliSecret;
//        if (deviceTypeUp.equals(DeviceTypeEnum.ANDROID.name())){
//
//        }
//        //687b2df479267e0210b79b6f
//        String umAppkey = "687b2e1679267e0210b79b70";
//        String appKey = "204918113";
//        String appSecret = "v4UrIhhLZlo0adpmevyCfvThGFbrRer0";
        // 下面的url要和阿里云云市场购买的商品对应
        String url = "https://verify5.market.alicloudapi.com/api/v1/mobile/info?appkey=" + umAppkey;
        HttpPost httpPost = new HttpPost(url);
        /**
         * body
         */
        JSONObject object = new JSONObject();
        object.put("token", token);
        StringEntity stringEntity = new StringEntity(object.toJSONString(), StandardCharsets.UTF_8);
        httpPost.setEntity(stringEntity);
        /**
         * header
         */
        httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("X-Ca-Version", "1");
        httpPost.setHeader("X-Ca-Signature-Headers", "X-Ca-Version,X-Ca-Stage,X-Ca-Key,X-Ca-Timestamp");
        httpPost.setHeader("X-Ca-Stage", "RELEASE");
        httpPost.setHeader("X-Ca-Key", appKey);
        httpPost.setHeader("X-Ca-Timestamp", String.valueOf(System.currentTimeMillis()));
        httpPost.setHeader("X-Ca-Nonce", UUID.randomUUID().toString());
        httpPost.setHeader("Content-MD5", Base64.encodeBase64String(DigestUtils.md5(object.toJSONString())));
        /**
         * sign
         */
        String stringToSign = getSignString(httpPost);
        Mac hmacSha256;
        try {
            hmacSha256 = Mac.getInstance("HmacSHA256");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
        byte[] keyBytes = appSecret.getBytes(StandardCharsets.UTF_8);
        try {
            hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, "HmacSHA256"));
        } catch (InvalidKeyException e) {
            throw new RuntimeException(e);
        }
        String sign = new String(Base64.encodeBase64(hmacSha256.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8))));
        httpPost.setHeader("X-Ca-Signature", sign);
        /**
         * execute
         */
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            log.info("发送数据：{}",httpPost);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            String respStr = EntityUtils.toString(response.getEntity());
            log.info("返回数据：{}",respStr);
            return JSONUtil.toBean(respStr, UmResp.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }




    public static void main(String[] args) {
//        System.out.println(DeviceTypeEnum.ANDROID.name());
//        UmResp sss1 = send("eyJvIjoiaU9TIiwiayI6ImJNSGJwMktVdjhVaE5zOW1wQWhwYl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JPNWpZMnhLTHZvb1NjMmRcLzhcL2JSTmxFM0txUUFLcDRGQUpxdWJ2bjhQRzdPcGN2bXhuSkF4bTJYNTFkQUZtaTdsSjZuZlc0MlJSNDRZWDBtMlhkczAwY3hZa2s5Q29zeVdWVUdGUkVDMjdjUUFURU9PMWp2TzdlMHEwOTRLZjdnaEx2UFJadlo2bFIxSUxmTTJxeWlQc0V5dmRiSUJyaG1yVEtJOWdqRW5Qc3U2dEZPc1RiZ0oxaVwvNGZBRFBKWDhOczF1Ym9taVl2KzZnVGsyNzlZTmQ3WU9OT21mMzlTOG05RktrNEN3Uk1QT1wvcVVSMGRJN25HbER4U1wvWEFFbWNHU0wxcDllczN0U0lsVUIrbHNcL3luWWZFNWNicDIwRE9NV3ZcL0xLa0I2cXA5RkVtaXV6eDY2MWYzZE9hZnk2WUJ2V2dsQnljU05TSkdDNkpYeTZnWHEwR1wvNE9XTkRPdjFhakIxMnhGRk9PK1dhbUVKcG9Takxic0FFV0V5eEtDb3pXaU9meG0ydEJ0bHdoM2hwXC9Vb3RyRCtIbkY2Z1NOOGtCblVtYnJRU3FzYUdsM2g3WDZSZUREbXdRSmMzSzY0QkxNcCJ9", "ios");
//        String sss;
//
//        sss = "{\"success\":true,\"data\":{\"mobile\":\"18518753918\",\"score\":null,\"activeScore\":null,\"aesEncryptKey\":null},\"code\":2001,\"message\":\"gain mobile&#39;s result success\",\"requestId\":\"0E87E249-42A0-42C0-94D3-7424D45E571E\"}\n";
//
//        UmResp ss = JSONUtil.toBean(sss, UmResp.class);
//        System.out.println(ss);

    }

    private static String getSignString(HttpPost httpPost) {
        Header[] headers = httpPost.getAllHeaders();
        Map<String, String> map = new HashMap<>();
        for (Header header : headers) {
            map.put(header.getName(), header.getValue());
        }
        return httpPost.getMethod() + "\n" +
                map.get("Accept") + "\n" +
                map.get("Content-MD5") + "\n" +
                map.get("Content-Type") + "\n\n" +
                "X-Ca-Key:" + map.get("X-Ca-Key") + "\n" +
                "X-Ca-Stage:" + map.get("X-Ca-Stage") + "\n" +
                "X-Ca-Timestamp:" + map.get("X-Ca-Timestamp") + "\n" +
                "X-Ca-Version:" + map.get("X-Ca-Version") + "\n" +
                httpPost.getURI().getPath() + "?" + httpPost.getURI().getQuery();
    }


}
