package com.ruoyi.utils.wx.wecom;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class WecomUtil {


    /**
     *  获取access_token的url
     */
    private final String access_token_url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken";

    /**
     * 根据手机号获取userid的url
     */
    private final String userid_by_mobile_url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserid";

    /**
     *  发送消息的url
     */
    private final  String send_message_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send";

    private final String corpid = "ww45fb4d72c735ee1d";

    private final String corpsecret = "5x3F-AHQMO9VwpXH9_lOUX8887sqb1fUx0-5goN6U_Y";

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取access_token
     *
     * @return
     */
    public  String getToken() {
        // 参数
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("corpid", corpid);
        paramMap.put("corpsecret", corpsecret);
        String result =   HttpUtil.createRequest(Method.GET,access_token_url)
                .form(paramMap).execute().body();
        System.err.println(result);

        JSONObject jsonObject = JSONObject.parseObject(result);
        //服务断了status会有值
        Integer errcode = (Integer) jsonObject.get("errcode");
        if (errcode == 0) {
            String access_token = (String) jsonObject.get("access_token");

            // 设置过期时间
            redisTemplate.opsForValue().set("wecom_access_token", access_token, 5400, TimeUnit.SECONDS);

            return access_token;
        }
        return "";
    }

    /**
     * 根据手机号获取userid
     * @param mobile
     * @return
     */
    public String getUserid(String mobile){
        //根据手机号获取userid
        Map map = new HashMap();
        map.put("mobile", mobile);

        //获取access_token
        String token = getAccessToken();

        String body = HttpUtil.createRequest(Method.POST,userid_by_mobile_url)
                .form("access_token",token).form(map)
                .header("Content-Type", "application/json;charset=utf-8")
                .body(JSONObject.toJSONString(map))
                .execute().body();

        System.out.println(body);

        Map<String,Object> resultMap = JSONObject.parseObject(body, Map.class);

        if (resultMap.get("errcode") != null && resultMap.get("errcode").equals(0)){
            return resultMap.get("userid").toString();
        }

        return null;

    }

    private String getAccessToken(){

        //key
        String key = "wecom_access_token";

        String token = "";

        //获取access_token
        if (redisTemplate.hasKey(key)){
            token =  redisTemplate.opsForValue().get(key).toString();
        }else {
            token = getToken();
        }

        return token;
    }

    /**
     * 发送文本信息
     * @param content
     * @return
     */
    public String sendTextMessage(String content,String userid){
        Map map = new HashMap();
        map.put("touser", userid);
        map.put("toparty", "@all");
        map.put("totag", "@all");
        map.put("msgtype", "text");
        map.put("agentid", "1000003");
        Map map1 = new HashMap();
        map1.put("content", content);
        map.put("text", map1);
        String s = JSONObject.toJSONString(map);

        //获取access_token
        String token = getAccessToken();

        String result = HttpUtil.createRequest(Method.POST,send_message_url)
                .form("access_token",token)
                .header("Content-Type", "application/json;charset=utf-8")
                .body(s).execute().body();

        System.err.println(result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        Integer errcode = (Integer) jsonObject.get("errcode");
        if (errcode == 0) {
            log.info("用户:{} 发送消息成功",userid);
        }
        return null;

    }
}
