package cn.pluss.platform.utils;

import cn.pluss.platform.exception.MsgException;
import cn.pluss.platform.util.HttpUtil;
import cn.pluss.platform.wechat.WxConstants;
import cn.pluss.platform.wx.*;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Administrator
 */
public class WechatUtils {

    private static Logger logger = LoggerFactory.getLogger(WechatUtils.class);

    public static WxAccessTokenResponse getAccessToken(WxAccessTokenRequest request){
        String url = WxConstants.ACCESS_TOKEN_URL.replace("APPID", request.getAppid()).replace("SECRET", request.getSecret());
        try {
            JSONObject response = HttpUtil.httpRequest(url,"GET", null);
            if(response == null){
                MsgException.throwException("获取token请求失败");
            }
            if(response.containsKey(WxConstants.ERRCODE_NAME_PARAM)){
                logger.error("获取token失败,异常信息:{}", response.toJSONString());
                MsgException.throwException("获取token请求失败");
            }
            return JSONObject.parseObject(response.toJSONString(),WxAccessTokenResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取token失败,异常信息:{}",e.getMessage());
        }
        MsgException.throwException("获取token失败");
        return null;
    }

    public static WxOpenidResponse getWxOpenid(WxAccessTokenRequest request) {
        String url = request.getUrl().replace("APPID", request.getAppid()).replace("SECRET", request.getSecret()).replace("CODE",request.getCode());
        try {
            JSONObject response = HttpUtil.httpRequest(url,"GET", null);
            if(response == null){
                MsgException.throwException("获取openid请求失败");
            }
            if(response.containsKey(WxConstants.ERRCODE_NAME_PARAM) && !WxConstants.RESULT_SUCCESS_CODE.equals(response.getInteger(WxConstants.ERRCODE_NAME_PARAM))){
                logger.error("获取openid失败,异常信息:{}", response.toJSONString());
                MsgException.throwException("获取openid请求失败");
            }
            return JSONObject.parseObject(response.toJSONString(),WxOpenidResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取openid失败,异常信息:{}",e.getMessage());
            MsgException.throwException("获取openid失败");
        }
        return null;
    }

    /**
     * 发送微信模板消息
     * @date: 2021/11/29 18:22
     * @param accessToken:
     * @param request:
     */
    public static void sendTemplateMsg(String accessToken, WxTemolateRequest request) {
        String url = WxConstants.WX_SEND_TEMPLATE_URL.replace("ACCESS_TOKEN",accessToken);
        JSONObject response = HttpUtil.httpRequest(url, "POST", JSON.toJSONString(request));
        if(response == null){
            MsgException.throwException("模板消息发送失败！");
        }
        if(response.containsKey(WxConstants.ERRCODE_NAME_PARAM) && !WxConstants.RESULT_SUCCESS_CODE.equals(response.getInteger(WxConstants.ERRCODE_NAME_PARAM))){
            logger.error("模板消息发送失败,异常信息:{}", response.toJSONString());
            MsgException.throwException("模板消息发送失败");
        }
        logger.info("模板消息推送，推送人openid:{}",request.getTouser());
        logger.info("模板消息发送结果:{}",response.toJSONString());
    }

    /**
     * 微信网页授权信息获取
     * @date: 2021/11/30 10:32
     * @param request:
     * @return cn.pluss.platform.wx.WxOauth2AccessTokenResponse
     */
    public static WxOauth2AccessTokenResponse getOauth2AccessToken(WxAccessTokenRequest request) {
        String url = WxConstants.OAUTH2_ACCESS_TOKEN_URL.replace("APPID", request.getAppid()).replace("SECRET", request.getSecret()).replace("CODE",request.getCode());
        JSONObject response = HttpUtil.httpRequest(url, "GET", null);
        if (response == null)	{
            MsgException.throwException("微信获取网页授权信息接口失败");
        }
        if(response.containsKey(WxConstants.ERRCODE_NAME_PARAM) && !WxConstants.RESULT_SUCCESS_CODE.equals(response.getInteger(WxConstants.ERRCODE_NAME_PARAM))){
            logger.error("获取网页信息的失败,异常信息：{}",response.toJSONString());
            MsgException.throwException("微信获取网页授权信息接口失败");
        }
        return JSONObject.parseObject(response.toJSONString(),WxOauth2AccessTokenResponse.class);
    }

    public static WxUserInfoResponse getWxUserInfo(String accessToken,String openid) {
        String url = WxConstants.WX_USER_INFO_URL.replace("ACCESS_TOKEN", accessToken).replace("OPENID",openid);
        try {
            JSONObject response = HttpUtil.httpRequest(url,"GET", null);
            if(response == null){
                MsgException.throwException("获取微信用户信息异常");
            }
            if(response.containsKey(WxConstants.ERRCODE_NAME_PARAM) && !WxConstants.RESULT_SUCCESS_CODE.equals(response.getInteger(WxConstants.ERRCODE_NAME_PARAM))){
                logger.error("获取微信用户信息异常,异常信息:{}", response.toJSONString());
                MsgException.throwException("获取微信用户信息异常");
            }
            return JSONObject.parseObject(response.toJSONString(),WxUserInfoResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("获取微信用户信息异常,异常信息:{}",e.getMessage());
            MsgException.throwException("获取微信用户信息异常");
        }
        return null;
    }

    /**
     * 微信生成带参数的二维码
     * @date: 2021/12/9 11:26
     * @param accessToken:
     * @param qrCodeRequest:
     * @return cn.pluss.platform.wx.WxCreateQrCodeResponse
     */
    public static WxCreateQrCodeResponse getWxQrCode(String accessToken, WxCreateQrCodeRequest qrCodeRequest) {
        String url = WxConstants.WX_CREATE_QR_CODE_URL.replace("ACCESS_TOKEN", accessToken);
        try {
            JSONObject response = HttpUtil.httpRequest(url,"POST", JSON.toJSONString(qrCodeRequest));
            if(response == null){
                MsgException.throwException("生成微信带参数的二维码失败");
            }
            if(response.containsKey(WxConstants.ERRCODE_NAME_PARAM) && !WxConstants.RESULT_SUCCESS_CODE.equals(response.getInteger(WxConstants.ERRCODE_NAME_PARAM))){
                logger.error("生成微信带参数的二维码异常,异常信息:{}", response.toJSONString());
                MsgException.throwException("生成微信带参数的二维码异常");
            }
            return JSONObject.parseObject(response.toJSONString(),WxCreateQrCodeResponse.class);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("生成微信带参数的二维码异常,异常信息:{}",e.getMessage());
            MsgException.throwException("生成微信带参数的二维码异常");
        }
        return null;
    }

    /**
     * 获取微信jsapiticket
     * @param accessToken
     * @param type
     * @return
     */
    public static WxJsApiTicketResponse getJsapiTicket(String accessToken, String type) {
        String requestUrl = WxConstants.WX_TICKET_URL.replace("ACCESS_TOKEN", accessToken).replace("TYPE",type);
        JSONObject response = HttpUtil.httpRequest(requestUrl,"GET",null);
        if(response == null){
            MsgException.throwException("获取微信ticket异常");
        }
        if(response.containsKey(WxConstants.ERRCODE_NAME_PARAM) && !WxConstants.RESULT_SUCCESS_CODE.equals(response.getInteger(WxConstants.ERRCODE_NAME_PARAM))){
            logger.error("获取微信ticket异常,异常信息:{}", response.toJSONString());
            MsgException.throwException("获取微信ticket异常");
        }
        return JSONObject.parseObject(response.toJSONString(),WxJsApiTicketResponse.class);
    }

    /**
     * 获取小程序 scheme 码
     * @param request
     * @return
     */
    public static WxUrlschemeResponse getUrlecheme(WxUrlschemeRequest request,String accessToken) {
        String url = WxConstants.GENERATE_SCHEME.replace("ACCESS_TOKEN",accessToken);
        JSONObject response = HttpUtil.httpRequest(url, "POST", JSON.toJSONString(request));
        if(response == null){
            MsgException.throwException("获取微信小程序urlscheme异常");
        }
        WxUrlschemeResponse resp = JSONObject.parseObject(response.toJSONString(), WxUrlschemeResponse.class);
        if(!WxConstants.RESULT_SUCCESS_CODE.equals(resp.getErrcode())){
            logger.error("获取微信小程序urlscheme异常,异常信息:{}", resp.getErrmsg());
            MsgException.throwException("获取微信小程序urlscheme异常");
        }
        return resp;
    }
}
