package com.ics.controller.mobile;

import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import org.springframework.web.client.RestTemplate;

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

public class SmallWxOkHttp {

    static String APP_ID = "wx5582a07c1fbbcf06";
    static String SECRET = "ad24130a8919c613efd9538f69abafd3";

    public static JSONObject sendGet(String url, Map<String, String> map) {
        OkHttpClient client = new OkHttpClient();
        // 创建url
        HttpUrl.Builder urlBuilder = HttpUrl.parse(url).newBuilder();
        // 添加参数
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                urlBuilder.addQueryParameter(entry.getKey(), entry.getValue());
            }
        }
        // 创建请求
        Request request = new Request.Builder()
                .url(urlBuilder.build().toString())
                .build();
        try {
            Response response = client.newCall(request).execute();
            String resultStr = response.body().string();
            System.out.println(resultStr);
            return JSON.parseObject(resultStr);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static JSONObject sendPost(String url, Map<String, String> paramMap) {
        if (paramMap == null) {
            paramMap = new HashMap<>();
        }
        String jsonString = JSON.toJSONString(paramMap);
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        RequestBody body = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), jsonString);
        Request request = new Request.Builder()
                .post(body)
                .url(url)
                .build();
        Call call = client.newCall(request);
        //返回请求结果
        try {
            Response response = call.execute();
            String resultStr = response.body().string();
            System.out.println(resultStr);
            return JSON.parseObject(resultStr);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取AccessToken
     */
    public static String getAccessToken(String appId, String secret) {
        // url
        String url = "https://api.weixin.qq.com/cgi-bin/token";
        // 参数
        Map<String, String> map = new HashMap<>();
        map.put("grant_type", "client_credential");
        map.put("appid", appId);
        map.put("secret", secret);
        // 发送请求
        JSONObject jsonObject = sendGet(url, map);
        String accessToken = jsonObject.getString("access_token");
        String expiresIn = jsonObject.getString("expires_in");
        return accessToken;
    }

    /**
     * 小程序登录
     */
    public static JSONObject code2Session(String jsCode, String appId, String secret) {
        // url
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        // 参数
        Map<String, String> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", secret);
        map.put("js_code", jsCode);
        map.put("grant_type", "authorization_code");
        // 发送请求
        JSONObject jsonObject = sendGet(url, map);
        return jsonObject;
    }

    /**
     * 获取手机号
     */
    public static JSONObject getPhoneNumber(String code, String openid, String accessToken) {
        // url
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
        // 参数
        Map<String, String> map = new HashMap<>();
        map.put("code", code);
        map.put("openid", openid);
        // 发送请求
        JSONObject jsonObject = sendPost(url, map);
        return jsonObject;
    }


    /*
     * 发送模板
     *
     * name01 :{
     *  value :
     * }
     */
    public static String push() {

        JSONObject map = new JSONObject();

        JSONObject  jsonObject = new JSONObject();
        JSONObject thing1 = new JSONObject();
        thing1.put("value","123456");
        jsonObject.put("thing1",thing1);
        JSONObject time2 = new JSONObject();
        time2.put("value","2022-01-01 12:00:00");
        jsonObject.put("time2",time2);
        JSONObject thing3 = new JSONObject();
        thing3.put("value","789");
        jsonObject.put("thing3",thing3);

        map.put("touser", "o0_yY69LcLUi_x62WyH5Wvpe0tsA");
        map.put("template_id", "lSuc6ocmiPVoXP7ohyJ38wAqZKP2Nn-rhjCxM9JjvBI");

        map.put("page","/page/index/index");
        map.put("miniprogram_state","formal");
        map.put("lang","zh_CN");
        map.put("data",jsonObject);

        System.out.println(map);


        String result = HttpRequest.post("https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+getAccessToken(APP_ID,SECRET))
                .body(map.toString()).timeout(30*1000).execute().body();

        JSONObject jsonObject1 = JSON.parseObject(result);
        System.out.println(jsonObject1);
//        Boolean success = Boolean.valueOf(jsonObject1.getString("success"));
//        log.info("情景面板接口返回结果：{}",jsonObject1);
//
//        log.info(DateUtil.date()+" -------情景面板接口结果：{}",success);


//        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="+getAccessToken(APP_ID,SECRET);
//

//
//        System.out.println("-------"+jsonObject);
//        Map<String, String> map = new HashMap<>();
//        map.put("touser", "o0_yY69LcLUi_x62WyH5Wvpe0tsA");
//        map.put("template_id", "lSuc6ocmiPVoXP7ohyJ38wAqZKP2Nn-rhjCxM9JjvBI");
//
//        map.put("page","/page/index/index");
//        map.put("miniprogram_state","formal");
//        map.put("lang","zh_CN");
//        map.put("data",jsonObject.toString());
//        System.out.println(map);
////        return new JSONObject();
//        JSONObject jsonObject1 = sendPost(url, map);
        return "jsonObject1";
    }


        public static void main (String[]args){
        push();
//        getAccessToken();
//            getPhoneNumber("", "", "74_NGF_xru4Mt5gDVperBd9LYwtMjWaXGb7JNleZ-nqSOSGvtW3vIGYKkFY0ymMFn2aLYZaN9d1rAZ65X5X-mGX556bWQWFy1mawkWUorOvz37QH34q2YBJjsDCih8FYOfAHAWPF");
        }

    }
