package com.platform.yijia.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.platform.yijia.pojo.AppUserInfo;
import com.platform.yijia.service.AppUserInfoService;
import com.platform.yijia.utils.ConstantUtil;
import com.platform.yijia.utils.HttpClientUtil;
import com.platform.yijia.utils.SignUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.List;

/**
 * @Author : suxinghua
 * @CreateTime : 2020/11/25
 * @Description :
 **/

@Controller
@RequestMapping("/demo")
public class WXLoginController {

    @Resource
    private AppUserInfoService appUserInfoService;
    /**
     * 用于给微信验证token
     *
     * @param request
     * @param response
     * @return
     * @throws IOException
     */
    @RequestMapping("/checkToken")
    public String checkToken(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        if (SignUtil.checkSignature(signature, timestamp, nonce)) {
            System.out.println("校验token成功");
            return echostr;
        } else {
            System.out.println("校验token不成功");
            return null;
        }
    }

    /**
     * 用于获取出回调地址  （引导用户调用此接口，成功后自动调取回调地址然后取出用户信息）
     *
     * @param response
     * @throws IOException
     */
    @RequestMapping("/wxLogin")
    public String wxLogin(HttpServletResponse response)  throws ParseException,IOException {
        //请求获取code的回调地址
        //用线上环境的域名或者用内网穿透，不能用ip
        String callBack = "http://www.onlyfido.top/wxAuth/callBack";//域名填你自己的
        //请求地址
        String url = null;
        try {
            url = "https://open.weixin.qq.com/connect/oauth2/authorize" +
                    "?appid=" + ConstantUtil.APPID +
                    "&redirect_uri=" + URLEncoder.encode(callBack, "utf-8") +
                    "&response_type=code" +
                    "&scope=snsapi_userinfo" +
                    "&state=STATE#wechat_redirect";
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        System.out.println(url);
        //重定向
//        response.sendRedirect(url);
        return  "redirect:"+url;
    }

    @RequestMapping("getMpOpenIdByCode")
    public String getOpenIdByCode(String code){
        //获取access_token
        String url = "https://api.weixin.qq.com/sns/jscode2session" +
                "?appid=" + ConstantUtil.MPAPPID +
                "&secret=" + ConstantUtil.MPAPPSECRET +
                "&js_code=" + code +
                "&grant_type=authorization_code";
        String result = HttpClientUtil.doGet(url);
        System.out.println("请求获取access_token:" + result);
        //返回结果的json对象
        JSONObject resultObject = JSON.parseObject(result);
        //请求获取userInfo
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + resultObject.getString("access_token") +
                "&openid=" + resultObject.getString("openid") +
                "&lang=zh_CN";
        String resultInfo = HttpClientUtil.doGet(infoUrl);

        return  resultInfo;
    }

    /**
     * 回调方法
     *
     * @param request
     * @param response
     * @throws IOException
     */
    //	回调方法
    @RequestMapping("/callBack")
    public String wxCallBack(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = request.getParameter("code");
        //获取access_token
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                "?appid=" + ConstantUtil.APPID +
                "&secret=" + ConstantUtil.APPSECRET +
                "&code=" + code +
                "&grant_type=authorization_code";

        String result = HttpClientUtil.doGet(url);

        System.out.println("请求获取access_token:" + result);
        //返回结果的json对象
        JSONObject resultObject = JSON.parseObject(result);

        //请求获取userInfo
        String infoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                "?access_token=" + resultObject.getString("access_token") +
                "&openid=" + resultObject.getString("openid") +
                "&lang=zh_CN";

        String resultInfo = HttpClientUtil.doGet(infoUrl);
        JSONObject resultInfoObject = JSON.parseObject(resultInfo);
        AppUserInfo appUserInfo =new AppUserInfo();

        if(StringUtils.isNotBlank(resultInfoObject.getString("openid"))){
            appUserInfo.setBlogOpenid(resultInfoObject.getString("openid"));
        }
        if(StringUtils.isNotBlank(resultInfoObject.getString("nickname"))){
            appUserInfo.setBlogNickName(resultInfoObject.getString("nickname"));
        }
        if(StringUtils.isNotBlank(resultInfoObject.getString("sex"))){
            appUserInfo.setSexFlag(resultInfoObject.getString("sex"));
        }
        if(StringUtils.isNotBlank(resultObject.getString("access_token"))){
            appUserInfo.setBlogToken(resultObject.getString("access_token"));
        }
        appUserInfo.setUserType("1");//公众号
        //查询用户是否存在
        List<AppUserInfo> list =appUserInfoService.Authentication(appUserInfo);
        if(list!=null && list.size()==0){
            appUserInfoService.AddAppUserInfo(appUserInfo);
        }
        //此时已获取到userInfo，再根据业务进行处理
        System.out.println("请求获取userInfo:" + resultInfo);
        //跳转网页地址
        System.out.println("跳转网页地址:" + "redirect:"+"http://www.onlyfido.top:45060/?openid="+resultObject.getString("openid"));
        return "redirect:"+"http://www.onlyfido.top:45060/?openid="+resultObject.getString("openid");
    }

}
