package com.zcloud.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.client.WebClient;

import java.util.HashMap;
import java.util.Map;

/**
 * @author fangjiakai
 * @date 2023/03/08 14:51
 */
public class PushUtil {
    private static final String PUSH_URL = "https://fc-mp-356b2575-7ebe-471b-b689-8fd2b9b6c518.next.bspapp.com/unipush";
    private static final String PUSH_URL_GWJ = "https://fc-mp-356b2575-7ebe-471b-b689-8fd2b9b6c518.next.bspapp.com/unipush_gwj";
    private static final Map<String, String> PUSH_TYPE = new HashMap<String, String>() {{
        put("first", "__UNI__A117F2D");
        put("other", "__UNI__A0F75C1");
    }};
    private static final WebClient client = WebClient.create();

    public static void push(Object cid, String title, String content) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("push_clientid", cid);
        requestBody.put("title", title);
        requestBody.put("content", content);
        sendPushRequest(PUSH_URL, requestBody);
    }

    public static void push(Object cid, String title, String content, String type) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("push_clientid", cid);
        requestBody.put("title", title);
        requestBody.put("content", content);
        requestBody.put("APPID", PUSH_TYPE.get(type));
        sendPushRequest(PUSH_URL_GWJ, requestBody);
    }

    private static void sendPushRequest(String url, Map<String, Object> requestBody) {
        client.post()
                .uri(url)
                .contentType(MediaType.APPLICATION_JSON)
                .body(BodyInserters.fromValue(new JSONObject(requestBody)))
                .exchange()
                .flatMap(response -> {
                    System.out.println("Status code: " + response.statusCode().value());
                    return response.bodyToMono(String.class);
                })
                .doOnSuccess(body -> {
                    System.out.println("Response body: " + body);
                })
                .doOnError(throwable -> {
                    System.out.println("Error occurred: " + throwable.getMessage());
                })
                .block();
    }
}
