package cn.iocoder.yudao.module.basic.util;

import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class WXUtils {

    /** 这些参数暂时放这个工具类里面 */
    public static final String APPID = "wx95ceacc2f2bbc208";

    public static final String APPSECRET = "d0fd416146e15a07935ca626e89616df";

    /**全局token 所有与微信有交互的前提 */
    public static volatile String ACCESS_TOKEN;

    /**全局token上次获取事件 */
    public static volatile long LASTTOKENTIME;

    /**
     * 获取全局token方法
     * 该方法通过使用HttpClient发送http请求，HttpGet()发送请求String
     * 微信返回的json中access_token是我们的全局token
     * 注意，如果多个微服务都有，可能无法保证access_token的有效性
     */
    public static synchronized String getAccessToken(){
        String strURL = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + APPID + "&secret=" + APPSECRET ;
        InputStream is = null;
        if(ACCESS_TOKEN == null || System.currentTimeMillis() - LASTTOKENTIME > 7000 * 1000){
            try {
                HttpURLConnection connection = WXUtils.createConnection(strURL);
                // 读取响应
                assert connection != null;
                is = connection.getInputStream();
                int length = connection.getContentLength();// 获取长度
                if (length != -1) {
                    byte[] data = new byte[length];
                    byte[] temp = new byte[512];
                    int readLen;
                    int destPos = 0;
                    while ((readLen = is.read(temp)) > 0) {
                        System.arraycopy(temp, 0, data,destPos, readLen);
                        destPos += readLen;
                    }
                    String result = new String(data, StandardCharsets.UTF_8); // utf-8编码
                    Map<String, Object> mapTypes = JSONObject.parseObject(result);
                    for (Object obj: mapTypes.keySet()){
                        if(obj.equals("access_token")) {
                            ACCESS_TOKEN = (String)mapTypes.get(obj);
                            LASTTOKENTIME = System.currentTimeMillis();
                        }
                    }
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    assert is != null;
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ACCESS_TOKEN;
    }

    public static synchronized String getPhoneNumber(String code) {
        if(ACCESS_TOKEN != null && System.currentTimeMillis() - LASTTOKENTIME < 7000 * 1000) {
            String strURL = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + ACCESS_TOKEN;
            Map<String, Object> params = new HashMap<>();
            params.put("code", code);
            params.put("access_token", ACCESS_TOKEN);
            String result = HttpUtil.post(strURL, params);

            Map<String, Object> mapTypes = JSONObject.parseObject(result);
            if((int)mapTypes.get("errcode") == 0) {
                Map<String, Object> phoneInfoMaps = JSONObject.parseObject(mapTypes.get("phone_info").toString());
                if(phoneInfoMaps != null) {
                    return phoneInfoMaps.get("purePhoneNumber").toString();
                }
            } else {
                log.error("-- 调用微信接口 code2Session 失败:errcode:{}  errmsg:{}", mapTypes.get("errcode").toString(), mapTypes.get("errmsg").toString());
                throw ServiceExceptionUtil.exception0(GlobalErrorCodeConstants.THIRD_PARTY_INTERFACE_CALL_FAILED.getCode(),
                        StrUtil.format("微信接口[code2Session]调用失败:errcode:{}  errmsg:{}", mapTypes.get("errcode").toString(), mapTypes.get("errmsg").toString()));
            }
            return null;
        } else {
            WXUtils.getAccessToken();
            return WXUtils.getPhoneNumber(code);
        }
    }

    public static synchronized String code2Session(String code) {
        // 后续可考虑使用https://gitee.com/binary/weixin-java-tools 开源工具
        if(ACCESS_TOKEN != null && System.currentTimeMillis() - LASTTOKENTIME < 7000 * 1000) {
            // String strURL = "https://api.weixin.qq.com/sns/jscode2session?grant_type=authorization_code&appid=" + APPID + "&secret=" + APPSECRET + "&js_code=" + code;
            String strURL = "https://api.weixin.qq.com/sns/jscode2session";
            Map<String, Object> params = new HashMap<>();
            params.put("appid", APPID);
            params.put("secret", APPSECRET);
            params.put("js_code", code);
            params.put("grant_type", "authorization_code");
            String result;
            try {
                result = HttpUtil.get(strURL, params);
            } catch (IORuntimeException e) {
                throw ServiceExceptionUtil.exception0(GlobalErrorCodeConstants.THIRD_PARTY_INTERFACE_CALL_FAILED.getCode(),
                        StrUtil.format("微信接口[code2Session]调用失败: errmsg:{}", e.getMessage()));
            }
            Map<String, Object> mapTypes = JSONObject.parseObject(result);
            if(mapTypes.get("errcode") == null || (int)mapTypes.get("errcode") == 0) {
                return mapTypes.get("openid").toString();
            } else {
                log.error("-- 调用微信接口 code2Session 失败:errcode:{}  errmsg:{}", mapTypes.get("errcode").toString(), mapTypes.get("errmsg").toString());
                throw ServiceExceptionUtil.exception0(GlobalErrorCodeConstants.THIRD_PARTY_INTERFACE_CALL_FAILED.getCode(),
                        StrUtil.format("微信接口[code2Session]调用失败:errcode:{}  errmsg:{}", mapTypes.get("errcode").toString(), mapTypes.get("errmsg").toString()));
            }
        } else {
            WXUtils.getAccessToken();
            return WXUtils.code2Session(code);
        }
    }

    public static HttpURLConnection createConnection(String urlStr) {
        OutputStreamWriter out = null;
        try {
            URL url = new URL(urlStr);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("GET"); // 设置请求方式
            connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
            connection.setRequestProperty("Content-Type", "application/json"); //设置发送数据的格式
            connection.connect();
            out = new OutputStreamWriter(connection.getOutputStream(), StandardCharsets.UTF_8); // utf-8编码
            out.flush();
            out.close();
            return connection;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert out != null;
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static void main(String[] args) {
        System.out.println(WXUtils.getAccessToken());
    }
}
