package com.liquidnet.service.sweet.service.impl;

import com.liquidnet.service.sweet.config.WechatMpConfigure;
import lombok.extern.slf4j.Slf4j;
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.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 公众号动作回调 服务实现类
 * </p>
 *
 * @author liquidnet
 * @since 2021-07-31
 */
@Service
@Slf4j
public class SweetWechatCallbackServiceImpl {

    @Autowired
    WechatMpConfigure wechatMpConfigure;

    public String record(String requestBody, Integer type, String timestamp, String nonce, String encType, String msgSignature) {
        if (null == type || type <= 0) {
            type = 1;
        }
        WxMpService wxMpService = wechatMpConfigure.getWxMpService(type);
        String out = null;
        if (encType == null || encType.isEmpty()) {
            // 明文传输的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
            log.info("\n消息内容为：\n[{}] ", inMessage.toString());
            WxMpXmlOutMessage outMessage = wechatMpConfigure.messageRouter(type).route(inMessage);
            if (outMessage == null) {
                // 假如服务器无法保证在五秒内处理并回复，可以直接回复空串，微信服务器不会对此作任何处理，并且不会发起重试
                return "";
            }
            out = outMessage.toXml();
        } else if ("aes".equalsIgnoreCase(encType)) {
            // aes加密的消息
            WxMpXmlMessage inMessage = WxMpXmlMessage.fromEncryptedXml(requestBody, wxMpService.getWxMpConfigStorage(),
                    timestamp, nonce, msgSignature);
            log.info("\n消息解密后内容为：\n[{}] ", inMessage.toString());
            WxMpXmlOutMessage outMessage = wechatMpConfigure.messageRouter(type).route(inMessage);
            if (outMessage == null) {
                return "";
            }
            out = outMessage.toEncryptedXml(wxMpService.getWxMpConfigStorage());
        }
        log.info("\n组装回复信息：[{}]", out);
        return out;
    }
}
