package com.mtcarpenter.mall.portal.controller;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;

@Slf4j
@Controller
@RequestMapping("/wechat/h5")
public class WechatH5Controller {
    /**
     * h5
     */
    @Autowired
    private WxMpService wxMpService;



    private static final String WECHAT_USER_INFO = "wechatUserInfo";

    /**
     * 请求微信服务器认证授权
     *
     * @param returnUrl 微信认证授权时的state参数
     * @return
     */

    @Value("${wx.mp.url}")
    private String url;

    @GetMapping("/authorize")
    public void authorize(@RequestParam("returnUrl") String returnUrl, HttpServletResponse response) throws IOException {
        // 用户授权完成后的重定向链接，441aca54.ngrok.io为使用ngrok代理后的公网域名，该域名需要替换为在微信公众号后台设置的域名，否则请求微信服务器不成功，一般都是采用将本地服务代理映射到一个可以访问的公网进行开发调试
        String redirectURL = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAuth2Scope.SNSAPI_USERINFO, URLEncoder.encode(returnUrl,"utf-8"));
        log.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
//        redirectURL ="https://www.baidu.com/";
        response.sendRedirect(redirectURL);
    }
    @Autowired
    ApplicationContext applicationContext;
    /**
     * 认证授权成功后返回微信用户信息
     *
     * @param code      微信授权成功后重定向地址后的code参数
     * @param returnUrl 请求微信授权时携带的state参数
     * @return
     * @throws Exception
     */
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                           @RequestParam("state") String returnUrl) throws Exception {
        log.info("【微信网页授权】code={}", code);
        log.info("【微信网页授权】state={}", returnUrl);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            // 获取accessToken
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            log.error("【微信网页授权】{}", e);
            throw new Exception(e.getError().getErrorMsg());
        }
        // 根据accessToken获取openId
        String openId = wxMpOAuth2AccessToken.getOpenId();
        log.info("【微信网页授权】openId={}", openId);
        //applicationContext.publishEvent(new LoginOutEvent(this,wxMpOAuth2AccessToken.getAccessToken()));
        // 获取用户信息
        WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        log.info("【微信网页授权】wxMpUser={}", wxMpUser);
        // 刷新accessToken
        wxMpService.oauth2refreshAccessToken(wxMpOAuth2AccessToken.getRefreshToken());
        // 验证accessToken是否有效
        wxMpService.oauth2validateAccessToken(wxMpOAuth2AccessToken);
//        MyWxMpUser myWxMpUser =new MyWxMpUser();
//        BeanUtils.copyProperties(wxMpUser,myWxMpUser);
//        //后台新增用户成功
//        ResultVO<String> wxlogin = customerClient.wxlogin(myWxMpUser);
//        Integer codeRe = wxlogin.getCode();
//        if (0!=codeRe){
//            log.error("登录出现错误!");
//            return  "登录出现错误!远程服务失败!";
//        }else{
//            String customerId = wxlogin.getData();
//            log.info(returnUrl+"?customerId="+customerId+"--------customerId================>{}",customerId);
//            //是否是发起跳转
//            return "redirect:" + returnUrl+"?customerId="+customerId;
//        }
        return "redirect:" + returnUrl;

    }


    /**
     * //签名成功生成支付订单
     *
     * @return
     * @throws GeneralSecurityException
     */
    private void insertPayOrder(Object object) {


    }

    public static String setXML(String return_code, String return_msg) {
        return "<xml><return_code><![CDATA[" + return_code + "]]></return_code><return_msg><![CDATA[" + return_msg + "]]></return_msg></xml>";
    }

    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        String[] split = ip.split(",");
        ip = split[0];
        return ip;
    }


//    /**
//     * 上线更新用户数据
//     * @return
//     * @throws Exception
//     */
//    @GetMapping("/update")
//    @ResponseBody
//    public Object userInfo() throws Exception {
//        applicationContext.publishEvent(new LoginOutEvent(this,"1"));
//        // 获取用户信息
//        WxMpUser wxMpUser = wxMpService.getUserService().userInfo("o_8t0t24aCWyepdPCbR3xO5uz4Rg");
//        log.info("【微信网页授权】wxMpUser={}", wxMpUser);
//        return wxMpUser;
//    }





}
