package com.seer.teach.mp.handler;

import com.seer.teach.mp.convert.MpMessageConvert;
import com.seer.teach.mp.entity.MpMessageEntity;
import com.seer.teach.mp.service.IMpMessageService;
import com.seer.teach.user.api.UserInfoServiceApi;
import com.seer.teach.user.api.dto.UserInfoDTO;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMessageHandler;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

import jakarta.annotation.Resource;
import java.util.Map;


@Component
@Slf4j
public class MessageReceiveHandler implements WxMpMessageHandler {

    @Resource
    private IMpMessageService mpMessageService;

    @Resource
    private UserInfoServiceApi userInfoServiceApi;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context,
                                    WxMpService wxMpService, WxSessionManager sessionManager) {
        log.info("[handle][接收到请求消息，内容：{}]", wxMessage);
        UserInfoDTO userInfoDTO = userInfoServiceApi.getByOpenId(wxMessage.getFromUser());
        MpMessageEntity wxMessageEntity = MpMessageConvert.INSTANCE.convertOne(wxMessage);
        wxMessageEntity.setUserId(userInfoDTO.getId());
        wxMessageEntity.setAppId(wxMpService.getWxMpConfigStorage().getAppId());
        log.info("[handle][保存消息，内容：{}]", wxMessageEntity);
        mpMessageService.save(wxMessageEntity);
        return WxMpXmlOutMessage.TEXT()
                .toUser(wxMessage.getFromUser())
                .fromUser(wxMessage.getToUser())
                .content("点击下方菜单进入seerTeach小程序")
                .build();
    }

}