package com.playlet.web.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.playlet.common.constant.PlayletConstants;
import com.playlet.common.utils.http.HttpUtils;
import com.playlet.web.core.config.WxConfig;
import com.playlet.web.service.WxService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WxServiceImpl implements WxService {

    private final WxConfig wxConfig;

    @Override
    public String getAccessToken() {
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxConfig.getAppId() + "&secret=" + wxConfig.getSecret();
        log.info("调用微信获取access_token,入参url:{}", url);
        String result = HttpUtils.sendGet(url);
        log.info("调用微信获取access_token,响应内容:{}", result);
        JSONObject json = JSONObject.parseObject(result);
        if(json.containsKey(PlayletConstants.ACCESS_TOKEN)){
            return json.getString(PlayletConstants.ACCESS_TOKEN);
        }
        return null;
    }

    @Override
    public String getOpenidByCode(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+ wxConfig.getAppId() + "&secret=" + wxConfig.getSecret() + "&js_code=" + code + "&grant_type=authorization_code";
        log.info("调用微信获取openId,入参url:{}", url);
        String result = HttpUtils.sendGet(url);
        log.info("调用微信获取openId,响应内容:{}", result);
        JSONObject json = JSONObject.parseObject(result);
        if(json.containsKey(PlayletConstants.OPEN_ID)){
            return json.getString(PlayletConstants.OPEN_ID);
        }
        return null;
    }
}
