package cn.iocoder.yudao.module.base.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaAnalysisService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.iocoder.yudao.module.base.service.WxPushMessagesService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class WxPushMessagesServiceImpl implements WxPushMessagesService {

    @Autowired
    private WxMaService wxMaService;

    /**
     * 发送订阅消息
     * @param openid 用户openid
     * @param templateId 模板ID
     * @param page 跳转页面
     * @param data 模板内容
     */
    @Override
    public void sendSubscribeMessage(String openid, String templateId, String page, Map<String, String> data) {
        WxMaSubscribeMessage message = new WxMaSubscribeMessage();
        message.setToUser(openid);
        message.setTemplateId(templateId);
        message.setPage(page);

        data.forEach((key, value) ->
                message.addData(new WxMaSubscribeMessage.MsgData(key, value))
        );

        try {
            wxMaService.getMsgService().sendSubscribeMsg(message);
        } catch (WxErrorException e) {
            log.error("微信消息推送失败: {}", e.getMessage());
        }
    }
}
