package com.ruoyi.system.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.system.service.WxAppService;
import com.ruoyi.system.utils.StaticValue;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class WxAppServiceImpl implements WxAppService {

    /**
     * 获取微信小程序的token
     * @return {@code Map<String, String>}
     */
    @Override
    public Map<String, String> getAccessToken() {
        HashMap<String, String> result = new HashMap<>();
        String url = "https://api.weixin.qq.com" + "/cgi-bin/token"  +
                "?" +
                "grant_type=client_credential" +
                "&appid=wx9f7c1acfec2ea44b" +
                "&secret=b3ab0c4ed75bad40de668803647bc720";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = client.newCall(request).execute()){
            if (response.isSuccessful()) {
                String responseBody = response.body().string();
                final JSONObject jsonObject = JSONObject.parseObject(responseBody);
                if(response.code() == 200) {
                    result.put("success", String.valueOf(response.code()));
                    result.put("access_token", (String) jsonObject.get("access_token"));
                    StaticValue.appAccessToken = (String) jsonObject.get("access_token");
                } else {
                    result.put("error", String.valueOf(response.code()));
                    result.put("error_message", (String) jsonObject.get("errormsg"));
                }
            } else {
                result.put("error", "获取token失败");
            }
        }catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return result;
    }
}
