package cn.axzo.msg.center.notices.integration.client.impl;

import cn.axzo.msg.center.notices.common.constans.CommonConstants;
import cn.axzo.msg.center.notices.integration.client.DingDingClient;
import cn.axzo.msg.center.notices.integration.dto.response.DingMessageResponse;
import cn.axzo.msg.center.notices.integration.dto.request.At;
import cn.axzo.msg.center.notices.integration.dto.request.DingMessageRequest;
import cn.axzo.msg.center.notices.integration.dto.request.MessageText;
import cn.azxo.framework.common.utils.LogUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * 钉钉客户端实现类
 *
 * @author zhaoyong
 * @see DingDingClientImpl
 * @since 2021-07-12 12:00
 */
@Slf4j
@Service("dingDingClient")
@RefreshScope
public class DingDingClientImpl implements DingDingClient, EnvironmentAware {

  public static final String NOTIFY_VERIFICATION_CODE = "https://oapi.dingtalk.com/robot/send?access_token=ac574ebc7f9f5c197f6a58e122332689a5b5b75a3b7e4413e67b33bba4e95af6";
  
  public static final String NOTIFY_BATCH_MESSAGE = "https://oapi.dingtalk.com/robot/send?access_token=65845830bc350344abdcb2c196a0dafe100053a812ff47d65ce1f395f12ec484";

  public static final String NOTIFY_SINGLE_MESSAGE = "https://oapi.dingtalk.com/robot/send?access_token=9fb3a8a8f1c827ddb07e2e138b21351845e9381b62aa206e0c06333b0e4c95f7";

  public static final String NOTIFY_MQ_MESSAGE = "https://oapi.dingtalk.com/robot/send?access_token=bff5747081dccd33d57276ffc67a4b2d7caca550081b0d1c8e5f7af9cf473221";

  public static final String NOTIFY_CHANNEL_CALLBACK = "https://oapi.dingtalk.com/robot/send?access_token=cf51872a50040a2a7ac88397de2c8c9fad6e37059d2525ced3084d2d6781af05";

  @Resource(name = "restTemplate")
  private RestTemplate restTemplate;

  private final static String NOTIFY_MESSAGE_FORMAT = "主题:短信 Mock\n环境: %s \n手机号: %s \n模板名称: %s \n短信内容: %s";

  private final static String BATCH_MESSAGE_FORMAT = "主题:批量短信发送失败\n环境: %s \n消息模板号: %s \n批次号: %s \n错误信息: %s";

  private final static String SINGLE_MESSAGE_FORMAT = "主题:单条短信发送失败\n环境: %s \n消息模板号: %s \n请求号: %s \n错误信息: %s";

  private final static String MQ_MESSAGE_FORMAT = "主题:RocketMQ异常\n环境: %s \n错误信息: %s";

  private final static String CHANNEL_CALLBACK_FORMAT = "主题:渠道回调异常\n环境: %s \n渠道名称: %s \n回调信息: %s \n错误信息: %s";

  private Environment environment;

  @Value("${dingDing.at:false}")
  private boolean dingDingAt;

  @Override
  public void notifyMockMessage(String mobile, String title, String param) {
    if (!dingDingAt) {
      return;
    }
    try {
      DingMessageRequest request = new DingMessageRequest();
      request.setMsgtype(CommonConstants.DING_TEXT_MESSAGE_TYPE);
      MessageText text = new MessageText();
      String content = String.format(NOTIFY_MESSAGE_FORMAT, getProfile(), mobile, title, param);
      text.setContent(content);
      request.setText(text);
      if(dingDingAt){
        At at = new At();
        at.setAtMobiles(Lists.newArrayList(mobile));
        request.setAt(at);
      }
      log.info("[mns -> ding] DingDingClientImpl.notify request param is {}", JSON.toJSONString(request));
      DingMessageResponse response = restTemplate.postForObject(NOTIFY_VERIFICATION_CODE, request, DingMessageResponse.class);
      log.info("[mns <- ding] DingDingClientImpl.notify response is {}", JSON.toJSONString(response));
    } catch (Exception e) {
      LogUtil.error("[mns <- ding] DingDingClientImpl.notify response is error", e);
    }
  }

  @Override
  public void notifySingleMessage(String templateNo, String requestNo, String errorMsg) {
    try {
      DingMessageRequest request = new DingMessageRequest();
      request.setMsgtype(CommonConstants.DING_TEXT_MESSAGE_TYPE);
      MessageText text = new MessageText();
      String content = String.format(SINGLE_MESSAGE_FORMAT, getProfile(), templateNo, requestNo, errorMsg);
      text.setContent(content);
      request.setText(text);
      At at = new At();
      at.setAtMobiles(Lists.newArrayList("13585844124", "15928328930", "17605414211"));
      request.setAt(at);
      log.info("[mns -> ding] DingDingClientImpl.notifySingleMessage request param is {}", JSON.toJSONString(request));
      DingMessageResponse response = restTemplate.postForObject(NOTIFY_SINGLE_MESSAGE, request, DingMessageResponse.class);
      log.info("[mns <- ding] DingDingClientImpl.notifySingleMessage response is {}", JSON.toJSONString(response));
    } catch (Exception e) {
      LogUtil.error("[mns <- ding] DingDingClientImpl.notifySingleMessage response is error", e);
    }
  }

  @Override
  public void notifyBatchMessage(String templateNo, String batchNo, String errorMsg) {
    try {
      DingMessageRequest request = new DingMessageRequest();
      request.setMsgtype(CommonConstants.DING_TEXT_MESSAGE_TYPE);
      MessageText text = new MessageText();
      String content = String.format(BATCH_MESSAGE_FORMAT, getProfile(), templateNo, batchNo, errorMsg);
      text.setContent(content);
      request.setText(text);
      At at = new At();
      at.setAtMobiles(Lists.newArrayList("13585844124", "15928328930", "17605414211"));
      request.setAt(at);
      log.info("[mns -> ding] DingDingClientImpl.notifyBatchMessage request param is {}", JSON.toJSONString(request));
      DingMessageResponse response = restTemplate.postForObject(NOTIFY_BATCH_MESSAGE, request, DingMessageResponse.class);
      log.info("[mns <- ding] DingDingClientImpl.notifyBatchMessage response is {}", JSON.toJSONString(response));
    } catch (Exception e) {
      LogUtil.error("[mns <- ding] DingDingClientImpl.notifyBatchMessage response is error", e);
    }
  }

  @Override
  public void notifyChannelCallback(String channelName, String callbackData, String errorMsg) {
    try {
      DingMessageRequest request = new DingMessageRequest();
      request.setMsgtype(CommonConstants.DING_TEXT_MESSAGE_TYPE);
      MessageText text = new MessageText();
      String content = String.format(CHANNEL_CALLBACK_FORMAT, getProfile(), channelName, callbackData, errorMsg);
      text.setContent(content);
      request.setText(text);
      At at = new At();
      at.setAtMobiles(Lists.newArrayList("13585844124", "15928328930", "17605414211"));
      request.setAt(at);
      log.info("[mns -> ding] DingDingClientImpl.notifyChannelCallback request param is {}", JSON.toJSONString(request));
      DingMessageResponse response = restTemplate.postForObject(NOTIFY_CHANNEL_CALLBACK, request, DingMessageResponse.class);
      log.info("[mns <- ding] DingDingClientImpl.notifyChannelCallback response is {}", JSON.toJSONString(response));
    } catch (Exception e) {
      LogUtil.error("[mns <- ding] DingDingClientImpl.notifyChannelCallback response is error", e);
    }
  }

  @Override
  public void notifyRocketMqError(String errorMsg) {
    try {
      DingMessageRequest request = new DingMessageRequest();
      request.setMsgtype(CommonConstants.DING_TEXT_MESSAGE_TYPE);
      MessageText text = new MessageText();
      String content = String.format(MQ_MESSAGE_FORMAT, getProfile(), errorMsg);
      text.setContent(content);
      request.setText(text);
      At at = new At();
      at.setAtMobiles(Lists.newArrayList("13585844124", "15928328930", "17605414211"));
      request.setAt(at);
      log.info("[mns -> ding] DingDingClientImpl.notifyRocketMqError request param is {}", JSON.toJSONString(request));
      DingMessageResponse response = restTemplate.postForObject(NOTIFY_MQ_MESSAGE, request, DingMessageResponse.class);
      log.info("[mns <- ding] DingDingClientImpl.notifyRocketMqError response is {}", JSON.toJSONString(response));
    } catch (Exception e) {
      LogUtil.error("[mns <- ding] DingDingClientImpl.notifyRocketMqError response is error", e);
    }
  }

  @Override
  public void setEnvironment(Environment environment) {
    this.environment = environment;
  }

  private String getProfile() {
    String[] activeProfiles = environment.getActiveProfiles();
    if(ArrayUtils.isEmpty(activeProfiles)) {
      return CommonConstants.DEFAULT_ENV;
    }
    return activeProfiles[0];
  }

}
