package com.liquidnet.service.sweet.controller;

import com.liquidnet.service.sweet.service.impl.SweetWechatCallbackServiceImpl;
import com.liquidnet.service.sweet.utils.WechatSignUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Api(tags = "公众号动作回调")
@RestController
@RequestMapping("/actionCallback")
@Slf4j
public class SweetWechatActionCallbackController {

    @Autowired
    private SweetWechatCallbackServiceImpl sweetWechatCallbackService;

    @Autowired
    private WechatSignUtils wechatSignUtils;

    @GetMapping("record")
    @ApiOperation("get")
    public void record(
            HttpServletResponse response,
            @RequestParam() String signature,
            @RequestParam() String timestamp,
            @RequestParam() String nonce,
            @RequestParam() String echostr
    ) {
        try {
            if (wechatSignUtils.checkSignature(signature, timestamp, nonce)) {
                log.info("验签通过");
                PrintWriter out = response.getWriter();
                out.print(echostr);
                out.close();
            } else {
                log.info("验签未通过");
            }
        } catch (Exception e) {
            log.info(e.getMessage());
        }
    }

    @PostMapping("record")
    @ApiOperation("post")
    public String record(
            @RequestBody String requestBody,
//            @RequestParam String requestBody,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam("openid") String openid,
            @RequestParam(name = "encrypt_type", required = false) String encType,
            @RequestParam(name = "msg_signature", required = false) String msgSignature
    ) {
        log.info("\n接收微信请求：[openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
                        + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                openid, signature, encType, msgSignature, timestamp, nonce, requestBody);
        if (!wechatSignUtils.checkSignature(signature, timestamp, nonce)) {
            log.info("验签未通过，非法请求，可能属于伪造的请求！");
            return "";
        }
        return sweetWechatCallbackService.record(requestBody, timestamp, nonce, encType, msgSignature);
    }
}
