package com.sikey.wa04.business.infrastructure;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.PropertyNamingStrategies;
import com.sikey.wa04.business.infrastructure.adapter.RequestParametersBuilder;
import com.sikey.wa04.business.infrastructure.adapter.push.AccessToken;
import com.sikey.wa04.business.infrastructure.adapter.push.HuaweiPushNotification;
import com.sikey.wa04.business.infrastructure.adapter.push.XiaomiPushNotification;
import com.sikey.wa04.business.infrastructure.adapter.push.template.NotificationMessageTemplate;
import com.sikey.wa04.business.infrastructure.configuration.PushConfig;
import com.sikey.wa04.common.utils.ObjectMapperUtil;
import okhttp3.*;
import org.junit.jupiter.api.Test;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

import java.io.IOException;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;

public class HuaweiPushTripartiteTests {
    private static final String CLIENT_ID = "114048095";

    /**
     * 使用接口https://push-api.cloud.huawei.com/v2/[projectid]/messages:send时，才能使用
     */
    private static final String PROJECT_ID = "461323198429873300";

    private static final String CLIENT_SECRET = "39cf856f66e555b21b7964f1f14b0570a9a7753b9e09b28ea7a957828a9265d3";

    private static final OkHttpClient httpClient = new OkHttpClient();

    private static final String ack_id = "28865";

    private static final Long  MsgId = 62214L;


    private static final String sendId = "7cd3c863-9a16-4a23-9eee-e750ba4a62f9";
    private static final String recvId = "7a5b93ef-bcf2-41f8-bf65-c83cea00f3b1";

    private static final int msg_type = 40;

    //设备请求小米获取到的RegId
    private static final String RegId = "IQAAAACy1KVqAADLgcsmLWcyQJuN5b30LBCmCP0IAA2_h_3HXUNIRbIANxWq_58Wx6PuY4YMfKYD4QbWaH6u96lE07juJ4F6Kh99myyE44_DRPhN0w";

    @Test
    public void authenticate() throws Exception {
//        AccessToken accessToken = getAccessToken();
//
//        String body = """
//                {
//                    "validate_only": false,
//                    "message": {
//                        "android": {
//                            "notification": {
//                                "title": "新消息",
//                                "body": "点击查看",
//                                "click_action": {
//                                    "type": 3
//                                }
//                            }
//                        },
//                        "token": ["IQAAAACy1KVqAACvthwbSZz7OXahWQjQTEwCT-x4krPyBz9dPiXwHh-tVf4ScvjsM4V7tnku7NUaQtlklZo_chjfkLNtWpBP6kQjl704jQk1iXHyqg"],
//                        "data": "{\\"from_push\\":\\"true\\",\\"sendId\\":\\"7cd3c863-9a16-4a23-9eee-e750ba4a62f9\\",\\"recvId\\":\\"7a5b93ef-bcf2-41f8-bf65-c83cea00f3b1\\",\\"msg_type\\":22,\\"ack_id\\":\\"28865\\",\\"msg_id\\":62214,\\"content\\":{\\"videoCallToken\\":\\"007eJxSYDC5tzyUeX3AhXWr5riJfz63a+LNGo5XU0LezKvSEHu++rK5AoOlUbKJsalFkmWapYWJoWWaZaKhQYqxiWmqqWWiuXmaoSuLeoYAHwPD+jObmRgZGBlYGBgZQHwmMMkMJlnApAODgYGFqUliWpqumbGxia6JmXmSrkWyQZKusWVisrF5WophUpJJfIh3vH+gm0eRd3FIunO8obmJubGFuYmZoZmRGSODASAAAP//EqIvKw==\\",\\"roomId\\":\\"TK_m0NddolJMM_7a5b93ef-bcf2-41f8-bf65-c83cea00f3b1_1749021506\\"},\\"sendTime\\":1755687735417}"
////                        {
////                             "from_push": true,
////                             "sendId": "7cd3c863-9a16-4a23-9eee-e750ba4a62f9",
////                             "recvId": "7a5b93ef-bcf2-41f8-bf65-c83cea00f3b1",
////                             "msg_type": 40,
////                             "ack_id": "28865",
////                             "msg_id": 62214,
////                             "content": {
////                                 "videoCallToken": "007eJxSYDC5tzyUeX3AhXWr5riJfz63a+LNGo5XU0LezKvSEHu++rK5AoOlUbKJsalFkmWapYWJoWWaZaKhQYqxiWmqqWWiuXmaoSuLeoYAHwPD+jObmRgZGBlYGBgZQHwmMMkMJlnApAODgYGFqUliWpqumbGxia6JmXmSrkWyQZKusWVisrF5WophUpJJfIh3vH+gm0eRd3FIunO8obmJubGFuYmZoZmRGSODASAAAP//EqIvKw==",
////                                 "roomId": "TK_m0NddolJMM_7a5b93ef-bcf2-41f8-bf65-c83cea00f3b1_1749021506"
////                             },
////                             "sendTime": 1755672887080
////                         }
//                    }
//                }
//                """;
//        RequestBody requestBody = RequestBody.create(body, MediaType.parse("application/json; charset=UTF-8"));
//        Request request = new Request.Builder().addHeader("Authorization", "Bearer " + accessToken.getValue())
//                .url("https://push-api.cloud.huawei.com/v2/" + PROJECT_ID + "/messages:send")
//                .post(requestBody)
//                .build();
//        Response response = httpClient.newCall(request).execute();
//        System.out.println("发送推送通知："+response.body().string());


        PushConfig pushConfig = new PushConfig();
        PushConfig.PushHuaweiOAuth2Config pConfig = new PushConfig.PushHuaweiOAuth2Config();
        pConfig.setClientId(CLIENT_ID);
        pConfig.setClientSecret(CLIENT_SECRET);
        pConfig.setProjectId(PROJECT_ID);
        pushConfig.setHuawei(pConfig);
        HuaweiPushNotification pushNotification = new HuaweiPushNotification();
        AccessToken huaweiAccessToken = pushNotification.authenticate(pushConfig);

        Map<String, Object> content = new HashMap<>();
        content.put("roomId", "TK_m0NddolJMM_7a5b93ef-bcf2-41f8-bf65-c83cea00f3b1_1749021506");
        content.put("videoCallToken", "007eJxSYDC5tzyUeX3AhXWr5riJfz63a+LNGo5XU0LezKvSEHu++rK5AoOlUbKJsalFkmWapYWJoWWaZaKhQYqxiWmqqWWiuXmaoSuLeoYAHwPD+jObmRgZGBlYGBgZQHwmMMkMJlnApAODgYGFqUliWpqumbGxia6JmXmSrkWyQZKusWVisrF5WophUpJJfIh3vH+gm0eRd3FIunO8obmJubGFuYmZoZmRGSODASAAAP//EqIvKw==");

        NotificationMessageTemplate messageTemplate = new NotificationMessageTemplate();
        Map<String, Object> params = new HashMap<>();
        params.put("ackId", ack_id);
        params.put("msgId", MsgId);
        params.put("msgType", msg_type);
        params.put("sendId", sendId);
        params.put("recvId", recvId);
        params.put("sendTime", Instant.now().toEpochMilli());
        params.put("content", content);
        params.put("from_push", "true");
        //System.out.println("json-params:"+JSONUtil.toJsonPrettyStr(params));
        messageTemplate.setMsgId(MsgId).setMsgType(msg_type).setRegId(RegId).setTitle("新消息77777777"+Instant.now()).setBody("您有新的消息，请查看77777777777777777").setParams(params);
        try {
            String result = String.valueOf(pushNotification.send(messageTemplate, huaweiAccessToken));
            System.out.println(result);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    public AccessToken getAccessToken() throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("grant_type", "client_credentials");
        params.put("client_id", CLIENT_ID);
        params.put("client_secret", CLIENT_SECRET);
        RequestParametersBuilder requestParametersBuilder = new RequestParametersBuilder(params);
        String queryEncode = requestParametersBuilder.queryEncode();
        System.out.println("bodyQuery:"+ queryEncode);
        RequestBody requestBody = RequestBody.create(queryEncode, MediaType.parse("application/x-www-form-urlencoded"));

        Request request = new Request.Builder()
                .url("https://oauth-login.cloud.huawei.com/oauth2/v3/token")
                .post(requestBody)
                .build();
        Response response = httpClient.newCall(request).execute();
        String responseBody = response.body().string();
        System.out.println("Response Code: " + response.code());
        System.out.println("Response Body: " + responseBody);
        ObjectMapper objectMapper = new Jackson2ObjectMapperBuilder().build();
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
        Map<String, String> resMap = objectMapper.readValue(responseBody, ObjectMapperUtil.getValueTypeRef());
        System.out.println("获取token："+resMap);
        return new AccessToken().setValue(resMap.get("access_token"));
    }
}
