package com.ematou.wxservice.controller;

import com.alibaba.fastjson.JSONObject;
import com.ematou.wxservice.common.utils.SignUtil;
import com.ematou.wxservice.common.web.R;
import com.ematou.wxservice.mp.message.WeChatMessage;
import com.ematou.wxservice.mp.message.WeChatMpXmlOutMessage;
import com.ematou.wxservice.service.WeChatMessageService;
import com.ematou.wxservice.utils.HttpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author lhm
 * @version 1.0
 * 2021-05-11 11:48
 */
@RestController
public class WeChatMessageController {
    private static final Logger log = LoggerFactory.getLogger(WeChatMessageController.class);
    @Autowired
    WeChatMessageService weChatMessageService;

    /**
     * 微信公众号消息回调 用于微信鉴权
     * @param signature 微信的签名，需要跟自己的签名比对，相同才成功
     * @param timestamp 时间戳
     * @param nonce     随机数字
     * @param echostr   随机字符串
     * @param request   请求
     * @param response  响应
     * @return          字符串
     */
    @GetMapping("/message")
    public String sign(@RequestParam(name = "signature",required = false) String signature,
                       @RequestParam(name = "timestamp",required = false) String timestamp,
                       @RequestParam(name = "nonce",required = false) String nonce,
                       @RequestParam(name = "echostr",required = false) String echostr,
                       HttpServletRequest request, HttpServletResponse response){
        log.info("收到微信发来GET请求信息！signature：{}，timestamp：{}，nonce：{}，echostr：{}，" ,signature,timestamp,nonce,echostr);
        if(SignUtil.checkSignature(signature, timestamp, nonce)) {
            return echostr;
        }
        return "";
    }

    /**
     * 消息入口，由于微信平台在5s内无返回信息会进行重试，返回空字符串则不会重试
     */
    @PostMapping("/message")
    public String handleMessage(HttpServletRequest request, HttpServletResponse response){
        log.info("收到微信发来信息！");
        try {
            ServletInputStream inputStream = request.getInputStream();

            WeChatMessage weChatMessage = WeChatMessage.fromXml(inputStream);
            log.info("收到微信发来信息！"+ JSONObject.toJSON(weChatMessage));
            //消息分发
            WeChatMpXmlOutMessage outTextMessage = weChatMessageService.handleMessage(weChatMessage);
            return null == outTextMessage ? "" : outTextMessage.toXml();
        } catch (IOException e) {
            log.error("微信信息处理异常：",e);
            e.printStackTrace();
        }
        return "";
    }



    /**
     * 生成二维码信息
     * @return
     */
    @PostMapping("/generateqRcode")
    public R<Object> generateqRcode(@RequestBody JSONObject msg){
        log.info("生成取件二维码！");
        try {
            return new R<>().success(weChatMessageService.generateqRcodeService(msg));
        }catch (Exception e){
            log.error("生成取件二维码失败！",e);
            return new R<>().error("生成取件二维码失败!");
        }
    }

}
