package org.springblade.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springblade.common.config.WxConfig;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

public class WechatQsUtil {

	public final static String APPID = WxConfig.QS_APP_ID;
	public final static String SECRET = WxConfig.QS_AppSecret;

//	public static JSONObject getSessionKeyOrOpenId(String code) {
//		String requestUrl = "https://api.weixin.qq.com/sns/jscode2session";
//		Map<String, String> requestUrlParam = new HashMap<>();
//		// https://mp.weixin.qq.com/wxopen/devprofile?action=get_profile&token=164113089&lang=zh_CN
//		//小程序appId
//		requestUrlParam.put("appid", APPID);
//		//小程序secret
//		requestUrlParam.put("secret", SECRET);
//		//小程序端返回的code
//		requestUrlParam.put("js_code", code);
//		//默认参数
//		requestUrlParam.put("grant_type", "authorization_code");
//		//发送post请求读取调用微信接口获取openid用户唯一标识
//		JSONObject jsonObject = JSON.parseObject(HttpClientUtil.doPost(requestUrl, requestUrlParam));
//		return jsonObject;
//	}

	public  static String getOpenid(String code) {
// 调用接口必要的参数
		StringBuilder data=new StringBuilder();
// appid、secret定义在配置文件中，注入到项目里
		data.append("appid="+APPID+"&");
		data.append("secret="+ SECRET+"&");
		data.append("js_code="+ code+"&");
		data.append("grant_type="+ "authorization_code");

		String response = HttpClientUtil.doGet("https://api.weixin.qq.com/sns/jscode2session?" + data);


		return response;
	}

	public static Object getPhoneNumber(String appCode){
		try {
			Map<String, String> params = new HashMap<>(1);
			params.put("code",appCode);
			HttpHeaders headers = new HttpHeaders();
			HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(params, headers);

//			String objectStr = HttpClientUtil.doPostJson(String.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s",getAccessToken()), JSONObject.toJSONString(httpEntity));
			RestTemplate restTemplate = new RestTemplate();
			ResponseEntity<Object> response = restTemplate.postForEntity(String.format("https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=%s",getAccessToken()), httpEntity, Object.class);
			return response.getBody();
		}catch (Exception e){
			e.printStackTrace();
//			log.error("微信code解析异常", e.getMessage());
		}
		return null;
	}

	public static String getAccessToken(){
		try {
			String objectStr = HttpClientUtil.doGet(String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",APPID, SECRET));
//			log.info(objectStr);
			JSONObject jsonObject = JSON.parseObject(objectStr);
			return jsonObject.getString("access_token");
		}catch (Exception e){
			e.printStackTrace();
//			log.error("微信code解析异常", e.getMessage());
		}
		return null;
	}
}
