package cn.iocoder.yudao.module.appBase.utils;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

/**
 * @Author LBK
 * @Date 2022/12/18 18:11
 */
public class WxUtil {


    /**
     * 调用微信开放接口 获取小程序全局唯一后台接口调用凭据（access_token）
     * @return
     */
    public static String getAccessToken(Map<String,Object> params){
        String APPID=params.get("appId").toString();
        String APPSECRET=params.get("appSecret").toString();
        String accessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET;
        String access_token = HttpUtil.get(accessTokenUrl);
        JSONObject jsonObject= JSON.parseObject(access_token);
        String token = jsonObject.get("access_token").toString();//获取access_token
        return token;
    }


    /**
     * 调用微信开放接口subscribeMessage.send发送订阅消息    通用类
     * POST https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=ACCESS_TOKEN
     */
    public static JSONObject sendCommonSubscribeMessage(Map<String,Object> params,JSONObject data){
        JSONObject resJson =new JSONObject();
        HttpURLConnection httpConn = null;
        InputStream is = null;
        BufferedReader rd = null;
        String accessToken = null;
        String str = null;
        try
        {
            //获取token  小程序全局唯一后台接口调用凭据
            accessToken = getAccessToken(params);

            JSONObject xmlData = new JSONObject();
            xmlData.put("touser", params.get("touser"));//接收者（用户）的 openid
            xmlData.put("template_id", params.get("template_id"));//所需下发的订阅模板id
            xmlData.put("page", "pages/tarBar/index/index");//点击模板卡片后的跳转页面，仅限本小程序内的页面
            xmlData.put("miniprogram_state","formal");//跳转小程序类型：developer为开发版；trial为体验版；formal为正式版；默认为正式版
            xmlData.put("lang", "zh_CN");//进入小程序查看”的语言类型，支持zh_CN(简体中文)、en_US(英文)、zh_HK(繁体中文)、zh_TW(繁体中文)，默认为zh_CN返回值
            xmlData.put("data", data);//小程序模板数据
            URL url = new URL(
                    "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token="
                            + accessToken);
            httpConn = (HttpURLConnection)url.openConnection();
            httpConn.setRequestProperty("Host", "https://api.weixin.qq.com");
            // httpConn.setRequestProperty("Content-Length", String.valueOf(xmlData.));
            httpConn.setRequestProperty("Content-Type", "text/xml; charset=\"UTF-8\"");
            httpConn.setRequestMethod("POST");
            httpConn.setDoInput(true);
            httpConn.setDoOutput(true);
            OutputStream out = httpConn.getOutputStream();
            OutputStreamWriter osw = new OutputStreamWriter(out, "UTF-8");
            osw.write(xmlData.toString());
            osw.flush();
            osw.close();
            out.close();
            is = httpConn.getInputStream();
            rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String resStr = "";
            while ((str = rd.readLine()) != null)
            {
                resStr+=str;
            }
             resJson = JSONObject.parseObject(resStr);
        }
        catch (Exception e)
        {
            System.out.println("发送模板消息失败.." + e.getMessage());
        }
        return resJson;
    }

}