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

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaMessage;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.constant.WxMaConstants;
import com.liquidnet.service.sweet.config.WechatMaConfigure;
import com.liquidnet.service.sweet.utils.WechatSignUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Objects;

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

    @Autowired
    WechatMaConfigure wechatMaConfigure;

    @Autowired
    private WechatSignUtils wechatSignUtils;

    public String authGet(Integer type, String timestamp, String nonce, String signature, String echostr) {
        if (wechatSignUtils.checkSignature(signature, timestamp, nonce)) {
            log.info("验签通过");
            return echostr;
        } else {
            log.info("验签未通过");
            return "非法请求";
        }
    }

    public String post(Integer type, String requestBody, String msgSignature, String encryptType, String signature, String timestamp, String nonce) {
        WxMaService wxService = wechatMaConfigure.getWxMaService(type);

        final boolean isJson = Objects.equals(wxService.getWxMaConfig().getMsgDataFormat(),
                WxMaConstants.MsgDataFormat.XML);
        if (StringUtils.isBlank(encryptType)) {
            // 明文传输的消息
            WxMaMessage inMessage;
            if (isJson) {
                inMessage = WxMaMessage.fromJson(requestBody);
            } else {//xml
                inMessage = WxMaMessage.fromXml(requestBody);
                log.info("inMessage{}",inMessage);
            }

            wechatMaConfigure.messageRouter(type).route(inMessage);
            return "success";
        }

        if ("aes".equals(encryptType)) {
            // 是aes加密的消息
            WxMaMessage inMessage;
            if (isJson) {
                inMessage = WxMaMessage.fromEncryptedJson(requestBody, wxService.getWxMaConfig());
            } else {//xml
                inMessage = WxMaMessage.fromEncryptedXml(requestBody, wxService.getWxMaConfig(),
                        timestamp, nonce, msgSignature);
            }

            wechatMaConfigure.messageRouter(type).route(inMessage);
            return "success";
        }

        throw new RuntimeException("不可识别的加密类型：" + encryptType);
    }
}
