package cn.iocoder.yudao.framework.http.example;

import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
import cn.iocoder.yudao.framework.http.core.Request;
import cn.iocoder.yudao.framework.http.core.Response;
import cn.iocoder.yudao.framework.http.core.client.HttpClient;
import cn.iocoder.yudao.framework.http.core.client.HttpClientFactory;
import lombok.SneakyThrows;

import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @author wuxian
 * @since 2024-10-30
 **/
public class YCloudWhatsappHttp {

    private HttpClient client = null;
    //请求地址
    private static final String WA_URL = "https://api.ycloud.com/v2/whatsapp/messages/sendDirectly";
    private static final String RECEIVE_URL = "https://api.ycloud.com/v2/whatsapp/messages/";

    public YCloudWhatsappHttp() {
        init();
    }

    private void init() {
        client = HttpClientFactory.get(Request.Util.OkHttp);
    }

    @SneakyThrows
    public Response postWhatsapp(Map<String, String> header, Map<String, Object> param) {
        Request req = Request.create(WA_URL, Request.Method.POST, param);
        req.setParamFormat(Request.ParamFormat.JSON);
        Response res = client.execute(req, Request.Option.create(0, 0, header));
        System.out.println("response code ---------------------------->" + res.getCode());
        System.out.println("response content is --------------------》" + res.getBody());
        return res;
    }

    @SneakyThrows
    public Response getReceiveStatus(Map<String, String> header, String id) {
        Request req = Request.create(RECEIVE_URL + id, Request.Method.GET, "");
        Response res = client.execute(req, Request.Option.create(0, 0, header));
        System.out.println("response code ---------------------------->" + res.getCode());
        System.out.println("response content is --------------------》" + res.getBody());
        return res;
    }


    /**
     * @param code         验证码
     * @param templateName 模板名称
     * @param lanCode      语言编号
     * @param to           接收手机号
     * @return 参数
     */
    public Map<String, Object> setParams(String code, String templateName, String lanCode, String to) {
        Map<String, Object> template = new HashMap<>();
        Map<String, String> language = new HashMap<>();
        Components components = new Components();
        Parameters parameters = new Parameters();
        Button button = new Button();
        button.setIndex("0");
        button.setType("button");
        button.setSub_type("url");


        //模板包含语言(language)、组件（components），组件包含参数（parameters）
        parameters.setType("text");
        parameters.setText(code);
        List<Object> list1 = new ArrayList<>();
        list1.add(parameters);

        //构建json中的组件
        components.setType("body");
        components.setParameters(list1);
        button.setParameters(list1);
        List<Object> list2 = new ArrayList<>();
        list2.add(components);
        list2.add(button);

        language.put("code", lanCode);
        language.put("policy", "deterministic");

        template.put("language", language);
        template.put("name", templateName);
        template.put("components", list2);

        //构建最终requestBody的json
        Map<String, Object> param = new HashMap<>();
        param.put("from", "8618022485824");
        param.put("to", to);
        param.put("type", "template");
        param.put("template", template);
        return param;
    }

    //构建http请求的头
    public Map<String, String> setHeader(String apiKey) {
        Map<String, String> header = new HashMap<>();
        header.put("Accept", "application/json");
        header.put("Content-Type", "application/json");
        header.put("X-API-Key", apiKey);
        return header;
    }

    public static void main(String[] args) {
        YCloudWhatsappHttp test = new YCloudWhatsappHttp();
        String apiKey = "9dbd912f56c101e53b23cb7b758ffda8";
//        String code = "8888";
//        String templateName = "ec_verification";
//        String lanCode = "en";
//        test.postWhatsapp(test.setHeader(apiKey), test.setParams(code, templateName, lanCode, "8618926674857"));
        Response response = test.getReceiveStatus(test.setHeader(apiKey), "67370e34334f011e030dfd7b");
        Map<String, Object> responseObj = JsonUtils.parseObject(response.getBody(), Map.class);
        String status = (String) responseObj.get("status");
        if (status != null && ("delivered".equals(status) || "read".equals(status))) {
            System.out.println(status);
            String deliverTime = (String) responseObj.get("deliverTime");
            // 定义 ISO 8601 格式的日期时间解析器
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSX");
            // 将字符串解析为 ZonedDateTime 对象
            ZonedDateTime utcDateTime = ZonedDateTime.parse(deliverTime, formatter);
            // 获取本地时区
            ZoneId localZoneId = ZoneId.systemDefault();
            // 将 UTC 时间转换为本地时间
            ZonedDateTime localDateTime = utcDateTime.withZoneSameInstant(localZoneId);
            // 将 ZonedDateTime 转换为 Date
            Date localDate = Date.from(localDateTime.toInstant());
            // 输出本地时间
            System.out.println("本地时间: " + localDate);
        } else {
            System.out.println("null");
        }
    }
}

@lombok.Setter
@lombok.Getter
class Parameters {
    private String type;
    private String text;

}

@lombok.Setter
@lombok.Getter
class Components {
    private String type;
    private List<Object> parameters = null;
}

@lombok.Setter
@lombok.Getter
class Button {
    private String type;
    private String sub_type;
    private String index;
    private List<Object> parameters = null;
}



