package cn.axzo.msg.center.inside.notices.service.umeng;


import cn.axzo.msg.center.api.request.MsgBody4Guest;
import cn.axzo.msg.center.api.response.Message;
import cn.axzo.msg.center.inside.notices.config.PushProps;
import cn.axzo.msg.center.inside.notices.config.PushProps.ChannelConfig;
import cn.axzo.msg.center.inside.notices.config.PushProps.ChannelIds;
import cn.axzo.msg.center.inside.notices.service.umeng.android.AndroidCustomizedcast;
import cn.axzo.msg.center.inside.notices.service.umeng.ios.IOSCustomizedcast;
import cn.hutool.core.util.NumberUtil;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
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;

import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

/**
 * 友盟推送服务
 */


@Slf4j
@Component
@RefreshScope
public class UpushService {

  @Value("${upush.cmp.android.appkey}")
  private String cmpAndroidAppkey;
  @Value("${upush.cmp.android.secret}")
  private String cmpAndroidSecret;
  @Value("${upush.cmp.ios.appkey}")
  private String cmpIosAppkey;
  @Value("${upush.cmp.ios.secret}")
  private String cmpIosSecret;
  @Value("${upush.cm.android.appkey}")
  private String cmAndroidAppkey;
  @Value("${upush.cm.android.secret}")
  private String cmAndroidSecret;
  @Value("${upush.cm.ios.appkey}")
  private String cmIosAppkey;
  @Value("${upush.cm.ios.secret}")
  private String cmIosSecret;
  @Value("${upush.profile}")
  private String profile;
  @Autowired
  private PushProps pushProps;

  private String timestamp = null;
  private PushClient client = new PushClient();

  public UpushService() {
  }

  /**
   * 华为手机的消息类型
   */
  private static final Map<String, String> HUAWEI_CHANNEL_CATEGORY = Maps.newHashMap();

  /**
   * 华为荣耀的消息类型
   */
  private static final Map<String, String> HUAWEI_CHANNEL_IMPORTANCE = Maps.newHashMap();

  /**
   * 小米手机的消息类型
   */
  private static final Map<String, String> XIAOMI_CHANNEL_ID = Maps.newHashMap();

  /**
   * VIVO手机的消息类型
   */
  private static final Map<String, String> VIVO_CATEGORY = Maps.newHashMap();

  /**
   * 系统消息
   */
  private static final String SYSTEM_MESSAGE = "system";

  private static final String OP_MESSAGE = "op";

  static {
    HUAWEI_CHANNEL_CATEGORY.put(SYSTEM_MESSAGE, "SYSTEM_REMINDER");
    HUAWEI_CHANNEL_CATEGORY.put(OP_MESSAGE, "MARKETING");

    HUAWEI_CHANNEL_IMPORTANCE.put(SYSTEM_MESSAGE, "NORMAL");
    HUAWEI_CHANNEL_IMPORTANCE.put(OP_MESSAGE, "LOW");
//
//    XIAOMI_CHANNEL_ID.put(SYSTEM_MESSAGE, "NORMAL");
//    XIAOMI_CHANNEL_ID.put(OP_MESSAGE, "LOW");

    VIVO_CATEGORY.put(SYSTEM_MESSAGE, "TODO");
    VIVO_CATEGORY.put(OP_MESSAGE, "MARKETING");
  }

  public void sendAndroidCustomizedcast(Message message, MsgBody4Guest msgFromClient, com.alibaba.fastjson.JSONObject extraData)
      throws Exception {

    AndroidCustomizedcast customizedcast;
    if (msgFromClient.isForManager()) {
      customizedcast = new AndroidCustomizedcast(cmpAndroidAppkey, cmpAndroidSecret);
    } else {
      if (message.getToId().startsWith("cmp")) {
        customizedcast = new AndroidCustomizedcast(cmpAndroidAppkey, cmpAndroidSecret);
      } else {
        customizedcast = new AndroidCustomizedcast(cmAndroidAppkey, cmAndroidSecret);
      }
    }

    // TODO Set your alias here, and use comma to split them if there are multiple alias.
    // And if you have many alias, you can also upload a file containing these alias, then
    // use file_id to send customized notification.
    if ("pro".equals(profile)) {
      customizedcast.setProductionMode(true);
      if (message.getToId().startsWith("not_identity")) {
        customizedcast.setAlias("pro_" + msgFromClient.getM3(), "person");
      } else {
        customizedcast.setAlias("pro_" + message.getToId(), "pcode");
      }
    } else {
      customizedcast.setProductionMode(false);
      if(message.getToId().startsWith("not_identity")) {
        customizedcast.setAlias(msgFromClient.getM3(), "person");
      } else {
        customizedcast.setAlias(message.getToId(), "pcode");
      }

    }
    // 旧版本的M3和toId并非只有personId，4月10号旧版本不会使用，所以这里M3或者toId是number的时候才设置成personId
    if(message.getToId().startsWith("not_identity")) {
      if (NumberUtil.isNumber(msgFromClient.getM3())) {
        customizedcast.setExtraField("personId", msgFromClient.getM3());
      }
    } else if (NumberUtil.isNumber(message.getToId())) {
      customizedcast.setExtraField("personId", message.getToId());
    }
    // customizedcast.setAlias(message.getToId(), "pcode");
//		customizedcast.set
    customizedcast.setTicker("安心筑通知");
    customizedcast.setTitle(message.getTitle());
    customizedcast.setText(message.getHint());
    customizedcast.goCustomAfterOpen("cd");
    customizedcast
        .setDisplayType(
            AndroidNotification.DisplayType.NOTIFICATION);

    //厂商通道相关参数
    customizedcast.setExtraField("extra", message.getExtra());
    customizedcast.setExtraField("fromType", String.valueOf(message.getFromType()));
    customizedcast.setExtraField("fromName", message.getFromName());
    customizedcast.setExtraField("fromLogo", message.getFromLogo());
    customizedcast.setExtraField("fromGrade", message.getFromGrade());
    customizedcast.setExtraField("router", message.getRouter());
    customizedcast.setExtraField("msgId", String.valueOf(message.getMsgId()));
    customizedcast.setExtraField("terminalId", extraData.getString("terminalId"));
    String audio = message.getAudio();
    if (audio != null) {
      customizedcast.setExtraField("audio", message.getAudio());
    }
    customizedcast.setExtraField("routerType", String.valueOf(message.getRouterType()));
    customizedcast.setExtraField("conversationId", String.valueOf(message.getConversationId()));
    customizedcast.setExtraField("params", message.getParams());
    customizedcast.setExtraField("type", String.valueOf(message.getType()));
    if (msgFromClient.getOuId() != null) {
      customizedcast.setExtraField("ouId", msgFromClient.getOuId().toString());
    }
    customizedcast.setChannelActivity("cn.axzo.push.PushActivity");

    if (StringUtils.isNotBlank(msgFromClient.getPushType())) {
      customizedcast.setChannelProperties(UmengNotification.ChannelProperties.builder()
              .huaweiChannelCategory(HUAWEI_CHANNEL_CATEGORY.get(msgFromClient.getPushType()))
              .huaweiChannelImportance(HUAWEI_CHANNEL_IMPORTANCE.get(msgFromClient.getPushType()))
              .oppoChannelId(determineChannelId(pushProps.getOppoChannelConfig(), msgFromClient))
              .xiaomiChannelId(determineChannelId(pushProps.getXiaomiChannelConfig(), msgFromClient))
              .vivoCategory(VIVO_CATEGORY.get(msgFromClient.getPushType()))
              .build());
    }
    client.send(customizedcast);
  }

  private String determineChannelId(ChannelConfig cfg, MsgBody4Guest request) {
    Function<ChannelIds, String> channelSelector = channelIds -> {
      if (request.isWorkMessage()) {
        return channelIds.getWorkMessageChannelId();
      } else if (request.isOpMessage()) {
        return channelIds.getOpMessageChannelId();
      }
      log.info("can't determine channel id for request={}, channel config={}", request, cfg);
      return null;
    };
    if (request.isForManager()) {
      return channelSelector.apply(cfg.getManagerIds());
    } else {
      return channelSelector.apply(cfg.getWorkerIds());
    }
  }

  public void sendIOSCustomizedcast(Message message, MsgBody4Guest msgFromClient, com.alibaba.fastjson.JSONObject extraData)
      throws Exception {
    IOSCustomizedcast customizedcast;
    if (Objects.nonNull(msgFromClient.getAppClient()) && "cmp".equals(msgFromClient.getAppClient())) {
      customizedcast = new IOSCustomizedcast(cmpIosAppkey, cmpIosSecret);
    } else {
      if (message.getToId().startsWith("cmp")) {
        customizedcast = new IOSCustomizedcast(cmpIosAppkey, cmpIosSecret);
      } else {
        customizedcast = new IOSCustomizedcast(cmIosAppkey, cmIosSecret);
      }
    }

    // TODO Set your alias here, and use comma to split them if there are multiple alias.
    // And if you have many alias, you can also upload a file containing these alias, then
    // use file_id to send customized notification.
    if ("pro".equals(profile)) {
      customizedcast.setProductionMode(true);
      if (message.getToId().startsWith("not_identity")) {
        customizedcast.setAlias("pro_" + msgFromClient.getM3(), "person");
      } else {
        customizedcast.setAlias("pro_" + message.getToId(), "pcode");
      }
    } else {
      customizedcast.setProductionMode(false);
      if(message.getToId().startsWith("not_identity")) {
        customizedcast.setAlias(msgFromClient.getM3(), "person");
      } else {
        customizedcast.setAlias(message.getToId(), "pcode");
      }
    }
    // 旧版本的M3和toId并非只有personId，4月10号旧版本不会使用，所以这里M3或者toId是number的时候才设置成personId
    if(message.getToId().startsWith("not_identity")) {
      if (NumberUtil.isNumber(msgFromClient.getM3())) {
        customizedcast.setCustomizedField("personId", msgFromClient.getM3());
      }
    } else if (NumberUtil.isNumber(message.getToId())) {
      customizedcast.setCustomizedField("personId", message.getToId());
    }
    //厂商通道相关参数
    customizedcast.setCustomizedField("extra", message.getExtra());
/*    customizedcast.setCustomizedField("fromType", String.valueOf(message.getFromType()));
    customizedcast.setCustomizedField("fromName", message.getFromName());
    customizedcast.setCustomizedField("fromLogo", message.getFromLogo());
    customizedcast.setCustomizedField("fromGrade", message.getFromGrade());*/
    customizedcast.setCustomizedField("router", message.getRouter());
    customizedcast.setCustomizedField("routerType", String.valueOf(message.getRouterType()));
    customizedcast.setCustomizedField("type", String.valueOf(message.getType()));
    customizedcast
        .setCustomizedField("conversationId", String.valueOf(message.getConversationId()));
    customizedcast.setCustomizedField("params", message.getParams());
    customizedcast.setCustomizedField("msgId", String.valueOf(message.getMsgId()));
    customizedcast.setCustomizedField("terminalId", extraData.getString("terminalId"));
    // TODO Set your alias and alias_type here, and use comma to split them if there are multiple alias.
    // And if you have many alias, you can also upload a file containing these alias, then
    // use file_id to send customized notification.

    //customizedcast.setAlert("IOS 个性化测试");
    //alert的值设置为字典
    customizedcast.setAlert(message.getTitle(), "", message.getHint());
//    Long incr = RedisManager.incr("push:" + message.getToId());
    Long incr= 1L;
    customizedcast.setBadge(Math.toIntExact(incr));
    String audio = message.getAudio();
    if (audio != null) {
      customizedcast.setSound(audio + ".caf");
    } else {
      customizedcast.setSound("default");
    }

    if (msgFromClient.getOuId() != null) {
      customizedcast.setCustomizedField("ouId", msgFromClient.getOuId().toString());
    }
    customizedcast.setContentAvailable(1);
    // TODO set 'production_mode' to 'true' if your app is under production mode
    //customizedcast.setProductionMode();
    client.send(customizedcast);
  }


}
