package com.izouma.nineth.service.wx;

import com.izouma.nineth.config.SysConstants;
import com.izouma.nineth.exception.BusinessException;
import com.izouma.nineth.service.SysConfigService;
import me.chanjar.weixin.common.bean.WxJsapiSignature;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.impl.WxMpServiceHttpClientImpl;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * 自定义处理
 */
public class CustomWxMpServiceImpl extends WxMpServiceHttpClientImpl {

    private SysConfigService sysConfigService;

    public CustomWxMpServiceImpl(SysConfigService sysConfigService) {
        this.sysConfigService = sysConfigService;
    }

    /**
     * 是否开启
     * @return
     */
    private void checkWxSwitch(){
        boolean isOpen = sysConfigService.getBoolean(SysConstants.WX_MP_SWITCH);
        if(!isOpen){
            throw new BusinessException("微信公众号调用功能未开启");
        }
    }


    @Override
    public WxMpOAuth2AccessToken oauth2getAccessToken(String code) throws WxErrorException {
        //checkWxSwitch();

        return super.oauth2getAccessToken(code);
    }


    @Override
    public WxMpUser oauth2getUserInfo(WxMpOAuth2AccessToken token, String lang) throws WxErrorException {
        //checkWxSwitch();

        return super.oauth2getUserInfo(token, lang);
    }


    @Override
    public WxJsapiSignature createJsapiSignature(String url) throws WxErrorException {
        checkWxSwitch();
        //该方法内部使用了单线程锁定，所以并发效率非常低
        return super.createJsapiSignature(url);
    }

    @Override
    public String oauth2buildAuthorizationUrl(String redirectURI, String scope, String state) {
        //只是构建url,不需要校验处理
        //checkWxSwitch();
        return super.oauth2buildAuthorizationUrl(redirectURI, scope, state);
    }
}
