package cn.iocoder.yudao.module.system.controller.admin.util;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.cache.RedisCache;

import java.util.concurrent.TimeUnit;

public class WechatPushUtil {
    @Autowired
    private RedisUtil redisCache;
    private final String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token";
    private final String msgSecCheckUrl = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=";

    public String getSeccessToken(){
        if (redisCache.hasKey("access_token")){
            return redisCache.getCacheObject("access_token").toString();
        }else {
            String token = HttpUtil.get(tokenUrl+"?grant_type=client_credential&appid=wx102bcb3e2601f99a&secret=1111cef0b5dec92899299d25624e9adc");
            String access_token = JSONObject.parseObject(token).get("access_token").toString();
            redisCache.setCacheObject("access_token",access_token,7000, TimeUnit.SECONDS);
            return access_token;
        }
    }
    public  String msgSecCheck(String openid,String content) {
        try{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("openid",openid);
            jsonObject.put("scene",2);
            jsonObject.put("version",2);
            jsonObject.put("content",content);
            String s = JSONObject.toJSONString(jsonObject);
            String seccessToken = this.getSeccessToken();
            String post = HttpUtil.post(msgSecCheckUrl + seccessToken, s);
            return JSONObject.parseObject(JSONObject.parseObject(post).get("result").toString()).get("suggest").toString();
        }catch (Exception e){
            System.out.println(e);
        }
        return "pass";
    }
}
