package vip.xiaonuo.biz.modular.api.controller;

import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import vip.xiaonuo.biz.modular.api.service.ApiService;
import vip.xiaonuo.biz.modular.utils.SignUtil;
import vip.xiaonuo.common.prop.CommonProperties;

import java.io.IOException;
import java.io.PrintWriter;

@Tag(name = "微信公众号")
@RestController
@Validated
public class ApiController {

    @Resource
    private CommonProperties commonProperties;

    @Resource
    private ApiService apiService;

    /***
     * 微信公众号验证接口
     * @param request
     * @param response
     */
    @GetMapping("/api/wxOpen")
    public void get(HttpServletRequest request, HttpServletResponse response) {
        // 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，否则接入失败
            if (SignUtil.checkSignature(commonProperties.getOfficialToken(), signature, timestamp, nonce)) {
                out.print(echostr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }


    /**
     * 微信公众号操作事件(包括关注和取消动作操作)
     *
     * @param request
     * @param response
     */
    @PostMapping("/api/wxOpen")
    public void officialCallback(HttpServletRequest request, HttpServletResponse response) {
        apiService.officialCallback(request, response);
    }
}
