package com.tashow.cloud.sdk.feishu.client;
import com.lark.oapi.Client;
import com.lark.oapi.service.im.v1.model.*;
import com.tashow.cloud.sdk.feishu.util.ChartImageGenerator;
import com.lark.oapi.service.im.v1.model.ext.MessageTemplate;
import com.lark.oapi.service.im.v1.model.ext.MessageTemplateData;
import java.io.File;
import java.util.*;
import com.tashow.cloud.sdk.feishu.config.LarkConfig;
import com.tashow.cloud.sdk.feishu.util.LarkClientUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
/**
 * 飞书告警客户端
 * 用于处理系统告警消息的发送
 */
@Service
public class FeiShuAlertClient {
    private final Client client;
    private final LarkConfig larkConfig;
    private final ChartImageGenerator chartImageGenerator;

    @Autowired
    public FeiShuAlertClient(LarkClientUtil larkClientUtil, LarkConfig larkConfig, 
                           ChartImageGenerator chartImageGenerator) {
        this.client = larkClientUtil.getLarkClient();
        this.larkConfig = larkConfig;
        this.chartImageGenerator = chartImageGenerator;
    }

    /**
     * 创建报警群并拉人入群
     *
     * @return 创建的群聊ID
     * @throws Exception 异常信息
     */
    public String createAlertChat() throws Exception {
        CreateChatReq req = CreateChatReq.newBuilder()
                .userIdType("open_id")
                .createChatReqBody(CreateChatReqBody.newBuilder()
                        .name("[待处理] 线上事故处理")
                        .description("线上紧急事故处理")
                        .userIdList(larkConfig.getAlertUserOpenIds())
                        .build())
                .build();
        CreateChatResp resp = client.im().chat().create(req);
        if (!resp.success()) {
            throw new Exception(String.format("client.im.chat.create failed, code: %d, msg: %s, logId: %s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }
        return resp.getData().getChatId();
    }


    /**
     * 发送报警消息
     *
     * @param chatId  会话ID
     * @param msgType 消息类型
     * @param content 消息内容
     * @return 消息ID
     * @throws Exception 异常信息
     */
    public String sendMessage(String chatId, String msgType, String content) throws Exception {
        CreateMessageReq req = CreateMessageReq.newBuilder()
                .receiveIdType("chat_id")
                .createMessageReqBody(CreateMessageReqBody.newBuilder()
                        .receiveId(chatId)
                        .msgType(msgType)
                        .content(content)
                        .build())
                .build();

        CreateMessageResp resp = client.im().message().create(req);
        if (!resp.success()) {
            throw new Exception(String.format("client.im.message.create failed, code: %d, msg: %s, logId: %s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }
        
        return resp.getData().getMessageId();
    }

    /**
     * 更新卡片消息
     *
     * @param messageId 消息ID
     * @param content   新的卡片内容
     * @throws Exception 异常信息
     */
    public void updateCardMessage(String messageId, String content) throws Exception {
        PatchMessageReq req = PatchMessageReq.newBuilder()
                .messageId(messageId)
                .patchMessageReqBody(PatchMessageReqBody.newBuilder()
                        .content(content)
                        .build())
                .build();
        PatchMessageResp resp = client.im().message().patch(req);

        if (!resp.success()) {
            throw new Exception(String.format("client.im.message.patch failed, code: %d, msg: %s, logId: %s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }
    }

    /**
     * 上传指定数据的监控图表（带错误信息）
     *
     * @param monitoringData 监控数据
     * @param errorMessage   错误信息
     * @return 上传后的图片KEY
     * @throws Exception 异常信息
     */
    public String uploadImage(List<ChartImageGenerator.MonitoringDataPoint> monitoringData, String errorMessage) throws Exception {
        // 动态生成监控图表
        File tempFile = File.createTempFile("alert", ".png");
        // 使用提供的数据生成图表
        chartImageGenerator.generateDashboardImage(tempFile, monitoringData, errorMessage);
        CreateImageReq req = CreateImageReq.newBuilder()
                .createImageReqBody(CreateImageReqBody.newBuilder()
                        .imageType("message")
                        .image(tempFile)
                        .build())
                .build();
        
        CreateImageResp resp = client.im().image().create(req);
        if (!resp.success()) {
            throw new Exception(String.format("client.im.image.create failed, code: %d, msg: %s, logId: %s",
                    resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }
        tempFile.delete();
        return resp.getData().getImageKey();
    }

    /**
     * 使用模板数据构建卡片内容
     * 
     * @param templateId 卡片模板ID
     * @param templateData 模板数据
     * @return 卡片JSON内容
     */
    public String buildCardWithData(String templateId, Map<String, Object> templateData) {
        return new MessageTemplate.Builder()
                .data(new MessageTemplateData.Builder().templateId(templateId)
                        .templateVariable(templateData)
                        .build())
                .build();
    }



    /**
     * 发送卡片消息
     *
     * @param chatId     会话ID
     * @param templateId 卡片模板ID
     * @param templateData 模板数据
     * @return 消息ID
     * @throws Exception 异常信息
     */
    public String sendCardMessage(String chatId, String templateId, Map<String, Object> templateData) throws Exception {
        String cardContent = buildCardWithData(templateId, templateData);
        return sendMessage(chatId, "interactive", cardContent);
    }
}
