package top.baogutang.strategy.alerts;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import okhttp3.*;
import top.baogutang.strategy.models.PositionPlan;
import top.baogutang.strategy.models.Signal;
import top.baogutang.strategy.utils.SignUtil;

import java.util.List;

public class DingTalkRobotChannel implements AlertChannel {

    public static class RobotConfig {
        public String name;
        public String webhook;
        public boolean signEnable;
        public String secret;
        public List<String> atMobiles;
        public boolean atAll;
    }

    private final OkHttpClient http;
    private final ObjectMapper mapper;
    private final List<RobotConfig> robots;

    public DingTalkRobotChannel(OkHttpClient http, ObjectMapper mapper, List<RobotConfig> robots) {
        this.http = http;
        this.mapper = mapper;
        this.robots = robots;
    }

    public void send(Signal s, PositionPlan plan) {
        StringBuilder sb = new StringBuilder();
        sb.append("【交易信号】\n");
        sb.append("品种: ").append(s.getSymbol()).append("\n");
        sb.append("策略: ").append(s.getStrategy()).append("\n");
        sb.append("方向: ").append(s.getDirection()).append(" 等级:").append(s.getGrade()).append("\n");
        sb.append("参考入场: ").append(String.format("%.10f", s.getEntryRef())).append("\n");
        sb.append("止损: ").append(String.format("%.10f", s.getStopRef())).append("\n");
        sb.append("目标: ").append(java.util.Arrays.toString(s.getTargets())).append("\n");
        sb.append("风险金额: ").append(String.format("%.2f", plan.getRiskAmount())).append("\n");
        sb.append("计划数量: ").append(String.format("%.4f", plan.getQuantity())).append(" 杠杆:")
                .append(String.format("%.2f", plan.getLeverage())).append("\n");
        sb.append("备注: ").append(s.getComment()).append("\n");
        sb.append("时间: ").append(s.getTimestamp()).append("\n");

        String text = sb.toString();

        for (final RobotConfig rc : robots) {
            try {
                long ts = System.currentTimeMillis();
                String finalWebhook = rc.webhook;
                if (rc.signEnable) {
                    String sign = SignUtil.sign(ts, rc.secret);
                    finalWebhook = finalWebhook + "&timestamp=" + ts + "&sign=" + sign;
                }
                ObjectNode root = mapper.createObjectNode();
                root.put("msgtype", "text");
                ObjectNode textNode = mapper.createObjectNode();
                textNode.put("content", text);
                root.set("text", textNode);
                ObjectNode atNode = mapper.createObjectNode();
                if (rc.atMobiles != null && !rc.atMobiles.isEmpty()) {
                    atNode.set("atMobiles", mapper.valueToTree(rc.atMobiles));
                } else {
                    atNode.putArray("atMobiles");
                }
                atNode.put("isAtAll", rc.atAll);
                root.set("at", atNode);

                RequestBody body = RequestBody.create(mapper.writeValueAsBytes(root),
                        MediaType.parse("application/json"));
                Request req = new Request.Builder().url(finalWebhook).post(body).build();
                http.newCall(req).enqueue(new Callback() {
                    public void onFailure(Call call, java.io.IOException e) {
                        e.printStackTrace();
                    }

                    public void onResponse(Call call, Response response) {
                        response.close();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
