package com.ssm.controller;

import com.ssm.manage.query.InstanceVariables;
import com.ssm.manage.utils.CheckoutUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Map;

@RestController
@RequestMapping(value = "wx")
@Api("微信")
public class WeiController {

    /**
     * 公众号appid
     */
    @Value("${wx.appid}")
    private  String appid;

    /**
     * 公众号appSecret
     */
    @Value("${wx.secret}")
    private  String secret;

    /**
     * 微信消息接收和token验证
     * @param request
     * @param response
     * @throws IOException
     */
//    @GetMapping("/weChatToken")
    @PostMapping("/weChatToken")//关注和取消公众号回调
    public void weChat(HttpServletRequest request, HttpServletResponse response) {
//        boolean isGet = request.getMethod().toLowerCase().equals("get");
        boolean isGet = request.getMethod().toLowerCase().equals("post");
//        ((RequestFacade) (request).request).request.coyoteRequest.getParameters().queryMB.strValue;
        String openids = null;
        if (isGet) {
            Map<String, String[]> map= request.getParameterMap();
            if (null!=map){
                if (null!=request.getParameterMap().get("openid"))
                openids = request.getParameterMap().get("openid")[0];
                InstanceVariables.setOpenid(openids);
                InstanceVariables.setDate(new Date());
            }
        }
    }

    @GetMapping("/weChatToken")
//    @PostMapping("/weChatToken")//公众号配置服务器认证
    public void weChat1(HttpServletRequest request, HttpServletResponse response) {
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        String openids = null;
        if (isGet) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            if (signature != null && CheckoutUtil.checkSignature(signature, timestamp, nonce)) {
                try {
                    PrintWriter print = response.getWriter();
                    print.write(echostr);
                    print.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
