package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.system.config.WxConfig;
import com.ruoyi.system.mapper.Vo.WXResponse;
import com.ruoyi.system.service.WXService;
import lombok.extern.slf4j.Slf4j;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Slf4j
@Service
public class WXServiceImpl implements WXService {
    @Resource
    private WxConfig wxConfig;

    @Override
    public WXResponse getWXOpenId(String code) {
        String url = "https://api.weixin.qq.com/sns/jscode2session?" +
                "appid=" + wxConfig.getAppid() + "&secret=" + wxConfig.getAppSecret() + "&js_code=" + code + "&" +
                "grant_type=authorization_code";

        OkHttpClient client = new OkHttpClient();

        // 创建一个 GET 请求
        Request request = new Request.Builder()
                .url(url) // 替换为你想要请求的 URL
                .build();

        try (Response response = client.newCall(request).execute()) {
            // 检查响应是否成功
            if (response.isSuccessful()) {
                // 打印响应体
                String result = response.body().string();
                WXResponse wxResponse = JSONObject.parseObject(result, WXResponse.class);
                return wxResponse;
            } else {
                // 处理错误情况
                log.error("获取Openid错误{}","请求失败: " + response.code());
                System.err.println("请求失败: " + response.code());
                return null;
            }
        } catch (Exception e) {
            log.error("获取Openid错误{}",e);
            e.printStackTrace();
        }
        return null;
    }
}
