package com.liquidnet.service.sweet.controller;

import com.liquidnet.service.sweet.service.impl.SweetWechatApplyEventPushServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@Api(tags = "小程序-事件推送")
@RestController
@RequestMapping("/applyEventPush")
@Slf4j
public class SweetWechatApplyEventPushController {

    @Autowired
    private SweetWechatApplyEventPushServiceImpl pushService;

    //    @GetMapping(produces = "text/plain;charset=utf-8")
    @GetMapping("{type}")
    @ApiOperation("验签调用")
    public String authGet(
            @PathVariable Integer type,
            @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
    ) {
        log.info("\n接收到来自微信服务器的认证消息：signature = [{}], timestamp = [{}], nonce = [{}], echostr = [{}]",
                signature, timestamp, nonce, echostr);

        if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
            throw new IllegalArgumentException("请求参数非法，请核实!");
        }

        return pushService.authGet(type, timestamp, nonce, signature, echostr);
    }

    //        @PostMapping(value = "{type}", produces = "application/xml; charset=UTF-8")
    @PostMapping("{type}")
    @ApiOperation("用户动作回调")
    public String post(
            @PathVariable Integer type,
            @RequestBody String requestBody,
            @RequestParam(name = "msg_signature", required = false) String msgSignature,
            @RequestParam(name = "encrypt_type", required = false) String encryptType,
            @RequestParam(name = "signature", required = false) String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce
    ) {
        log.info("\n接收微信请求：[msg_signature=[{}], encrypt_type=[{}], signature=[{}]," +
                        " timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ",
                msgSignature, encryptType, signature, timestamp, nonce, requestBody);

        return pushService.post(type, requestBody, msgSignature, encryptType, signature, timestamp, nonce);
    }

}
