package com.persagy.dmp.sender.service.impl;

import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosAlert;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import com.persagy.dmp.message.model.vo.MessageVO;
import com.persagy.dmp.message.model.vo.SenderRegister;
import com.persagy.dmp.sender.service.IMessageSender;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 短信消息
 * @author Charlie Yu
 * @date 2021-05-24
 */
@Service
@Slf4j
public class SmsMessageSender implements IMessageSender {

    private String appKey;
    private String masterSecret;

   // public static final String push_notification = "https://api.jpush.cn/v3/push";

    @Override
    public boolean initParam(SenderRegister register) {
        this.appKey = register.getAccessKey();
        this.masterSecret = register.getAccessSecret();
        return true;
    }

    @Override
    public void send(MessageVO vo) {
        PushPayload jpushMessage = buildPushRequest(vo);
        this.doSend(jpushMessage);
    }

    /**
     * 构建推送参数
     * @param vo
     * @return
     */
    private PushPayload buildPushRequest(MessageVO vo) {
        PushPayload.Builder builder = PushPayload.newBuilder();
        builder.setPlatform(Platform.android_ios());
        builder.setAudience(Audience.alias(vo.getUserId()));
        Notification.Builder notificationBuilder = Notification.newBuilder();
        //android 参数设置
        AndroidNotification.Builder androidNotifiBuilder =
                AndroidNotification.newBuilder()
                        .setTitle(vo.getTitle())
                        .setAlert(vo.getContent());
        notificationBuilder.addPlatformNotification(androidNotifiBuilder.build());

        //ios 参数设置
        IosAlert alert = IosAlert.newBuilder()
                .setTitleAndBody(vo.getTitle(), null, vo.getContent())
                .build();
        notificationBuilder.addPlatformNotification(IosNotification.newBuilder()
                .setAlert(alert)
                .setContentAvailable(true)
                .setMutableContent(true)
                //.addExtras(vo.getExtras())
                .autoBadge()
                .build());

        return builder.setNotification(notificationBuilder.build())
                .setOptions(Options.newBuilder()
                        .setApnsProduction(false)
                        .setTimeToLive(24 * 60 * 60 * 2)
                        .build())
                .build();
    }


    /**
     * 执行发送
     * 5次重试
     * @param pushPayload
     * @return 返回的消息Id，为空表示执行失败
     */
    private String doSend(PushPayload pushPayload) {
        int count = 1;
        // 最多重试5次
        while (count <= 5) {
            try {
                JPushClient jpushClient = new JPushClient(masterSecret, appKey);
                PushResult result = jpushClient.sendPush(pushPayload);
                log.info("Sms发送结果:{}"+result);
                if (result.isResultOK()) {
                    //发送成功，返回消息ID
                    return String.valueOf(result.msg_id);
                } else {
                    //发送失败
                    if (result.error.getCode() == 2002) {
                        log.warn("极光API调用频率超出限制");
                    } else if (result.error.getCode() == 1011) {
                        log.info("没有设备满足推送目标，可能是因为没有登录");
                    } else {
                        String errorMessage = "极光API出错, statusCode=" + result.getResponseCode()
                                + ", code=" + result.error.getCode()
                                + ", msg=" + result.error.getMessage();
                        log.error(errorMessage);
                    }
                }
                return String.valueOf(result.msg_id);
            } catch (Exception e) {
                log.error("{}:{},重试第{}次", pushPayload.getSendno(), e.getMessage(), count);
                count++;
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException interruptedException) {
                }
                continue;
            }
        }
        return null;
    }

}
