package com.xingxi.api.configuration;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaMessage;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import cn.binarywang.wx.miniapp.message.WxMaMessageHandler;
import cn.binarywang.wx.miniapp.message.WxMaMessageRouter;
import cn.binarywang.wx.miniapp.message.WxMaXmlOutMessage;
import lombok.RequiredArgsConstructor;
import me.chanjar.weixin.common.api.WxConsts;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@RestController
@RequestMapping("/wx/message")
@RequiredArgsConstructor
public class WXMessageEndpoint {
    private final WxMaService wxMaService;
    private final WxMaMessageHandler wxMaMessageHandler;


    @PostMapping
    public String message(HttpServletRequest request, HttpServletResponse response) {
        WxMaMessageRouter router = new WxMaMessageRouter(wxMaService);
        router.rule()
                .msgType(WxConsts.XmlMsgType.EVENT)
                .event("wxa_media_check")
                .handler(wxMaMessageHandler)
                .end();

        WxMaConfig wxMaConfig = wxMaService.getWxMaConfig();

        try {
            WxMaMessage wxMaMessage = WxMaMessage.fromEncryptedJson(request.getInputStream(), wxMaConfig);
            WxMaXmlOutMessage route = router.route(wxMaMessage);
        } catch (IOException e) {
            e.printStackTrace();

            return "fail";
        }

        return "success";

    }

}
