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("配置验签微信调用")
    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=[{}]]", e.getMessage());
        }
    }

    @PostMapping("record")
    @ApiOperation("用户动作微信回调")
    public String record(
            @RequestBody String requestBody,
//            @RequestParam() String requestBody,
            @RequestParam("type") Integer type,
            @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
    ) {
        try {
            log.info("\n接收微信请求：[type=[{}], openid=[{}], [signature=[{}], encType=[{}], msgSignature=[{}],"
                            + " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                    type, openid, signature, encType, msgSignature, timestamp, nonce, requestBody);
            if (!wechatSignUtils.checkSignature(signature, timestamp, nonce)) {
                log.info("验签未通过，非法请求，可能属于伪造的请求！");
                return "";
            }
            return sweetWechatCallbackService.record(requestBody, type, timestamp, nonce, encType, msgSignature);
        } catch (Exception e) {
            log.error("用户动作微信回调Exception：[msg=[{}], e=[{}]]", e.getMessage(), e);
            return "";
        }
    }
}
