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.LarkClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.Arrays;

/**
 * 飞书普通消息客户端
 * 用于处理与警报无关的消息发送
 */
@Service
public class FeiShuMessageClient {
    private final Logger log = LoggerFactory.getLogger(FeiShuMessageClient.class);
    private final Client client;
    

    
    @Autowired
    public FeiShuMessageClient(LarkClientUtil larkClientUtil) {
        this.client = larkClientUtil.getLarkClient();
    }

    /**
     * 发送通用消息
     * @param chatId 会话ID
     * @param msgType 消息类型
     * @param content 消息内容（不同消息类型有不同的格式要求）
     * @return 发送结果，包含消息ID和是否成功
     * @throws Exception 异常信息
     */
    public Map<String, Object> 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);
        Map<String, Object> result = new HashMap<>();
        result.put("success", resp.success());
        
        if (resp.success()) {
            result.put("messageId", resp.getData().getMessageId());
        } else {
            result.put("errorCode", resp.getCode());
            result.put("errorMessage", resp.getMsg());
            result.put("requestId", resp.getRequestId());
            log.error("发送消息失败: 类型={}, 错误码={}, 错误信息={}", msgType, resp.getCode(), resp.getMsg());
        }
        
        return result;
    }


    
    /**
     * 获取会话历史消息
     * @param chatId 会话ID
     * @return 消息列表
     * @throws Exception 异常信息
     */
    public List<Message> listChatHistory(String chatId) throws Exception {
        ListMessageReq req = ListMessageReq.newBuilder()
                .containerIdType("chat")
                .containerId(chatId)
                .build();

        ListMessageResp resp = client.im().message().list(req);

        if (!resp.success()) {
            throw new Exception(String.format("获取消息历史失败，错误码: %d, 错误信息: %s, 请求ID: %s", 
                    resp.getCode(), resp.getMsg(), resp.getRequestId()));
        }
        
        return Arrays.asList(resp.getData().getItems());
    }
    

} 