package com.xxfc.platform.universal.controller;

import cn.hutool.core.codec.Base64;
import com.alibaba.fastjson.JSONObject;
import com.github.wxiaoqi.security.auth.client.annotation.IgnoreUserToken;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.github.wxiaoqi.security.common.util.process.ResultCode;
import com.xxfc.platform.universal.biz.WeixinService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.mockito.internal.util.collections.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


/**
 * @author Administrator
 */
@Controller
@RequestMapping("/auth")
@Slf4j
public class WeixinController {

    public static final String WECHAT_AUTOLOGIN_CALLBACKURL_KEY = "callback";

    public static final String frontSessionKey = "frontWeixKey";

    @Autowired
    WeixinService weixinService;

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



    @RequestMapping(value ="/app/unauth/wxLogin",method = RequestMethod.GET)
    @IgnoreUserToken
    public String wxLogin(@RequestParam(value = "redirec_url")String redirec_url){
        log.info("-----微信wxLogin---redirec_url=="+redirec_url);
        if (StringUtils.isBlank(redirec_url)){
            redirec_url="";
        }
        try {
        String encrypt_curr_url = Base64.encode(redirec_url.getBytes("utf-8"));
        redirec_url=url+"?" + WECHAT_AUTOLOGIN_CALLBACKURL_KEY+ "=" + encrypt_curr_url;
        String  oauth_api=weixinService.getAuthorize(redirec_url);
        return  String.format("redirect:"+oauth_api);
        }catch (Exception e){
            log.error(e.getMessage(), e);
            log.info("网络异常===" + e.getMessage());
            return  String.format("网络异常");
        }
    }


    /**
     * 微信浏览器获取用户信息
     * @param code
     * @param callback
     * @return
     */
    @GetMapping(value = "/app/unauth/userInfo")
    public String getUserInformation(String code, String callback, HttpServletRequest request) {
        log.info("-----微信回调userInfo---code=="+code+"----redirec_url==="+callback);
        try {
            authUser(code,request);
            callback =new String(Base64.decode(callback), "utf-8");
            log.info("callback===" + callback);
        }catch (Exception e){
            log.error(e.getMessage(), e);
            log.info("网络异常===" + e.getMessage());
        }
        return  String.format("redirect:"+callback);
    }



    public  void  authUser(String code,HttpServletRequest request){
        if (StringUtils.isBlank(code)){
            log.info("----code为空---");
            throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("code为空"));
        }
        String openid = null;
        String access_token = null;
        try {
            JSONObject jsonData = weixinService.getAccessToken(code);
            openid = jsonData.getString("openid");
            access_token = jsonData.getString("access_token");
            String refresh_token = jsonData.getString("refresh_token");
            log.info("-----微信回调userInfo---openid=="+openid+"----access_token==="+access_token);
            //验证access_token是否失效
            JSONObject validateData = weixinService.getValidateData(access_token, openid);
            if (!"0".equals(validateData.getString("errcode"))){
                //刷新access_token
                JSONObject refreshData= weixinService.getRefreshToken(refresh_token);
                access_token = refreshData.getString("access_token");
            }
            String encode = Base64.encode(openid);
            HttpSession session = request.getSession();
            session.removeAttribute(frontSessionKey);
            session.setAttribute(frontSessionKey, encode);
        }catch (Exception e){
            log.error(e.getMessage(), e);
            log.info("网络异常===" + e.getMessage());
            throw new BaseException(ResultCode.FAILED_CODE, Sets.newSet("网络异常"));
        }
    }

}
