package com.ywt.service.common;

import com.ywt.gapi.ResultCode;
import com.ywt.gapi.message.SendMPSubscribeMessageRequest;
import com.ywt.gapi.message.SendMPSubscribeMessageResponse;
import com.ywt.gapi.message.WeChatMessageServiceGrpc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author daiyihua
 * @create 2022-01-19 16:29
 * @program glasses_service
 * @description 消息推送服务调用
 **/
@Service
public class WeChatMessageService {

    private Logger logger = LoggerFactory.getLogger(WeChatMessageService.class);

    @Autowired
    private WeChatMessageServiceGrpc.WeChatMessageServiceBlockingStub weChatMessageServiceBlockingStub;


    /**
     * 发送小程序订阅消息
     *
     * @param terminal   终端
     * @param openId     openID
     * @param templateId 模版ID
     * @param page       跳转路径
     * @param keywordMap 携带参数
     */
    public void sendMPSubscribeMessage(int terminal, String openId, String templateId, String page, Map<String, String> keywordMap) {
        List<SendMPSubscribeMessageRequest.Keyword> keywordList = new LinkedList<>();
        for (String key : keywordMap.keySet()) {
            SendMPSubscribeMessageRequest.Keyword keyword = SendMPSubscribeMessageRequest.Keyword.newBuilder()
                    .setColor("#000")
                    .setValue(keywordMap.get(key))
                    .setKey(key)
                    .build();
            keywordList.add(keyword);
        }
        SendMPSubscribeMessageRequest req = SendMPSubscribeMessageRequest.newBuilder()
                .setTerminal(terminal)
                .setTouser(openId)
                .setTemplateId(templateId)
                .setPage(page)
                .addAllKeywords(keywordList)
                .build();
        SendMPSubscribeMessageResponse res = weChatMessageServiceBlockingStub.sendMPSubscribeMessage(req);
        if (res.getCode() != ResultCode.SUCCEED_VALUE) {
            logger.info("sendMPSubscribeMessage({})发送失败: {}", req, res.getInfo());
        }
    }
}
