package com.zcloud.common.utils;

import com.alibaba.fastjson.JSONObject;
import com.zcloud.modules.sys.entity.PageData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author fangjiakai
 * @date 2025/01/22 15:44
 */
@Component
public class WxPushUtil {
    @Autowired
    private RedisUtils redisUtil;
    private static final String APPID = "wx641d6a98d89ddd03";
    private static final String SECRET = "22cd2198a03e5a1a70351f55b3d7687d";

    public static String getOpenid(String code){
        String wxLoginUrl = "https://api.weixin.qq.com/sns/oauth2/access_token";
        String param = "appid=" + APPID + "&secret=" + SECRET + "&code=" + code + "&grant_type=authorization_code";
        String jsonString = sendGet(wxLoginUrl, param);
        JSONObject json = JSONObject.parseObject(jsonString);
        System.out.println(json);
        return json.get("openid").toString();
    }
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    /*
     * 微信推送新消息
     * */
    public void pushWxNotice(String openid,String name,String content) throws Exception{
        RestTemplate restTemplate = new RestTemplate();
        try {
            Object o = redisUtil.get("WeChatOfficialAccount");
            String access_token = "";
            if (Tools.isEmpty(o)) {
                access_token = getAccess_token(APPID, SECRET);
                redisUtil.set("WeChatOfficialAccount", access_token,30);
            } else {
                access_token = o.toString();
            }
            String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + access_token;

            //拼接推送的模版
            WxMssVo wxMssVo = new WxMssVo();
            wxMssVo.setTouser(openid);//用户openid
            wxMssVo.setTemplate_id("5InweJzYRkmP9FhCE4V_X9m1_OgDGM141mLRio4AE6s");//模版id

            Map<String, TemplateData> m = new HashMap();
            TemplateData keyword1 = new TemplateData();
            keyword1.setValue("安全检查工作提醒");
            m.put("first", keyword1);

            TemplateData keyword2 = new TemplateData();
            keyword2.setValue(name);
            m.put("keyword1", keyword2);

            TemplateData keyword3 = new TemplateData();
            keyword3.setValue(DateUtil.date2Str(new Date()));
            m.put("keyword2", keyword3);

            TemplateData keyword4 = new TemplateData();
            keyword4.setValue(content);
            m.put("keyword3", keyword4);
            wxMssVo.setData(m);

            ResponseEntity<String> responseEntity =
                    restTemplate.postForEntity(url, wxMssVo, String.class);
            System.out.println("pushNotice:" + responseEntity.getBody());
        } catch (Exception e) {
            System.out.println("微信推送异常 => " + e.getMessage());
        }
    }

    /*
     * 获取access_token
     * appid和appsecret到小程序后台获取，当然也可以让小程序开发人员给你传过来
     * */
    private String getAccess_token(String appid, String appsecret) {
        //获取access_token
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                "&appid=" + appid + "&secret=" + appsecret;
        String json = restTemplate.getForObject(url, String.class);
        System.out.println("微信access_token的json信息 => " + json);
        JSONObject jsonObject = JSONObject.parseObject(json);
        return jsonObject.get("access_token").toString();
    }
}
