package com.xingxi.api.configuration.security;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.xingxi.common.core.domain.entity.SysUser;
import com.xingxi.api.common.ApiException;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class WxLoginAuthenticationProcessingFilter extends UsernamePasswordAuthenticationFilter {
    private final WxLoginAuthenticationManager authenticationManager;
    private final WxMaService wxMaService;
    private final WxMpService wxMpService;

    public WxLoginAuthenticationProcessingFilter(final WxLoginAuthenticationManager authenticationManager, final WxMaService wxMaService, WxMpService wxMpService) {
        this.authenticationManager = authenticationManager;
        this.wxMaService = wxMaService;
        this.wxMpService = wxMpService;
        setAuthenticationManager(authenticationManager);
        setFilterProcessesUrl("/api/store/wxlogin");
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        log.debug("WxLoginAuthenticationProcessingFilter.attemptAuthentication()....");

        String jsCode = request.getParameter("jsCode");
        Assert.hasText(jsCode, "jsCode不能为空");

        log.debug("jsCode = " + jsCode);
        WxMaJscode2SessionResult result = null;
        WxOAuth2AccessToken accessToken = null;
        try {
            accessToken = wxMpService.getOAuth2Service().getAccessToken(jsCode);
//            result = wxMaService.jsCode2SessionInfo(jsCode);
        } catch (WxErrorException e) {
            e.printStackTrace();
            log.debug("微信登录失败");
            throw new ApiException("wxlogin.error");
        }

        String sessionKey = "";
//        sessionKey = result.getSessionKey();
        String openid = "";
//        openid = result.getOpenid();

        openid = accessToken.getOpenId();

        SysUser sysUser = new SysUser();
        sysUser.setWxOpenId(openid);
        sysUser.setWxSessionKey(sessionKey);

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(sysUser, sessionKey);
        return authenticationManager.authenticate(token);
    }

}
