package com.nantian.cloud.dbcapp.controller;


import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import com.nantian.cloud.dbcapp.unit.CheckoutUtil;
import com.nantian.sc.cloud.common.core.util.R;
import com.nantian.sc.cloud.common.log.annotation.SysLog;
import com.nantian.sc.cloud.common.security.annotation.Inner;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.CrossOrigin;
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.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@AllArgsConstructor
@RequestMapping(value = "msg")
public class WeChatActionController {
    /**
     * 微信消息接收和token验证
     * @param request
     * @param response
     * @throws IOException
     */
    @Inner(value = false)
    @RequestMapping("/weChatToken")
    @SysLog("微信消息接收和token验证")
    public void weChat(HttpServletRequest request, HttpServletResponse response) throws IOException {
        boolean isGet = request.getMethod().toLowerCase().equals("get");
        if (isGet) {
            // 微信加密签名
            String signature = request.getParameter("signature");
            // 时间戳
            String timestamp = request.getParameter("timestamp");
            // 随机数
            String nonce = request.getParameter("nonce");
            // 随机字符串
            String echostr = request.getParameter("echostr");
            // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
            boolean b = false;
                 b = CheckoutUtil.checkSignature(signature, timestamp, nonce,null);

            if (signature != null && b) {
                try {
                    PrintWriter print = response.getWriter();
                    print.write(echostr);
                    print.flush();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @RequestMapping("/getOpenId")
    @SysLog("获取微信openId")
    public R getOpenId(String code,String appid,String secret) throws IOException {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token";
        Map<String, Object> paraMap = new HashMap<>(16);
        paraMap.put("appid", appid);
        paraMap.put("secret", secret);
        paraMap.put("code", code);
        paraMap.put("grant_type", "authorization_code");
        String ret = HttpUtil.post(url, paraMap);
        //logger.info("请求微信获得openid结果：{}", ret);
        JSONObject jsonObject = new JSONObject(ret);
        if (!jsonObject.containsKey("errcode")) {
          String  open_id = jsonObject.getStr("openid");
          return R.ok(open_id);
        }else {
            return R.ok(jsonObject);
        }
       // logger.info("获取微信openid:"+open_id);
    }
}
