package com.ruoyi.common.jpush;

import cn.jiguang.sdk.api.PushApi;
import cn.jiguang.sdk.bean.push.PushSendParam;
import cn.jiguang.sdk.bean.push.PushSendResult;
import cn.jiguang.sdk.bean.push.audience.Audience;
import cn.jiguang.sdk.bean.push.message.notification.NotificationMessage;
import cn.jiguang.sdk.bean.push.other.CidGetResult;
import cn.jiguang.sdk.constants.ApiConstants;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Arrays;

@Service("jiGuangPushService")
public class JiGuangPushService {
    Logger log = LoggerFactory.getLogger(this.getClass());


    @Autowired
    private PushApi pushApi;

    @Value("${jpush.isDev}")
    private boolean isDev;

    public void getCidForPush() {
        CidGetResult result = pushApi.getCidForPush(10);
        log.info("result:{}", result);
    }

    @Async
    public void send(String title, String alert, String... alias) {
        PushSendParam param = new PushSendParam();
        // 通知内容
        NotificationMessage.Android android = new NotificationMessage.Android();
        android.setAlert(alert);
        android.setTitle(title);
        NotificationMessage.Android.Intent intent = new NotificationMessage.Android.Intent();
        intent.setUrl("intent:#Intent;action=android.intent.action.MAIN;end");

        android.setIntent(intent);

        NotificationMessage notificationMessage = new NotificationMessage();
        notificationMessage.setAlert(alert);
        notificationMessage.setAndroid(android);
        param.setNotification(notificationMessage);
        String[] alias1 = alias;
        if (isDev) {
            for (int i = 0 ;i<alias.length;i++) {
                alias1[i]="dev_" + alias[i];
            }
        }
        // 目标人群
        Audience audience = new Audience();
        audience.setAliasList(Arrays.asList(alias1));
//        audience.setRegistrationIdList(Arrays.asList("1104a89793af2cfc030", "1104a89793af2cfc030"));
        // 指定目标
        param.setAudience(audience);
        // 或者发送所有人
//        param.setAudience(ApiConstants.Audience.ALL);

        // 指定平台
//        param.setPlatform(Arrays.asList(Platform.android, Platform.ios));
        // 或者发送所有平台
        param.setPlatform(ApiConstants.Platform.ANDROID);

        log.info("param:{}", JSON.toJSONString(param));
        // 发送
        try {
            PushSendResult result = pushApi.send(param);
            System.out.println("Push result: " + result);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
