package cn.axzo.msg.center.inside.notices.utils;

import cn.axzo.msg.center.common.redis.AxzoJedisManager;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request.Msg;
import com.dingtalk.api.request.OapiMessageCorpconversationAsyncsendV2Request.Text;
import com.dingtalk.api.request.OapiV2UserGetbymobileRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiMessageCorpconversationAsyncsendV2Response;
import com.dingtalk.api.response.OapiV2UserGetbymobileResponse;
import com.taobao.api.ApiException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

/**
 * 钉钉消息推送工具类
 * <p>
 * 使用说明: 1. 登录钉钉开放平台,选择公司.地址:https://open-dev.dingtalk.com/
 * <p>
 * 2. 在首页点击立即创建应用, 选择 H5 微应用接即可,并配置应用名称/应用描述. 开发方式选择"企业自主开发"
 * <p>
 * 3. 选择创建的应用->开发管理,并设置服务器出口IP.(及应用调用钉钉开放接口的授权IP)
 * <p>
 * 4. 选择创建的应用->权限管理,并搜索"根据手机号姓名获取成员信息的接口访问权限"即可.
 * <p>
 * 5. 在 Nacos 中配置应用的 AgentId,Appkey,AppSecret.
 *
 * @author: wangli
 * @date: 2022/1/21 16:26
 */
@Component
@RefreshScope
public class DingTalkUtilWangli {

  @Autowired
  private AxzoJedisManager jedisManager;
  /**
   * 推送工作消息地址
   */
  private static final String PUSH_MSG_URL = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2";
  /**
   * 根据手机号获取用户id
   */
  private static final String GET_USERID_BY_MOBILE_URL = "https://oapi.dingtalk.com/topapi/v2/user/getbymobile";
  /**
   * 获取企业内部应用的 accessToken
   */
  private static final String GET_TOKEN = "https://oapi.dingtalk.com/gettoken";

  @Value("${dingtalk.agentId:1447949753}")
  private Long AgentId;
  @Value("${dingtalk.AppKey:dinghkmjx7tpy9jkxvyh}")
  private String AppKey;
  @Value("${dingtalk.AppSecret:Xtf-qpTA96vRBSVeiFbmPVFVgflW_F0K5En17qjJHM6qufSJqOzX2u57qe5ME1zM}")
  private String AppSecret;
  private String DINGTALK_TOKEN = "DINGTALK-TOKEN";

  public void sendMsg(String mobile, String msg) {
    getUserId(mobile);
    try {
      DingTalkClient client = new DefaultDingTalkClient(PUSH_MSG_URL);
      OapiMessageCorpconversationAsyncsendV2Request req = new OapiMessageCorpconversationAsyncsendV2Request();
      req.setAgentId(AgentId);
      req.setToAllUser(false);
      req.setUseridList(getUserId(mobile));
      Msg innerMsg = new Msg();
      innerMsg.setMsgtype("text");
      Text text = new Text();
      text.setContent(msg);
      innerMsg.setText(text);
      req.setMsg(innerMsg);
      OapiMessageCorpconversationAsyncsendV2Response rsp = client.execute(req, getToken());
      System.out.println(rsp.getBody());
    } catch (ApiException e) {
      e.printStackTrace();
    }
  }

  private String getUserId(String mobile) {
    String userId = null;
    try {
      DingTalkClient client = new DefaultDingTalkClient(GET_USERID_BY_MOBILE_URL);
      OapiV2UserGetbymobileRequest req = new OapiV2UserGetbymobileRequest();
      req.setMobile(mobile);
      OapiV2UserGetbymobileResponse rsp = client.execute(req, getToken());
      userId = rsp.getResult().getUserid();
    } catch (ApiException e) {
      e.printStackTrace();
    }
    return userId;
  }

  private String getToken() {
    return jedisManager.get(DINGTALK_TOKEN, () -> {
      String token = null;
      try {
        DingTalkClient client = new DefaultDingTalkClient(GET_TOKEN);
        OapiGettokenRequest req = new OapiGettokenRequest();
        req.setHttpMethod("GET");
        req.setAppkey(AppKey);
        req.setAppsecret(AppSecret);
        OapiGettokenResponse rsp = client.execute(req);
        token = rsp.getAccessToken();
      } catch (ApiException e) {
        e.printStackTrace();
      }
      return token;
    }, 7000);
  }

}
